diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 48270359d9d49f9ea7d7111b021cd8b81da3df82..3bafb0bc097f0277f88ff4489c2731afdad6569e 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -92,7 +92,7 @@ After the preceding code is executed, the **startAbility()** API is called to st - If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. - If the Service ability is running, the system directly calls **onCommand()** on the Service ability. -The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability-applying-only-to-system-applications). +The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability). ```javascript import featureAbility from '@ohos.ability.featureAbility'; diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 4c293fdee7114866ebd969151c0914d29a144941..62bf66fd7cabb7e30c765126ddacba639bd951f5 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -9,15 +9,15 @@ You can use APIs provided in the following table to obtain the system language a ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | -| ohos.i18n | getSystemRegion(): string | Obtains the system region. | -| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | -| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | -| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | -| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | -| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | +| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | +| ohos.i18n | getSystemRegion(): string | Obtains the system region. | +| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | +| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | +| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | +| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | +| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | ### How to Develop @@ -26,7 +26,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). - + ```js var language = i18n.getSystemLanguage(); ``` @@ -42,7 +42,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Obtain the system locale. Call the **getSystemLocale** method to obtain the system locale. - + ```js var locale = i18n.getSystemLocale(); ``` @@ -51,7 +51,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **isRTL** method to check whether the locale's language is RTL. - + ```js var rtl = i18n.isRTL("zh-CN"); ``` @@ -67,7 +67,7 @@ You can use APIs provided in the following table to obtain the system language a 6. Obtain the localized display of a language. Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - + ```js var language = "en"; var locale = "zh-CN"; @@ -78,7 +78,7 @@ You can use APIs provided in the following table to obtain the system language a 7. Obtain the localized display of a country. Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - + ```js var country = "US"; var locale = "zh-CN"; @@ -116,7 +116,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. - + ```js var calendar = i18n.getCalendar("zh-CN", "gregory"); ``` @@ -135,7 +135,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Set the year, month, day, hour, minute, and second for the **Calendar** object. Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. - + ```js calendar.set(2021, 12, 21, 6, 0, 0) ``` @@ -144,7 +144,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. - + ```js calendar.setTimeZone("Asia/Shanghai"); var timezone = calendar.getTimeZone(); @@ -163,7 +163,7 @@ You can use APIs provided in the following table to obtain the system language a 6. Set and obtain the minimum count of days in the first week for the **Calendar** object. Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. - + ```js calendar.setMinimalDaysInFirstWeek(3); var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); @@ -173,7 +173,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. - + ```js var localizedName = calendar.getDisplayName("zh-CN"); ``` @@ -196,11 +196,11 @@ You can use APIs provided in the following table to obtain the system language a ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | -| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | -| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | +| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | +| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | +| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | ### How to Develop @@ -209,7 +209,7 @@ You can use APIs provided in the following table to obtain the system language a Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. - + ```js var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); ``` @@ -223,7 +223,7 @@ You can use APIs provided in the following table to obtain the system language a 3. Format a phone number. Call the **format** method of **PhoneNumberFormat** to format the input phone number. - + ```js var formattedNumber = phoneNumberFormat.format("15812341234"); ``` @@ -236,15 +236,15 @@ The **unitConvert** API is provided to help you implement measurement conversion ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | +| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | ### How to Develop 1. Convert a measurement unit. - Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert8) method to convert a measurement unit and format the display result. + Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) method to convert a measurement unit and format the display result. ```js @@ -254,7 +254,7 @@ The **unitConvert** API is provided to help you implement measurement conversion var locale = "en-US"; var style = "long"; i18n.Util.unitConvert(fromUtil, toUtil, number, locale, style); - ``` + ``` ## Alphabet Index @@ -278,7 +278,7 @@ The **unitConvert** API is provided to help you implement measurement conversion Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. - + ```js var indexUtil = i18n.getInstance("zh-CN"); ``` @@ -294,7 +294,7 @@ The **unitConvert** API is provided to help you implement measurement conversion 3. Add an index. Call the **addLocale** method to add the alphabet index of a new locale to the current index list. - + ```js indexUtil.addLocale("ar") ``` @@ -302,7 +302,7 @@ The **unitConvert** API is provided to help you implement measurement conversion 4. Obtain the index of a string. Call the **getIndex** method to obtain the alphabet index of a string. - + ```js var text = "access index"; indexUtil.getIndex(text); @@ -336,7 +336,7 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **getLineInstance** method to instantiate a **BreakIterator** object. - + ```js var locale = "en-US" var breakIterator = i18n.getLineInstance(locale); @@ -357,7 +357,7 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. - + ```js var pos = breakIterator.current(); ``` @@ -383,7 +383,9 @@ When a text is displayed in more than one line, [BreakIterator8](../reference/ap Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. - + ```js var isboundary = breakIterator.isBoundary(5); ``` + + ``` \ No newline at end of file diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index 424320dcc17f3dc0eb6d3e30970869da83874408..540e8dbf89029df9daa4825c5883eb7d41271412 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -13,13 +13,13 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | -| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | -| ohos.intl | toString(): string | Converts locale information into a string. | -| ohos.intl | maximize(): Locale | Maximizes locale information. | -| ohos.intl | minimize(): Locale | Minimizes locale information. | +| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | +| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | +| ohos.intl | toString(): string | Converts locale information into a string. | +| ohos.intl | maximize(): Locale | Maximizes locale information. | +| ohos.intl | minimize(): Locale | Minimizes locale information. | ### How to Develop @@ -81,13 +81,13 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to f ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | +| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | +| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | +| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | ### How to Develop @@ -144,12 +144,12 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to forma ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | -| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | +| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | +| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | ### How to Develop @@ -195,12 +195,12 @@ Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **Collator** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | -| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | -| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | +| ohos.intl | constructor()8+ | Creates a **Collator** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | +| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | +| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | ### How to Develop @@ -214,7 +214,7 @@ Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings var collator = new intl.Collator(); ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9). ```js var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); @@ -246,11 +246,11 @@ Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determ ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | -| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | +| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | +| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | ### How to Develop @@ -264,7 +264,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determ var pluralRules = new intl.PluralRules(); ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9). ```js var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); @@ -287,13 +287,13 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) ### Available APIs -| Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | +| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | +| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | +| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | +| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | +| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | ### How to Develop @@ -307,7 +307,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) var relativeTimeFormat = new intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9). ```js var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); diff --git a/en/application-dev/reference/apis/js-apis-application-StartOptions.md b/en/application-dev/reference/apis/js-apis-application-StartOptions.md index d1d7416500d37ab61523633f3880670ad8b98779..39f44f65437b6b91ce457228fa12153d10aed3e6 100644 --- a/en/application-dev/reference/apis/js-apis-application-StartOptions.md +++ b/en/application-dev/reference/apis/js-apis-application-StartOptions.md @@ -19,5 +19,5 @@ import StartOptions from '@ohos.application.StartOptions'; | Name| Readable| Writable| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -------- | -| [windowMode](js-apis-application-abilityConstant.md#AbilityConstant.WindowMode) | Yes| No| number | No| Window mode.| +| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | Yes| No| number | No| Window mode.| | displayId | Yes| No| number | No| Display ID.| diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 135400833c36005e1504b32f56f353cd2f271e40..2d7e9fab8a62e7d68dae92e66359a2704414bc01 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -1,6 +1,7 @@ # Battery Info ->![](../../public_sys-resources/icon-note.gif) **NOTE:** +>**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 Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. @@ -25,7 +26,7 @@ Describes battery information. | batterySOC | number | Yes | No | Battery state of charge (SoC) of the current device, in unit of percentage. | | chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device. | | healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the current device. | -| pluggedType | [BatteryPluggedType](#batterypluggertype) | Yes | No | Charger type of the current device. | +| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. | | voltage | number | Yes | No | Battery voltage of the current device, in unit of microvolt. | | technology | string | Yes | No | Battery technology of the current device. | | batteryTemperature | number | Yes | No | Battery temperature of the current device, in unit of 0.1°C. | @@ -43,12 +44,12 @@ var batterySoc = batteryInfo.batterySOC; Enumerates charger types. -| Name | Default Value | Description | -| -------- | ------------- | ---------------- | -| NONE | 0 | Unknown type | -| AC | 1 | AC charger | -| USB | 2 | USB charger | -| WIRELESS | 3 | Wireless charger | +| Name | Default Value | Description | +| -------- | ------------- | ----------------- | +| NONE | 0 | Unknown type. | +| AC | 1 | AC charger. | +| USB | 2 | USB charger. | +| WIRELESS | 3 | Wireless charger. | ## BatteryChargeState diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 3c908fabdc24cccc6f5949c9d5add8da88a08d01..b998d06bc0ca9900249144012f30e1230a0598f1 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -500,6 +500,7 @@ Returns properties reflecting the locale and collation options of a **Collator** | [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| **Example** + ``` var collator = new Intl.Collator("zh-Hans"); var options = collator.resolvedOptions(); diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md index 658082d2690c0ab00d76959a1a7ce1c97574ce5d..10f08e3b588e7c03d44ef3eac6ade39a42a5febe 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -29,15 +29,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description| - | ---------- | ------ | ---- | ---- | - | volumeUuid | string | Yes | UUID of the volume.| +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| volumeUuid | string | Yes | UUID of the volume.| **Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<number> | Promise used to return the total size of the volume.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<number> | Promise used to return the total size of the volume.| **Example** @@ -66,10 +66,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | -------------------------- | - | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | -------------------------- | +| volumeUuid | string | Yes | UUID of the volume. | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| **Example** @@ -97,15 +97,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description| - | ---------- | ------ | ---- | ---- | - | volumeUuid | string | Yes | UUID of the volume.| +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| volumeUuid | string | Yes | UUID of the volume.| **Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<number> | Promise used to return the available space of the volume.| +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the available space of the volume.| **Example** @@ -135,10 +135,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | ---------------------------- | - | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ---------------------------- | +| volumeUuid | string | Yes | UUID of the volume. | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| **Example** @@ -166,15 +166,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ----------- | ------ | ---- | -------- | - | packageName | string | Yes | Bundle name of the application.| +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | -------- | +| packageName | string | Yes | Bundle name of the application.| **Return value** - | Type | Description | - | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| +| Type | Description | +| ------------------------------------------ | -------------------------- | +| Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| **Example** @@ -203,10 +203,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | packageName | string | Yes | Bundle name of the application.| - | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------ | +| packageName | string | Yes | Bundle name of the application.| +| callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| **Example** @@ -228,9 +228,9 @@ Asynchronously obtains space information of the current third-party application. **Return value** - | Type | Description | - | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | +| Type | Description | +| ------------------------------------------ | -------------------------- | +| Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | **Example** @@ -249,9 +249,9 @@ Asynchronously obtains space information of the current third-party application. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------ | +| callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | **Example** @@ -294,9 +294,9 @@ This is a system API and cannot be called by third-party applications. **Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<number> | Promise used to return the total space of the built-in memory card. | +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the total space of the built-in memory card. | **Example** @@ -321,9 +321,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------------ | ---- | ------------------------ | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------ | ---- | ------------------------ | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| **Example** @@ -351,9 +351,9 @@ This is a system API and cannot be called by third-party applications. **Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<number> | Promise used to return the available space of the built-in memory card.| +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the available space of the built-in memory card.| **Example** @@ -379,9 +379,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------------------------------------ | ---- | ------------------------- | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------- | +| callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| **Example** @@ -408,9 +408,9 @@ This is a system API and cannot be called by third-party applications. **Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<number> | Promise used to return the system space obtained.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<number> | Promise used to return the system space obtained.| **Example** @@ -438,9 +438,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | -------------------------- | - | callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | -------------------------- | +| callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| **Example** @@ -467,15 +467,15 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description| - | ---------- | ------ | ---- | ---- | - | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| +| Name | Type | Mandatory| Description| +| ---------- | ------ | ---- | ---- | +| userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| **Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<[StorageStats](#StorageStats)> | Promise used to return the information obtained.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<[StorageStats](#storagestats9)> | Promise used to return the information obtained.| **Example** @@ -504,10 +504,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------------------------------------ | ---- | -------------------------- | - | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | - | callback | callback:AsyncCallback<[StorageStats](#StorageStats)> | Yes | Callback invoked to return the information obtained.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | -------------------------- | +| userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | +| callback | callback:AsyncCallback<[StorageStats](#storagestats9)> | Yes | Callback invoked to return the information obtained.| **Example** diff --git a/en/application-dev/reference/arkui-js/js-components-svg-animate.md b/en/application-dev/reference/arkui-js/js-components-svg-animate.md index 751dbe4adb724775bc0cd287b47f29c25cbd2339..f214967694d8534769932d1b1f0e9d95dc54e61f 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-animate.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-animate.md @@ -1,19 +1,20 @@ -# animate +# animate The **** component is used to apply animation to an **** component. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** +>![](../../public_sys-resources/icon-note.gif) **NOTE** +> >This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +## Required Permissions None -## Child Components +## Child Components Not supported -## Attributes +## Attributes

Name

@@ -193,7 +194,7 @@ Not supported
-## Example +## Example ``` diff --git a/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md b/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md deleted file mode 100644 index 029a61c9f47bfb216d507b70845c3fc6877ca697..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-ts/ts-interpolation-calculation.md +++ /dev/null @@ -1,277 +0,0 @@ -# Interpolation Calculation - -Interpolation calculation can be implemented to set the animation interpolation curve, which is used to construct the step curve, cubic Bezier curve, and spring curve objects. - -> **NOTE** -> -> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```js -import Curves from '@ohos.curves' -``` - - -## Curves.initCurve9+ - -initCurve(curve?: Curve): ICurve - - -Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter. - -**Parameters** - -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve | [Curve](#curve-enums)| No | Curve.Linear | Curve type.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Interpolation object of the curve.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. -``` - - -## Curves.stepsCurve9+ - -stepsCurve(count: number, end: boolean): ICurve - - -Constructs a step curve object. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | Yes | Number of steps. Must be a positive integer. | -| end | boolean | Yes | Whether the step change occurs at the start or end point of each interval.
- **true**: The step change occurs at the end point.
- **false**: The step change occurs at the start point.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.stepsCurve(9, true) // Create a step curve. -``` - - -## Curves.cubicBezierCurve9+ - -cubicBezierCurve(x1: number, y1: number, x2: number, y2: number): ICurve - - -Constructs a third-order Bezier curve object. The curve value must be between 0 and 1. - - -**Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------- | -| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.| -| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.| -| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.| -| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.| - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve. -``` - - -## Curves.springCurve9+ - -springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve - - -Constructs a spring curve object. - - -**Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.| -| mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| -| stiffness | number | Yes | 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 | number | Yes | Damping. It is a pure number and has no real physical meaning. 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.| - - -**Return value** - -| Type | Description | -| ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve object.| - - -**Example** - -```ts -import Curves from '@ohos.curves' -Curves.springCurve(100, 1, 228, 30) // Create a spring curve. -``` - - -## ICurve - - -### interpolate - -interpolate(fraction: number): number - - -Calculation function of the interpolation curve. Passing a normalized time parameter to this function returns the current interpolation. - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | -------------------------------------------- | -| fraction | number | Yes | Current normalized time. The value ranges from 0 to 1.| - -**Return value** - -| Type | Description | -| ------ | ------------------------------------ | -| number | The curve interpolation corresponding to the normalized time point is returned.| - -**Example** - -```ts -import Curves from '@ohos.curves' -let curve = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. -let value: number = curve.interpolate(0.5) // Calculate the interpolation for half of the time. -``` - - -## Curves.init(deprecated) - -init(curve?: Curve): string - - -Implements initialization to create a curve object based on the input parameter. This API is deprecated since API version 9. Use [Curves.initCurve](#curvesinitcurve9) instead. - -**Parameters** - -| Name| Type | Mandatory| Default Value | Description | -| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | -| curve |[Curve](#curve-enums)| No | Curve.Linear | Curve type.| - - -## Curves.steps(deprecated) - -steps(count: number, end: boolean): string - - -Constructs a step curve object. This API is deprecated since API version 9. Use [Curves.stepsCurve](# curvesstepscurve9) instead. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ----| ------------------------------------------------------------ | -| count | number | Yes | Number of steps. Must be a positive integer. | -| end | boolean | Yes | Whether the step change occurs at the start or end of each interval.
- **true**: The step change occurs at the end point.
- **false**: The step change occurs at the start point.| - - -## Curves.cubicBezier(deprecated) - -cubicBezier(x1: number, y1: number, x2: number, y2: number): string - - -Constructs a cubic Bezier curve object. The curve value must range from 0 to 1. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. - - -**Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------- | -| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.| -| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.| -| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.| -| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.| - - -## Curves.spring(deprecated) - -spring(velocity: number, mass: number, stiffness: number, damping: number): string - - -Constructs a spring curve object. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.| -| mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| -| stiffness | number | Yes | 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 | number | Yes | Damping. It is a pure number and has no real physical meaning. 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.| - - -## Curve - -| Name | Description | -| ------------------- | ---------------------------------------- | -| Linear | The animation speed keeps unchanged. | -| Ease | The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.| -| EaseIn | The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.| -| EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.| -| EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.| -| FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0).| -| LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0).| -| FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0).| -| ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).| -| Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).| -| Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).| -| Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).| -| Friction | The animation uses the friction cubic-bezier curve (0.2, 0.0, 0.2, 1.0).| - - -## Example - -```ts -// xxx.ets -import Curves from '@ohos.curves' -@Entry -@Component -struct ImageComponent { - @State widthSize: number = 200 - @State heightSize: number = 200 - build() { - Column() { - Text() - .margin({top:100}) - .width(this.widthSize) - .height(this.heightSize) - .backgroundColor(Color.Red) - .onClick(()=> { - let curve = Curves.cubicBezierCurve(0.25, 0.1, 0.25, 1.0); - this.widthSize = curve.interpolate(0.5) * this.widthSize; - this.heightSize = curve.interpolate(0.5) * this.heightSize; - }) - .animation({duration: 2000 , curve: Curves.stepsCurve(9, true)}) - }.width("100%").height("100%") - } -} -``` -![en-us_image_0000001212058456](figures/en-us_image_0000001212058456.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md b/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md deleted file mode 100644 index 34f1738c2085bd8c77e6c69f43845a37bbc98985..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-ts/ts-matrix-transformation.md +++ /dev/null @@ -1,441 +0,0 @@ -# Matrix Transformation - -Matrix transformation enables you to rotate, scale, skew, or translate an image. - -> **NOTE** -> -> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```ts -import matrix4 from '@ohos.matrix4' -``` - - -## matrix4.init - -init(array: Array<number>): Matrix4Transit - - -Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------------- | ---- | ------------------------------------------------------------ | -| array | Array<number> | Yes | A number array whose length is 16 (4 x 4). For details, see **array**.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | 4x4 matrix object created based on the input parameter.| - -**array** - -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | -------------------- | -| m00 | number | Yes | Scaling value of the x-axis. Defaults to **1** for the identity matrix. | -| m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. | -| m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. | -| m03 | number | Yes | Meaningless. | -| m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. | -| m11 | number | Yes | Scaling value of the y-axis. Defaults to **1** for the identity matrix. | -| m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. | -| m13 | number | Yes | Meaningless. | -| m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. | -| m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. | -| m22 | number | Yes | Scaling value of the z-axis. Defaults to **1** for the identity matrix. | -| m23 | number | Yes | Meaningless. | -| m30 | number | Yes | Translation value of the x-axis, in px. Defaults to **0** for the identity matrix.| -| m31 | number | Yes | Translation value of the y-axis, in px. Defaults to **0** for the identity matrix.| -| m32 | number | Yes | Translation value of the z-axis, in px. Defaults to **0** for the identity matrix.| -| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. | - -**Example** - -```ts -import matrix4 from '@ohos.matrix4' -// Create a 4x4 matrix. -let matrix = matrix4.init([1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0]) -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width("40%") - .height(100) - .transform(matrix) - } - } -} -``` - - -## matrix4.identity - -identity(): Matrix4Transit - - -Matrix initialization function. Can return an identity matrix object. - -**Return value** - -| Type | Description | -| -------------- | -------------- | -| Matrix4Transit | Identity matrix object.| - -**Example** - -```ts -// The effect of matrix 1 is the same as that of matrix 2. -import matrix4 from '@ohos.matrix4' -let matrix1 = matrix4.init([1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0]) -let matrix2 = matrix4.identity() -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width("40%") - .height(100) - .transform(matrix1) - Image($r("app.media.zh")) - .width("40%") - .height(100) - .margin({ top: 150 }) - .transform(matrix2) - } - } -} -``` - - -## matrix4.copy - -copy(): Matrix4Transit - - -Matrix copy function, which is used to copy the current matrix object. - -**Return value** - -| Type | Description | -| -------------- | -------------------- | -| Matrix4Transit | Copy object of the current matrix.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = Matrix4.identity().translate({x:100}) - private matrix2 = this.matrix1.copy().scale({x:2}) - - build() { - Column() { - Image($r("app.media.bg1")) - .width("40%") - .height(100) - .transform(this.matrix1) - Image($r("app.media.bg2")) - .width("40%") - .height(100) - .margin({top:50}) - .transform(this.matrix2) - } - } -} -``` - -![en-us_image_0000001256858419](figures/en-us_image_0000001256858419.png) - - -## Matrix4 - - -### combine - -combine(matrix: Matrix4): Matrix4Transit - - -Matrix overlay function, which is used to overlay the effects of two matrices to generate a new matrix object. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------ | -| matrix | Matrix4 | Yes | Matrix object to be overlaid.| - -**Return value** - -| Type | Description | -| -------------- | ------------------ | -| Matrix4Transit | Object after matrix overlay.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().translate({x:200}).copy() - private matrix2 = matrix4.identity().scale({x:2}).copy() - - build() { - Column() { - // Before matrix transformation - Image($r("app.media.icon")) - .width("40%") - .height(100) - .margin({top:50}) - // Translate the x-axis by 200px, and then scale down the x-axis twice. - Image($r("app.media.icon")) - .transform(this.matrix1.combine(this.matrix2)) - .width("40%") - .height(100) - .margin({top:50}) - } - } -} -``` - -![en-us_image_0000001212378428](figures/en-us_image_0000001212378428.png) - - -### invert - -invert(): Matrix4Transit - - -Matrix inverse function. Can return an inverse matrix of the current matrix object, that is, get an opposite effect. - -**Return value** - -| Type | Description | -| -------------- | ---------------------- | -| Matrix4Transit | Inverse matrix object of the current matrix.| - -**Example** - -```ts -import matrix4 from '@ohos.matrix4' -// The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x). -let matrix1 = matrix4.identity().scale({x:2}) -let matrix2 = matrix1.invert() -@Entry -@Component -struct Tests { - build() { - Column() { - Image($r("app.media.zh")) - .width(200) - .height(100) - .transform(matrix1) - .margin({ top: 100 }) - Image($r("app.media.zh")) - .width(200) - .height(100) - .margin({ top: 150 }) - .transform(matrix2) - } - } -} -``` - - -### translate - -translate({x?: number, y?: number, z?: number}): Matrix4Transit - - -Matrix translation function, which is used to add the translation effect to the x, y, and z axes of the current matrix. - -**Parameter** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------- | -| x | number | No | Translation distance of the x-axis, in px.
Default value: **0**| -| y | number | No | Translation distance of the y-axis, in px.
Default value: **0**| -| z | number | No | Translation distance of the z-axis, in px.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the translation effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().translate({x:100, y:200, z:30}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - } - } -} -``` - -![en-us_image_0000001212058494](figures/en-us_image_0000001212058494.png) - - -### scale - -scale({x?: number, y?: number, z?: number, centerX?: number, centerY?: number}): Matrix4Transit - - -Matrix scaling function, which is used to add the scaling effect to the x, y, and z axes of the current matrix. - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------------------- | -| x | number | No | Scaling multiple of the x-axis.
Default value: **1** | -| y | number | No | Scaling multiple of the y-axis.
Default value: **1** | -| z | number | No | Scaling multiple of the z-axis.
Default value: **1** | -| centerX | number | No | X coordinate of the center point.
Default value: **0**| -| centerY | number | No | Y coordinate of the center point.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the scaling effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - } - } -} -``` - -![zh-cn_image_0000001219864131](figures/zh-cn_image_0000001219864131.png) - - -### rotate - -rotate({x?: number, y?: number, z?: number, angle?: number, centerX?: Length, centerY?: Length}): Matrix4Transit - - -Matrix rotation function, which is used to add the rotation effect to the x, y, and z axes of the current matrix. - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------------------- | -| x | number | No | X coordinate of the rotation axis vector.
Default value: **1** | -| y | number | No | Y coordinate of the rotation axis vector.
Default value: **1** | -| z | number | No | Z coordinate of the rotation axis vector.
Default value: **1** | -| angle | number | No | Rotation angle.
Default value: **0** | -| centerX | number | No | X coordinate of the center point.
Default value: **0**| -| centerY | number | No | Y coordinate of the center point.
Default value: **0**| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------- | -| Matrix4Transit | Matrix object after the rotation effect is added.| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().rotate({x:1, y:1, z:2, angle:30}) - - build() { - Column() { - Image($r("app.media.bg1")).transform(this.matrix1) - .width("40%") - .height(100) - }.width("100%").margin({top:50}) - } -} -``` - -![en-us_image_0000001211898504](figures/en-us_image_0000001211898504.png) - - -### transformPoint - -transformPoint(point: Point): Point - - -Matrix point transformation function, which is used to apply the current transformation effect to a coordinate point. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ----- | ---- | ------------------ | -| point | Point | Yes | Point to be transformed.| - -**Return value** - -| Type | Description | -| ----- | ---------------- | -| Point | Point object after matrix transformation| - -**Example** - -```ts -// xxx.ets -import matrix4 from '@ohos.matrix4' -import prompt from '@system.prompt' - -@Entry -@Component -struct Test { - private matrix1 = matrix4.identity().transformPoint([100, 10]) - - build() { - Column() { - Button("get Point") - .onClick(() => { - prompt.showToast({message:JSON.stringify(this.matrix1),duration:2000}) - }).backgroundColor(0x2788D9) - }.width("100%").padding(50) - } -} -``` - -![en-us_image_0000001212218464](figures/en-us_image_0000001212218464.gif) diff --git a/en/application-dev/ui/ts-pixel-units.md b/en/application-dev/ui/ts-pixel-units.md index a626608016ebfaa97f0a9a92dcfbdc2ce3bf7004..ca95e08be83c3d40d12fba614e11d58470be2f16 100644 --- a/en/application-dev/ui/ts-pixel-units.md +++ b/en/application-dev/ui/ts-pixel-units.md @@ -4,31 +4,31 @@ The framework provides four pixel units, with vp as the reference data unit. -| Name | Description | +| Name | Description | | -------- | -------- | -| px | Physical pixel unit of the screen. | -| vp | Pixels specific to the screen density, which are converted into physical pixels of the screen based on the screen pixel density. | -| fp | Font pixel, which is similar to vp and varies according to the system font size. | -| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by [designWidth](../ui/ts-framework-js-tag.md)). For example, if designWidth is set to 720, then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels. | +| px | Physical pixel unit of the screen. | +| vp | Pixels specific to the screen density, which are converted into physical pixels of the screen based on the screen pixel density. | +| fp | Font pixel, which is similar to vp and varies according to the system font size. | +| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by [designWidth](../quick-start/package-structure.md)). For example, if designWidth is set to 720, then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels. | ## Pixel Unit Conversion Conversion from other pixel units to px is supported. - | API | Description | +| API | Description | | -------- | -------- | -| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px. | -| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp. | -| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px. | -| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp. | -| lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px. | -| px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx. | +| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px. | +| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp. | +| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px. | +| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp. | +| lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px. | +| px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx. | ## Example - + ```ts // xxx.ets @Entry diff --git a/en/contribute/OpenHarmony-c-coding-style-guide.md b/en/contribute/OpenHarmony-c-coding-style-guide.md index c63b38e5e982dd0c148bb771a617e1fb7eeb6ae6..bd2fdf2bdac82f3ecabfaef2759fd587542132eb 100755 --- a/en/contribute/OpenHarmony-c-coding-style-guide.md +++ b/en/contribute/OpenHarmony-c-coding-style-guide.md @@ -1,6 +1,6 @@ # C Coding Style Guide -## Purpose +## Purpose Rules are not perfect. They might disable useful features in specific situations and therefore affect code implementation. However, the purpose of developing rules is to get more benefits for most programmers. If a rule cannot be followed in your team operation, we can improve the rule together. Before referring to this coding style guide, you are expected to have the following basic capabilities of the C programming language: @@ -8,11 +8,11 @@ Rules are not perfect. They might disable useful features in specific situations 2. Be familiar with the basic features of C. 3. Understand the standard library of C. -## General Principles +## General Principles Code must meet the requirements for **readability**, **maintainability**, **security**, **reliability**, **testability**, **efficiency**, and **portability** while ensuring functionality correctness. -## Conventions +## Conventions **Rule**: Conventions that must be followed during programming. @@ -20,51 +20,64 @@ Code must meet the requirements for **readability**, **maintainability**, **secu It is necessary to understand the reason for these conventions and try to comply with them, no matter if they are rules or recommendations. -## Exceptions +## Exceptions + +The only acceptable exceptions are those that do not violate the general principles and provide appropriate reasons for their existence. -The only acceptable exceptions are those that do not violate the general principles and provide appropriate reasons for their existence. Try to avoid exceptions because they affect the code consistency. Exceptions to 'Rules' should be very rare. -The style consistency principle is preferred in the following case: +The style consistency principle is preferred in the following case: + **When you modify open-source or third-party code, comply with their respective code specifications.** -# 1 Naming +# 1 Naming Names include file, function, variable, type, and macro names. -Naming is considered the most difficult and important thing in software development. +Naming is considered the most difficult and important thing in software development. + The name of an identifier must be clear, well defined, easy to understand, and accounting for reading habits. The unified naming style is the most direct expression of the consistency principle. -## General Conventions +## General Conventions + +**CamelCase** -**CamelCase** CamelCase is the practice of writing compound words or phrases so that each word or abbreviation in the phrase begins with a capital letter, and with no intervening spaces or punctuation. + There are two conventions: **UpperCamelCase and lowerCamelCase**. -**Unix\_like** +**Unix\_like** + Unix\_like is also known as the snake style. In the Unix\_like style, words contain only lowercase letters and are separated by underscores (\_). + Example: 'test_result' -### Rule 1.1 Name identifiers in the CamelCase style. +### Rule 1.1 Name identifiers in the CamelCase style. -| Type| Naming Style -|----------|---------- -| Function, struct, enum, union| UpperCamelCase -| Variable, function parameter, macro parameter, struct body, union member| lowerCamelCase -| Macro, constant, enumerated value, goto tag| All capitalized, separated by underscores (\_) +| Type| Naming Style| +|----------|----------| +| Function, struct, enum, union| UpperCamelCase| +| Variable, function parameter, macro parameter, struct body, union member| lowerCamelCase| +| Macro, constant, enumerated value, goto tag| All capitalized, separated by underscores (\_)| + +Note: -Note: **Constant** in the above table refers to the variable that is of the basic data type, enum type, and string type and modified by **const** under the global scope, excluding arrays, structs, and unions. + **Variable** indicates the variables excluding those defined in **Constant**. These variables use the lowerCamelCase style. + Unix\_like can be used for Linux or Unix friendly code. + For code that is using the Unix\_like style, you can continue using this style. + The same naming style must be used for the same function, struct, or union. -### Rec 1.1 Use more accurate names for identifiers with a large scope. +### Rec 1.1 Use more accurate names for identifiers with a large scope. + +Different from C++, C does not have namespace or class. Therefore, the names of identifiers in the global scope must not conflict with each other. -Different from C++, C does not have namespace or class. Therefore, the names of identifiers in the global scope must not conflict with each other. Names of global functions, global variables, macros, types, and enums must be accurately described and unique in the global scope. Example: @@ -75,7 +88,9 @@ int GetActiveConnectCount(void); // Good ``` For purposes of accurate naming, a module prefix can be added if necessary. -The module prefix and the naming body can be connected by following the CamelCase style. + +The module prefix and the naming body can be connected by following the CamelCase style. + Example: ```c @@ -86,26 +101,30 @@ enum XxxMyEnum { // OK }; ``` -## File Naming +## File Naming -### Rec 1.2 Use lowercase file names. +### Rec 1.2 Use lowercase file names. Only lowercase letters, numbers, and underscores (\_) are allowed in file names. -File names should be as short, accurate, and unambiguous as possible. + +File names should be as short, accurate, and unambiguous as possible. + The reason for using lowercase file names is that different systems process file names in different ways. (For example, file names in MS-DOS and Windows are not case sensitive, but those in Unix/Linux and macOS are case sensitive by default). -Good example: +Good example: + `dhcp_user_log.c` Bad examples: + `dhcp_user-log.c`: It is not recommended that you separate words with the hyphen (-). `dhcpuserlog.c`: The words are not separated, causing poor readability. -## Function Naming +## Function Naming Functions are named in the UpperCamelCase style. -### Rec 1.3 Name functions to comply with reading habits. +### Rec 1.3 Name functions to comply with reading habits. The "verb + object" structure can be used for action related function names. Example: @@ -130,13 +149,14 @@ TotalCount() // OK GetTotalCount() // OK ``` -## Variable Naming +## Variable Naming Variables are named in the lowerCamelCase style. This includes global variables, local variables, parameters in the function declaration or definition as well as parameters in function-like macro. -### Rule 1.2 Add the 'g_' prefix to global variables, but not to static variables in a function. +### Rule 1.2 Add the 'g_' prefix to global variables, but not to static variables in a function. Global variables should be used as little as possible, and special attention should be paid to their use. This prefix highlights global variables so that developers can be more careful when handling them. + Global static variables and global variables are named in the same way. Static variables in functions and common local variables are named in the same way. ```c @@ -151,7 +171,7 @@ void Func(void) Notes: Constants are also global variables in essence. However, if constants are named using uppercase letters separated by underscores (\_), the current rule does not apply. -### Rec 1.4 Keep local variables short and to the point. +### Rec 1.4 Keep local variables short and to the point. The name of a local variable should be short on the premise that meanings can be expressed through context. @@ -184,6 +204,7 @@ int Func(...) ``` Similarly, "tmp" can be used to address any type of temporary variable. + A short variable name should be used with caution, but sometimes a single-character variable is allowed, for example, a counter variable in a loop statement. ```c @@ -203,7 +224,7 @@ int Mul(int a, int b) } ``` -## Type Naming +## Type Naming Types are named in the UpperCamelCase style. @@ -248,14 +269,18 @@ typedef struct tagNode { // Good: Add the 'tag' prefix or use 'Node_'. } Node; // UpperCamelCase. ``` -## Macro, Constant, and Enum Naming +## Macro, Constant, and Enum Naming Use uppercase letters separated by underscores (\_) for macro names and enumerated values. + You are advised to use uppercase letters separated with underscores (\_) for constant names. Global const variables can be named with the same style of global variables. + The constants here are defined as global const variables of the basic data type, enum type, or string type. Use uppercase letters separated by underscores (\_) for function-like macros. + Exceptions: + 1. Functions that use macros to implement generic functions, for example, macros that implement functions such as list and map, can be named in the same way as functions, using the UpperCamelCase style. 2. A function-like macro that is used to replace a function in the earlier version can be named in the same way as functions, using the UpperCamelCase style. 3. Macros for printing logs can be named in the same way as functions, using the UpperCamelCase style. @@ -317,7 +342,7 @@ enum BaseColor { }; ``` -### Rec 1.5 Avoid temporary variables in function-like macros from polluting external scopes. +### Rec 1.5 Avoid temporary variables in function-like macros from polluting external scopes. **If possible, use a function instead of a function-like macro. Define a function-like macro only when necessary.** @@ -330,15 +355,18 @@ When defining local variables for a function-like macro, use double underscores } while (0) ``` -# 2 Formatting +# 2 Formatting -## Line Length +## Line Length -### Rule 2.1 Include 120 characters or less in each line. +### Rule 2.1 Include 120 characters or less in each line. A longer line makes it more difficult for reading. + To meet the line length requirement, you can shorten the names of functions and variables and reduce the number of nesting layers. This improves code readability. + Unless a long line is necessary to maintain readability and present complete information, steer your document clear of long lines. + Even on a high-resolution monitor, a long line increases the difficulty of reading. Strive for clearness and conciseness. Exceptions: @@ -354,19 +382,22 @@ Example: #endif ``` -## Indentation +## Indentation -### Rule 2.2 Use spaces to indent and indent four spaces at a time. +### Rule 2.2 Use spaces to indent and indent four spaces at a time. + +Only spaces can be used for indentation. Four spaces are indented each time. Do not use the Tab character to indent. -Only spaces can be used for indentation. Four spaces are indented each time. Do not use the Tab character to indent. Currently, almost all integrated development environments (IDEs) and code editors support automatic conversion of a Tab input to fours spaces. Configure your code editor to support indentation with spaces. -## Braces +## Braces + +### Rule 2.3 Use the K\&R indentation style. + +**K\&R style** -### Rule 2.3 Use the K\&R indentation style. +While wrapping a line, the left brace of the function starts a new line and takes a single line. Other left braces are placed at the end of the line along with the statement. -**K\&R style** -While wrapping a line, the left brace of the function starts a new line and takes a single line. Other left braces are placed at the end of the line along with the statement. The right brace takes a single line, unless it is followed by the rest of the same statement, such as `while` in the `do` statement, `else` or `else if` in the `if` statement, a comma, or a semicolon. Example: @@ -386,9 +417,9 @@ int Foo(int a) } ``` -## Function Declaration and Definition +## Function Declaration and Definition -### Rule 2.4 Keep the return type and function name of the function declaration or definition in the same line, and align the function parameter list appropriately if it needs to be wrapped. +### Rule 2.4 Keep the return type and function name of the function declaration or definition in the same line, and align the function parameter list appropriately if it needs to be wrapped. When a function is declared and defined, the return value type of the function should be in the same line as the function name. @@ -423,11 +454,12 @@ ReturnType ReallyReallyReallyReallyLongFunctionName( // The line leng } ``` -## Function Calls +## Function Calls -### Rule 2.5 Align the parameter list appropriately if it needs to be wrapped. +### Rule 2.5 Align the parameter list appropriately if it needs to be wrapped. In a function call, if the function parameter list is wrapped, it should be aligned appropriately. + The left parenthesis is always followed by a function name, and the right parenthesis always follows the last parameter. Example: @@ -454,11 +486,12 @@ int result = DealWithStructureLikeParams(left.x, left.y, // Indicates a grou right.x, right.y); // Indicates another group of related parameters. ``` -## Conditional Statements +## Conditional Statements -### Rule 2.6 Use braces for conditional statements. +### Rule 2.6 Use braces for conditional statements. Use braces to enclose conditional statements, even if there is only one statement. + Reason: - Logic is intuitive and easy to read. @@ -471,7 +504,7 @@ if (objectIsNotExist) { // Good: Braces are added to a single-line condi } ``` -### Rule 2.7 Do not place `if`, `else`, and `else if` in the same line. +### Rule 2.7 Do not place `if`, `else`, and `else if` in the same line. In a conditional statement, branches, if any, should be written in different lines. @@ -491,9 +524,9 @@ Bad example: if (someConditions) { ... } else { ... } // Bad: They are in the same line. ``` -## Loops +## Loops -### Rule 2.8 Use braces for loop statements. +### Rule 2.8 Use braces for loop statements. Use braces to enclose the `for` and `while` statements, even if there is only one loop. @@ -524,9 +557,9 @@ for (int i = 0; i < someRange; i++) while (condition); // Bad: The semicolon may be treated as part of the `while` statement. ``` -## `switch` Statements +## `switch` Statements -### Rule 2.9 Indent the `case` or `default` statement in a `switch` statement block. +### Rule 2.9 Indent the `case` or `default` statement in a `switch` statement block. Use the following indentation style for the `switch` statement: @@ -554,9 +587,9 @@ default: // Bad: 'default' not indented } ``` -## Expressions +## Expressions -### Rec 2.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of the line. +### Rec 2.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of the line. A long expression that does not meet the line length requirement must be wrapped appropriately. Generally, the expression is wrapped after a lower-priority operator or a hyphen, and the operator or hyphen is placed at the end of the line, indicating that the operation is to be continued. @@ -584,9 +617,9 @@ int sum = longVariableName1 + longVariableName2 + longVariableName3 + longVariableName4 + longVariableName5 + longVariableName6; // OK: aligned ``` -## Variable Assignment +## Variable Assignment -### Rule 2.10 Do not write multiple variable definitions or assignment statements in one line. +### Rule 2.10 Do not write multiple variable definitions or assignment statements in one line. It is recommended that each line contain only one variable initialization statement, which is easier to read and understand. @@ -619,13 +652,14 @@ for (i = 0; i < row; i++) { } ``` -## Initialization +## Initialization Initialization is applicable to structs, unions, and arrays. -### Rule 2.11 Use indentation or make a reasonable alignment for a new line. +### Rule 2.11 Use indentation or make a reasonable alignment for a new line. For the struct or array initialization, use 4 spaces for indentation if a line break is made. + From better readability, make a reasonable alignment. ```c @@ -669,7 +703,7 @@ Note: - If the left brace is placed at the end of the line, the corresponding right brace should be placed into a new line. - If the left brace is followed by the content, the corresponding right brace should also follow the content. -### Rule 2.12 Initialize each member in a separate line during struct and union member initialization. +### Rule 2.12 Initialize each member in a separate line during struct and union member initialization. The C99 standard supports the initialization of the struct and union members in their definition. This is called the designated initializer. In such a way, each member should be initialized in a separate line. @@ -687,9 +721,9 @@ struct Date date = { // Good: When the designated initializer is used, each m }; ``` -## Pointers +## Pointers -### Rec 2.2 Ensure that the asterisk (\*) in the pointer type is followed by the variable name or follows the type. There must be a space before or after the asterisk. +### Rec 2.2 Ensure that the asterisk (\*) in the pointer type is followed by the variable name or follows the type. There must be a space before or after the asterisk. When you declare or define a pointer variable or return a pointer type function, the asterisk can be placed on the left (following the type) or right (followed by the variable name). There must be only one space before or after the asterisk. @@ -719,16 +753,17 @@ int Foo(const char * restrict p); // OK Do not use the asterisk to follow the `const` or `restrict` keywords. -## Compilation Preprocessing +## Compilation Preprocessing -### Rule 2.13 Place the number sign (#) at the beginning of a line for compilation preprocessing. In nested compilation preprocessing, the number sign (#) can be indented. +### Rule 2.13 Place the number sign (#) at the beginning of a line for compilation preprocessing. In nested compilation preprocessing, the number sign (#) can be indented. The number sign (#) must be placed at the beginning of a line for compilation preprocessing, even if the code is embedded in the function body. + Try your best not to use compilation preprocessing macros. If they are needed in deed, they should be managed by dedicated personnel in a unified manner. -## Whitespace +## Whitespace -### Rule 2.14 Use horizontal whitespaces to highlight keywords and important information, and avoid unnecessary whitespaces. +### Rule 2.14 Use horizontal whitespaces to highlight keywords and important information, and avoid unnecessary whitespaces. Horizontal spaces should be used to highlight keywords and important information. Do not add spaces at the end of each line of code. The general rules are as follows: @@ -821,7 +856,7 @@ switch (var) { // Good: A space is added after the `switch` keyword. Note: The current IDE and code editor can be set to delete spaces at the end of a line. Configure your editor correctly. -### Rec 2.3 Arrange blank lines reasonably to keep the code compact. +### Rec 2.3 Arrange blank lines reasonably to keep the code compact. Reduce unnecessary blank lines so that more code can be displayed for easy reading. The following rules are recommended: @@ -862,7 +897,7 @@ int Foo(void) } ``` -# 3 Comments +# 3 Comments Generally, clear architecture and good symbol naming are recommended to improve code readability, and comments are provided only when necessary. @@ -873,6 +908,7 @@ The comments must be concise, clear, and unambiguous, ensuring that the informat **Comments are as important as code.** When writing a comment, you need to step into the reader's shoes and use comments to express what the reader really needs. Comments are used to express the code functionality and intention, rather than repeating code. + When modifying the code, ensure that the comments are consistent. It is impolite to only modify code and not update the comments. This destroys the consistency between code and comments, and may cause confusion or even misleading. Comment code in fluent **English**. @@ -883,18 +919,19 @@ Comments must be added in the following scenarios (including but not limited to 3. Core algorithms 4. A function that contains more than 50 lines -## Comment Style +## Comment Style In C code, both `/*` `*/` and `//` can be used. Comments can be classified into different types depending on the purpose and position, such as file header comments, function header comments, and general comments. + Comments of the same type must keep a consistent style. Note: The sample code used in this article sees extensive use of the '//' post-comment. This is only for better understanding, and does not mean that this comment style is better. -## File Header Comments +## File Header Comments -### Rule 3.1 Include the copyright license in the file header comments. +### Rule 3.1 Include the copyright license in the file header comments. /\* @@ -911,9 +948,9 @@ Note: The sample code used in this article sees extensive use of the '//' post-c * See the License for the specific language governing permissions and * limitations under the License. \*/ -## Function Header Comments +## Function Header Comments -### Rule 3.2 Do not use empty function header comments with no content. +### Rule 3.2 Do not use empty function header comments with no content. Not all functions need function header comments. @@ -947,10 +984,12 @@ int Func1(void); int Func2(void); ``` -Use function names to describe functions, and only add function header comments if necessary. +Use function names to describe functions, and only add function header comments if necessary. + Do not write useless or redundant function headers. Do not write empty function headers with no content. The following content is **optional** in the function header comment: function description, return value, performance constraint, usage, memory convention, algorithm implementation, and reentering requirement. + In the function interface declaration in the external header file of the module, the function header comment should clearly describe important and useful information. Example: @@ -981,11 +1020,11 @@ Problems in the preceding example are as follows: - The function name has redundant information. - It does not clearly state the party that should release the buffer. -## Code Comments +## Code Comments -### Rule 3.3 Place code comments above or to the right of the code. +### Rule 3.3 Place code comments above or to the right of the code. -### Rule 3.4 Add a space between the comment character and the comment content, and one space between the comment and code if the comment is placed to the right of the code. +### Rule 3.4 Add a space between the comment character and the comment content, and one space between the comment and code if the comment is placed to the right of the code. Comments placed above code should be indented to the same level as the code. @@ -1041,14 +1080,15 @@ Example: If the comment on the right exceeds the permitted line length, the comment can be placed above the code. -### Rule 3.5 Delete unused code segments. Do not comment them out. +### Rule 3.5 Delete unused code segments. Do not comment them out. + +Code that is commented out cannot be maintained. If you attempt to restore the code, it is very likely to introduce ignorable defects. -Code that is commented out cannot be maintained. If you attempt to restore the code, it is very likely to introduce ignorable defects. The correct method is to delete unnecessary code. If necessary, consider porting or rewriting the code. Here, commenting out refers to the removal of code from compilation without actually deleting it. This is done by using /\* \*/, //, #if 0, #ifdef NEVER\_DEFINED, and so on. -### Rec 3.1 Provide comments if `break` or `return` is not added to the end of the `case` statement block (fall-through). +### Rec 3.1 Provide comments if `break` or `return` is not added to the end of the `case` statement block (fall-through). Sometimes, the same thing is needed for multiple `case` tags. When a `case` statement ends without `break` or `return`, the statement in the next `case` tag will be executed. This is called "fall-through". @@ -1085,14 +1125,15 @@ switch (var) { } ``` -# 4 Header Files +# 4 Header Files **For the C programming language, the design of the header file reflects most of the system design.** + The correct use of the header file makes code more readable, reduces file size, and speeds up compilation and build performance. The following programming specifications aim to help you properly plan header files. -## Header File Responsibility +## Header File Responsibility A header file is an external interface of a module or file. @@ -1107,7 +1148,8 @@ If a .c file does not need to open any interface externally, it should not exist Exceptions: the entry point of the program (for example, the file where the main function is located), unit test code, and dynamic library code. -Example: +Example: + Content of **foo.h**: ```c @@ -1147,28 +1189,33 @@ Some simple header files, such as the command ID definition header file, do not If a set of interface protocols has multiple instances and the interface is fixed, one .h file can have multiple .c files. -### Rec 4.2 Use .h as the extension of the header file, rather than other unconventional extensions, for example, .inc. +### Rec 4.2 Use .h as the extension of the header file, rather than other unconventional extensions, for example, .inc. + +Some products use .inc as the header file name extension, which does not comply with the C programming language. A header file using .inc as the file name extension usually indicates a private header file. -Some products use .inc as the header file name extension, which does not comply with the C programming language. A header file using .inc as the file name extension usually indicates a private header file. However, in practice, this recommendation is not followed properly. An .inc file is generally contained in multiple .c files. It is not recommended that private definitions be stored in header files. For details, see [Rec 4.1](#a4-1). +However, in practice, this recommendation is not followed properly. An .inc file is generally contained in multiple .c files. It is not recommended that private definitions be stored in header files. For details, see [Rec 4.1](#a4-1). -## Header File Dependency +## Header File Dependency + +The header file contains a dependency, and the dependency should be stable. -The header file contains a dependency, and the dependency should be stable. Generally, an unstable module depends on a stable module. When the unstable module changes, the build of the stable module is not affected. Dependency direction is as follows: Products depend on the platform, and the platform depends on the standard library. -In addition to unstable modules depending on stable modules, each module depends on the interface. In this way, in case of any internal implementation changes to one module, users do not need to recompile another module. +In addition to unstable modules depending on stable modules, each module depends on the interface. In this way, in case of any internal implementation changes to one module, users do not need to recompile another module. + It is assumed that the interface is the most stable. -### Rule 4.1 Forbid cyclic dependency of header files. +### Rule 4.1 Forbid cyclic dependency of header files. + +Cyclic dependency (also known as a circular dependency) of header files means that a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any header file is modified, all code containing a.h, b.h, and c.h needs to be recompiled. -Cyclic dependency (also known as a circular dependency) of header files means that a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any header file is modified, all code containing a.h, b.h, and c.h needs to be recompiled. For a unidirectional dependency: a.h contains b.h, b.h contains c.h, and c.h does not contain any header file, modifying a.h does not mean a need to recompile the source code for b.h or c.h. The cyclic dependency of header files reflects an obviously unreasonable architecture design, which can be avoided through optimization. -### Rule 4.2 Include the internal #include protection character (#define protection) in the header file. +### Rule 4.2 Include the internal #include protection character (#define protection) in the header file. To prevent header files from being included multiple times, all header files should be protected by #define. Do not use #pragma once. @@ -1187,13 +1234,16 @@ Assume that the **timer.h** file of the timer component of the util subsystem is #endif // UTIL_TIMER_TIMER_H ``` -### Rule 4.3 Do not reference external function interfaces and variables by using declaration. +### Rule 4.3 Do not reference external function interfaces and variables by using declaration. + +You can use the interfaces provided by other modules or files only by using header files. + +Using external function interfaces and variables with an extern declaration may cause inconsistency between declarations and definitions when external interfaces are changed. -You can use the interfaces provided by other modules or files only by using header files. -Using external function interfaces and variables with an extern declaration may cause inconsistency between declarations and definitions when external interfaces are changed. In addition, this kind of implicit dependency may cause architecture corruption. Cases that do not comply with specifications: + Content of **a.c**: ```c @@ -1233,11 +1283,14 @@ int Foo(void) ``` In some scenarios, if internal functions need to be referenced with no intrusion to the code, the extern declaration mode can be used. + Example: -When performing unit testing on an internal function, you can use the extern declaration to reference the tested function. + +When performing unit testing on an internal function, you can use the extern declaration to reference the tested function. + When a function needs to be stubbed or patched, the function can be declared using extern. -### Rule 4.4 Do not include header files in extern "C". +### Rule 4.4 Do not include header files in extern "C". If a header file is included in extern "C", extern "C" may be nested. Some compilers restrict the number of nesting layers of extern "C". Too many nesting layers may cause compilation errors. @@ -1281,38 +1334,46 @@ extern "C" { } ``` -In the **a.h** file, the **Foo** function is intended to be a C++ free function following the C++ specifications. However, in the **b.h** file, because `#include "a.h"` is placed inside `extern "C"`, the linking specification of the **Foo** function is changed incorrectly. +In the **a.h** file, the **Foo** function is intended to be a C++ free function following the C++ specifications. + +However, in the **b.h** file, because `#include "a.h"` is placed inside `extern "C"`, the linking specification of the **Foo** function is changed incorrectly. Exceptions: In the C++ compilation environment, if you want to reference a header file written in pure C, a non-intrusive approach is to exclude the C header file from `extern "C"`. -# 5 Functions +# 5 Functions Functions help avoid repeated code and increase reusability. Functions are layered to reduce complexity and hide implementation details, making programs more modular and facilitating code reading and maintenance. Functions should be concise and short. + One function completes only one thing. -## Function Design +## Function Design The essence of function design is to write clean functions and organize code effectively. The code should be simple and not conceal the designer's intention, using clean abstractions and straightforward control statements to organize the function naturally. -### Rule 5.1 Avoid long functions and ensure that functions contain no more than 50 lines (excluding blank lines and comments). +### Rule 5.1 Avoid long functions and ensure that functions contain no more than 50 lines (excluding blank lines and comments). A function should be able to be displayed on one screen (fewer than 50 lines). It does only one thing and does it well. A long function usually means that it aims to implement complex functionalities or contains excess details. Exceptions: -Considering the code's aggregation and functionality, some functions may exceed 50 lines, but only if the code is readable and concise. + +Considering the code's aggregation and functionality, some functions may exceed 50 lines, but only if the code is readable and concise. + These exceptions should be minimal, such as specific algorithm processing. -Even if a large function works well in the moment, once someone modifies it, new problems may occur. It may even cause bugs that are difficult to discover. +Even if a large function works well in the moment, once someone modifies it, new problems may occur. It may even cause bugs that are difficult to discover. + It is recommended that you split the code into several functions that are simpler and easier to manage so that others can easily read and modify the code. -### Rule 5.2 Avoid nesting a code block more than four times within a function. +### Rule 5.2 Avoid nesting a code block more than four times within a function. The nested code block depth of a function refers to the layered depth of a code control block (created by statements such as `if`, `for`, `while`, and `switch`). + Each layer of nesting increases the difficulty in reading the code. + Further functional decomposition should be done for better understanding. Using `guard clauses` can effectively reduce the nesting layers of the `if` statements. Example: @@ -1350,10 +1411,12 @@ int Foo(...) ``` Exceptions: + Considering the code's aggregation and functionality, some functions may contain 4 or more nesting layers, but only if the code is readable and concise. + These exceptions should be rare. -### Rec 5.1 Process all returned error codes. +### Rec 5.1 Process all returned error codes. A function (in a standard library, a third-party library, or a user-defined function) must be able to indicate errors. This can be done by using error tags, special return data, or other means. No matter when a function provides such a mechanism, the caller should immediately check the error indication after the function returns. @@ -1379,11 +1442,12 @@ DealWithFileHead(fileHead, sizeof(fileHead)); // Process the file header. ``` If the return value of a function is ignored and `void` is returned frequently, check whether the return value of the function is designed properly. + Only if the caller of a function really doesn't need a return value, should you design the function to return `void`. -## Function Parameters +## Function Parameters -### Rec 5.2 Use the return value instead of the output parameter when designing a function. +### Rec 5.2 Use the return value instead of the output parameter when designing a function. Using return values rather than output parameters improves readability and usually provides the same or better performance. @@ -1393,17 +1457,18 @@ Exceptions: 1. When multiple values are returned, you can design an output parameter for the function. 2. If memory allocation is involved, you can design an output parameter. The caller passes the allocated memory as an output parameter, and memory allocation is not performed in the function. -### Rec 5.3 Define function parameters in the sequence of input, output, and input/output parameters. +### Rec 5.3 Define function parameters in the sequence of input, output, and input/output parameters. You are advised to define function parameters in the sequence of input, output, and input/output parameters. -### Rule 5.3 Provide a release function if allocation of resources, such as memory, locks, and queues, is involved. +### Rule 5.3 Provide a release function if allocation of resources, such as memory, locks, and queues, is involved. Resources should be released from where they are applied for. If a function applies for resources, the module must provide resource functions. -### Rec 5.4 Use strongly typed parameters. Do not use void\*. +### Rec 5.4 Use strongly typed parameters. Do not use void\*. + +While different languages have their own views on strong typing and weak typing, it is generally believed that C/C++ is a strongly typed language. Since we use such a strongly typed language, we should keep this style. -While different languages have their own views on strong typing and weak typing, it is generally believed that C/C++ is a strongly typed language. Since we use such a strongly typed language, we should keep this style. The advantage of this strongly typed style is to prevent evasive errors by catching errors at the compilation stage. Strong types help the compiler find more errors.Pay attention to the usage of the `FooListAddNode` function in the following code: @@ -1448,12 +1513,14 @@ void FooListAddNode(FooNode *foo) Exceptions: For some generic interfaces, you can use the input parameter `void *` to pass different types of pointers. -### Rec 5.5 It is the caller's responsibility to check the validity of internal function parameters of a module. +### Rec 5.5 It is the caller's responsibility to check the validity of internal function parameters of a module. Validity check must be performed on parameters passed from external modules to protect programs from being damaged by invalid input data. + When calling internal functions, by default, the caller is responsible for ensuring the validity of any returned data. If the callee takes responsibility for checking data validity, checks may be performed multiple times and redundant code is generated. This is not concise. When the caller ensures the validity of any received data, this contractual programming makes logic simpler and code more readable. + Example: ```c @@ -1480,7 +1547,7 @@ void DealWithData(int data) } ``` -### Rec 5.5 Declare the pointer argument of a function as 'const' if it is not used to modify the pointed object. +### Rec 5.5 Declare the pointer argument of a function as 'const' if it is not used to modify the pointed object. The const pointer argument, which restricts the function from modifying the object through the pointer, makes code stronger and safer. @@ -1492,7 +1559,7 @@ int strncmp(const char *s1, const char *s2, size_t n); // Good: The invariant pa Note: Whether to declare the pointer parameter as `const` depends on the function design, but not on whether there is a "modify object" action in the function entity. -### Rec 5.6 Include no more than 5 parameters in a function. +### Rec 5.6 Include no more than 5 parameters in a function. If a function has too many parameters, the function is easy to be affected by changes in external code, hindering maintenance. Too many function parameters will also increases the workload for testing. @@ -1501,11 +1568,11 @@ The number of parameters in a function must not exceed 5. If the number of param - Check whether the function can be split. - Check whether any related parameters can be combined and defined as a struct. -## Inline Functions +## Inline Functions -An inline function is a function optimization method introduced by C99. Function inlining can eliminate the overhead of function calls; thanks to inlining, combination with the called code is implemented, so that the compiler can achieve further code optimization from a larger perspective. The inline function is similar to a function-like macro. For details, see [Rec 6.1](#rec-61-use-functions-instead-of-function-like-macros). +An inline function is a function optimization method introduced by C99. Function inlining can eliminate the overhead of function calls; thanks to inlining, combination with the called code is implemented, so that the compiler can achieve further code optimization from a larger perspective. The inline function is similar to a function-like macro. For details, see [Rec 6.1](#a6-1). -### Rec 5.7 Include no more than 10 lines in an inline function (excluding blank lines and comments). +### Rec 5.7 Include no more than 10 lines in an inline function (excluding blank lines and comments). Defining a function as an inline function generally aims to improve performance, though it may fail to do so.If the function body is short, function inlining can effectively reduce the size of the target code and improve the function execution efficiency. @@ -1516,7 +1583,7 @@ It is recommended that inline functions be controlled to within **10** lines. Do not abuse inline functions to improve performance. Avoid premature optimization. In general, a function can be defined as an inline function only when actual test data proves that the inlining achieves higher performance. Functions such as setter and getter functions, which are short and called frequently, can be defined as inline functions. -### Rule 5.3 Define inline functions that will be called by multiple source files in the header file. +### Rule 5.3 Define inline functions that will be called by multiple source files in the header file. Inline functions are unfolded in compilation. Therefore, the inline function definition must be visible in each source file that calls this function. @@ -1548,11 +1615,12 @@ int OtherFunc(void) ``` Due to this restriction, if multiple source files need to call the same inline function, the definition of the inline function must be placed in the header file. + The inline function implementation in **gnu89** differs from that in the **C99** standard. For compatibility, you can declare the function as **static inline**. -# 6 Macros +# 6 Macros -## Function-like Macros +## Function-like Macros A function-like macro is a macro (as shown in the following example) similar to a function. It contains several statements to implement a specific function. @@ -1573,8 +1641,8 @@ Before defining a function-like macro, consider whether it can be replaced with The disadvantages of the function-like macro are as follows: - Function-like macros haves no type check, which is not as strict as the function call check. For the example code, see [Below](#macro_lack_of_type_check__example). -- If macro parameters are not calculated during macro expansion, unexpected results may be generated. For details, see [Rule 6.1](#rule-61-use-complete-parentheses-for-macro-parameters-when-defining-a-macro) and [Rule 6.3](#rule-63-do-not-pass-expressions-with-side-effects-to-a-function-like-macro). -- A macro has no independent scope. When it is used together with control flow statements, unexpected results described in [Rule 6.2](#rule-62-place-implementation-statements-of-function-like-macros-that-contain-multiple-statements-in-a-do-while0) may be generated. +- If macro parameters are not calculated during macro expansion, unexpected results may be generated. For details, see [Rule 6.1](#r6-1) and [Rule 6.3](#r6-3). +- A macro has no independent scope. When it is used together with control flow statements, unexpected results described in [Rule 6.2](#r6-2) may be generated. - There are high skill requirements on the proper use of macros (for example, the usage of `#` and wide use of parentheses), which reduces readability. - Extensions of some macros can only be implemented by specific compilers in specific scenarios, such as `statement expression` of `gcc`, reducing the portability. - After the macro is expanded during precompilation, it is invisible during subsequent compilation, linking, and debugging. Besides, macros that contain multiple lines are expanded into a line. @@ -1630,7 +1698,8 @@ int ErrLog(const char *file, unsigned long line, const char *fmt, ...); ### Rule 6.1 Use complete parentheses for macro parameters when defining a macro. -The macro parameter is replaced by text only when the macro is expanded. The value is calculated when the macro is compiled. After the text replacement, the statements contained in the macro are combined with called code. +The macro parameter is replaced by text only when the macro is expanded. The value is calculated when the macro is compiled. After the text replacement, the statements contained in the macro are combined with called code. + The expression after combination may result in a different result than expected, especially when the macro parameter is in an expression. The following is an incorrect format: @@ -1639,15 +1708,18 @@ The following is an incorrect format: #define SUM(a, b) a + b // Bad ``` -When the macro is used, the execution result is inconsistent with the expected result. -`100 / SUM(2, 8)` is expanded to `(100 / 2) + 8`. The expected result is `100 / (2 + 8)`. +When the macro is used, the execution result is inconsistent with the expected result. + +`100 / SUM(2, 8)` is expanded to `(100 / 2) + 8`. The expected result is `100 / (2 + 8)`. + This problem can be solved by adding parentheses to the entire expression, as shown in the following: ```c #define SUM(a, b) (a + b) // Bad ``` -However, this method has the following problems: +However, this method has the following problems: + `SUM(1 << 2, 8)` is extended to `1 << (2 + 8)` (because the priority of `<<` is lower than that of `+`), which is inconsistent with the expected result `(1 << 2) + 8`. To solve this problem, add parentheses to each macro parameter, as shown in the following: @@ -1721,7 +1793,8 @@ To solve the preceding problem, use braces to enclose the statements defined by } ``` -The brackets are not associated with semicolons (;). The semicolon following the braces is another statement. +The brackets are not associated with semicolons (;). The semicolon following the braces is another statement. + In the following code example, the "suspended else' compilation error message is displayed. ```c @@ -1749,7 +1822,8 @@ Exceptions: ### Rule 6.3 Do not pass expressions with side effects to a function-like macro. -Since macros are replaced by text, if a function-like macro uses the same macro parameter multiple times and transfers expressions with side effects as macro parameters, unexpected results may occur. +Since macros are replaced by text, if a function-like macro uses the same macro parameter multiple times and transfers expressions with side effects as macro parameters, unexpected results may occur. + As shown in the following example, the macro `SQUARE` is normal, but the `a++` expression with side effects is passed to the macro. As a result, the value of `a` is different from the expected value after the `SQUARE` macro is executed. ```c @@ -1769,10 +1843,11 @@ b = SQUARE(a); a++; // Result: a = 6, which is added only once. ``` -In addition, if the macro parameter contains a function call, the function may be called repeatedly after the macro is expanded. +In addition, if the macro parameter contains a function call, the function may be called repeatedly after the macro is expanded. + If the function execution results are the same, it is a waste; if the results are different, the execution result may not meet the expected value. -### Rec 6.2 Exercise caution when you use the statements such as `return`, `goto`, `continue`, and `break` in a function-like macro definition. +### Rec 6.2 Exercise caution when you use the statements such as `return`, `goto`, `continue`, and `break` in a function-like macro definition. Although process changing statements, such as `return`, `goto`, `continue`, and `break`, in a macro can simplify the code, they hide the real process, which hinders understanding and easily causes resource leakage. @@ -1821,27 +1896,32 @@ CHECK_PTR(mem2, ERR_CODE_XXX); // Wrong: Memory leak. ``` If `mem2` fails to apply for memory, `CHECK_PTR` will return a message instead of releasing `mem1`. + Besides, the name of the `CHECK_PTR` macro is not good. The macro name only reflects the check action and does not specify the result. Readers can see that a failure is returned when the pointer is null only after viewing the macro implementation. It's not inherently obvious. In summary, it is not recommended to encapsulate process changing statements, such as `return`, `goto`, `continue`, and `break`, in macro definitions. + However, these macros can be used in special scenarios, such as return value judgment. Note: **Macro names must contain descriptive keywords if process changing statements, such as `return`, `goto`, `continue`, and `break`, are used.** -### Rec 6.3 Include no more than 10 lines in a function-like macro (excluding blank lines and comments). +### Rec 6.3 Include no more than 10 lines in a function-like macro (excluding blank lines and comments). A function-like macro is more difficult to debug and locate than a function, especially when the macro is too long. Macro expansion will also lead to more compiled code. It is recommended that function-like macros contain no more than 10 lines. -# 7 Variables +# 7 Variables In C language coding, variables are the most important except for functions. -When using a variable, you should always follow the principle of "single responsibility". + +When using a variable, you should always follow the principle of "single responsibility". + By scope, variables can be classified into global variables and local variables. -## Global Variables +## Global Variables + +Do not use or avoid using global variables. -Do not use or avoid using global variables. In program design, global variables are variables that are accessible to all scopes. Using unnecessary global variables is generally considered a bad habit. Disadvantages of global variables: @@ -1852,16 +1932,18 @@ Disadvantages of global variables: If unavoidable, the read and write of global variables should be encapsulated in a centralized manner. -### Rule 7.1 Do not use global variables as interfaces between modules. +### Rule 7.1 Do not use global variables as interfaces between modules. Global variables are for the internal implementation of modules and should not be exposed as interfaces. + Global variables should be as centralized as possible. If the data of this module needs to be disclosed to external modules, a function as an interface to this data should be provided. -## Local Variables +## Local Variables + +### Rule 7.2 Do not use uninitialized variables as rvalues. -### Rule 7.2 Do not use uninitialized variables as rvalues. +The variable here refers to a local dynamic variable, and also includes a memory block obtained on a memory heap. -The variable here refers to a local dynamic variable, and also includes a memory block obtained on a memory heap. Because their initial values are unpredictable, it is prohibited to use them directly as rvalues without effective initialization. ```c @@ -1887,12 +1969,15 @@ void Foo(...) } ``` -Uninitialized rvalues can be found by generic static check tools. +Uninitialized rvalues can be found by generic static check tools. + For example, the PCLint tool reports a warning for the following two examples. -> Warning 530: Symbol 'data' (line ...) not initialized Warning 644: Variable 'data' (line ...) may not have been initialized +> Warning 530: Symbol 'data' (line ...) not initialized +> +> Warning 644: Variable 'data' (line ...) may not have been initialized -### Rule 7.3 Forbid invalid and redundant variable initialization. +### Rule 7.3 Forbid invalid and redundant variable initialization. If the initial value is not determined before initialization is performed, it is not concise or secure and may cause problems that are more difficult to discover. @@ -1939,41 +2024,53 @@ void Foo(...) ``` In the preceding code, if 0 is not assigned before initialization, the static check tool can help find the problem of "direct use without being initialized". + However, due to invalid initialization, the defect of placing "UseData" before "GetData" cannot be easily found. Therefore, simple code should be written to initialize variables or memory blocks as required. The C99 does not limit the definition position of local variables to before the first statement in a function. That is, a variable can now be defined close to a variable. + This concise approach not only limits the scope of the variable scope, but also solves the problem of how to initialize the variable when it is defined. + If this compilation environment is supported, you are advised to define local variables in this way. **Exceptions:** + **As 'Secure Coding Standard' required, pointers, resource variables, and boolean variables can be treated as exceptions of this rule.** -### Rule 7.4 Do not use magic numbers. +### Rule 7.4 Do not use magic numbers. + +The so-called magic numbers are the numbers that are unintelligible and difficult to understand. -The so-called magic numbers are the numbers that are unintelligible and difficult to understand. The magic number is not a concept that can be defined literally. It varies depending on context and service knowledge. -For example, the number 12 varies in different contexts. -`type = 12;` is not intelligible, but `month = year * 12;` can be understood. +For example, the number 12 varies in different contexts. + +`type = 12;` is not intelligible, but `month = year * 12;` can be understood. + The number 0 is sometimes seen as a magic number. For example, the `status = 0;` cannot truly express any status information. -Solution: -Comments can be added for numbers that are used only once. +Solution: + +Comments can be added for numbers that are used only once. + For numbers that are used multiple times, macro or const variables must be defined and self-commented with symbolic naming. -The following cases are forbidden: -The name is not used to explain the meaning of a number, for example, `#define ZERO 0`. +The following cases are forbidden: + +The name is not used to explain the meaning of a number, for example, `#define ZERO 0`. + The value is limited by the name, for example, `#define XX_TIMER_INTERVAL_300MS 300`. -# 8 Programming Practice +# 8 Programming Practice -## Expressions +## Expressions -### Rec 8.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged. +### Rec 8.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged. + +When a variable is compared with a constant, placing the constant on the left, for example, `if (MAX == v)` does not read naturally, and `if (MAX > v)` is more difficult to understand. -When a variable is compared with a constant, placing the constant on the left, for example, `if (MAX == v)` does not read naturally, and `if (MAX > v)` is more difficult to understand. The constant should be placed on the right according to the normal reading order and habit. The expression is written as follows: ```c @@ -1985,9 +2082,10 @@ There are special cases: for example, the expression `if (MIN < v && v < MAX)` i You do not need to worry about accidentally writing '==' as '=' because a compilation alarm will be generated for `if (v = MAX)` and an error will be reported by other static check tools. Use these tools to solve such writing errors and ensure that that code is readable. -### Do not reference a variable again in an expression containing an increment (++) or decrement (--) operator. +### Do not reference a variable again in an expression containing an increment (++) or decrement (--) operator. In an expression containing a variable increment or decrement operator, if the variable is referenced again, the result is not explicitly defined in the C standard, which may vary between compilers or different compiler versions. + For better portability, you should not make any assumptions about the operation sequence not defined in any standards. Note that this problem cannot be solved by using parentheses because it is not a problem of priority. @@ -2018,9 +2116,10 @@ i++; // Good: Single line. x = Func(i, i); ``` -### Rec 8.2 Use parentheses to specify the sequence of expressions, instead of using the default priority. +### Rec 8.2 Use parentheses to specify the sequence of expressions, instead of using the default priority. Parentheses can be used to better emphasize the purpose of used operators. This will prevent program errors due to the inconsistency between default priority and the intended design. + However, too many parentheses muddy the code, reducing readability. Use them moderately. Parentheses are recommended when expressions contain operators that are not commonly used and are confusing, such as bitwise operators. @@ -2029,14 +2128,16 @@ Parentheses are recommended when expressions contain operators that are not comm c = (a & 0xFF) + b; /* Parentheses are required while using bit operators. */ ``` -## Statements +## Statements -### Rule 8.2 Provide a 'default' branch for the `switch` statement. +### Rule 8.2 Provide a 'default' branch for the `switch` statement. In most cases, the 'default' branch exists in the switch statement to ensure that there is a default processing action when the case tag is missing. Exceptions: -If the switch condition variable is of the enum type and the case branches cover all values, then the default branch is redundant. + +If the switch condition variable is of the enum type and the case branches cover all values, then the default branch is redundant. + A modern compiler can check whether the case branch of some enumerated values is missing in the switch statement. A warning will be displayed. ```c @@ -2057,11 +2158,12 @@ switch (color) { } ``` -### Rec 8.3 Exercise caution when using the `goto` statement. +### Rec 8.3 Exercise caution when using the `goto` statement. The `goto` statement destroys the program. Avoid using it if possible. You can only jump to statements following the `goto` statement, and only within the one function. The `goto` statement is used to implement function return to a single point within a function. + If a function has a large number of identical logics that cannot be encapsulated, for example, repeated file execution, the processed part of code after the file operation failure (for example, closing the file handle and releasing memory that is dynamically applied for) is usually placed in the last part of the function body. And the goto statement is placed right before these. In this way, the code becomes clear and concise. It can also be encapsulated in functions or macros, but doing so makes code less straightforward. Example: @@ -2106,9 +2208,9 @@ EXIT: } ``` -## Type Conversion +## Type Conversion -### Rec 8.4 Minimize unnecessary type conversion and forced conversion. +### Rec 8.4 Minimize unnecessary type conversion and forced conversion. When the data type is forcibly changed, the meaning of the data and the value after conversion may change. If details are not considered, potential risks may be generated. diff --git a/en/contribute/code-of-conduct.md b/en/contribute/code-of-conduct.md index 6eea0059c3d2d38781a6d251bab7f639fe297fcd..09ba997e09eb252f1b30fd14cb63897658abf11e 100755 --- a/en/contribute/code-of-conduct.md +++ b/en/contribute/code-of-conduct.md @@ -1,4 +1,4 @@ -# Code of Conduct +# Code of Conduct The OpenHarmony community complies with the code of conduct specified in [Contributor Covenant](https://contributor-covenant.org/) of the open source community. For details, see [https://www.contributor-covenant.org/version/1/4/code-of-conduct/](https://www.contributor-covenant.org/version/1/4/code-of-conduct/). diff --git a/en/contribute/how-to-contribute.md b/en/contribute/how-to-contribute.md index 0e1f8ab9365b1a7f8c3c299992d6a816b02c89b6..1ee14278b36d16978cd1bfc61c8d98abc7538f34 100644 --- a/en/contribute/how-to-contribute.md +++ b/en/contribute/how-to-contribute.md @@ -1,8 +1,8 @@ -# How to Contribute +# How to Contribute -## Contributing Code +## Contributing Code -## Before You Start +## Before You Start **Signing the Developer Certificate of Origin** @@ -12,25 +12,25 @@ Click [here](https://dco.openharmony.cn/#/sign) to sign the DCO, and click [here **Code of Conduct** -OpenHarmony is an open source community that relies entirely on the friendly, welcoming environment of the community. Read and abide by the community's [Code of Conduct](code-of-conduct.md#EN-US_TOPIC_0000001055368056) before contributing to the community. +OpenHarmony is an open source community that relies entirely on the friendly, welcoming environment of the community. Read and abide by the community's [Code of Conduct](code-of-conduct.md) before contributing to the community. ## **Finding the SIG Group You Are Interested** For details about how to participate in Special Interest Group (SIG), see **SIG Governance**. -## Starting Contributing +## Starting Contributing -For details about how to contribute to code, see [Code Contributing ](code-contribution.md). +For details about how to contribute to code, see [Code Contributing ](code-contribution.md). ## Auto-Test For details about how to develop test cases based on test requirements, see [Test Subsystem](../readme/test.md). -## Contributing Documents +## Contributing Documents -For details, see [Documentation Contribution](documentation-contribution.md). +For details, see [Documentation Contribution](documentation-contribution.md). -## Communication in Community +## Communication in Community -For details, see [Communication in Community](communication-in-community.md#EN-US_TOPIC_0000001054608107). +For details, see [Communication in Community](communication-in-community.md). diff --git a/en/contribute/template/js-template.md b/en/contribute/template/js-template.md index 730e34660723b900e84861fa40e0df1fb8f144e9..3b165dfeb546f502ee80c91c0d034549d2c5006d 100644 --- a/en/contribute/template/js-template.md +++ b/en/contribute/template/js-template.md @@ -96,7 +96,7 @@ import call from '@ohos.telephony.call'; | Name | Type | Readable| Writable| Description | | ---------------- | ----------------------------------------- | ---- | ---- | ------------------------------------------ | -| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. | +| pluggedType | [BatteryPluggedType]\(#batterypluggedtype) | Yes | No | Charger type of the current device. | | isBatteryPresent | boolean | Yes | No | Whether the battery is supported or present.| ## Methods @@ -270,7 +270,7 @@ The following is an example of the custom type of a key-value pair. | Name | Type | Readable| Writable| Description | | ------------ | ------------------- | ---- | ---- | ------------------------------------------------------------ | | parameterUrl | string | Yes | Yes | Media output URI. Supported:
1. Relative path whose protocol type is `internal`. Example:
Temporary directory: internal://cache/test.mp4
2. Absolute path. Example:
file:///data/data/ohos.xxx.xxx/files/test.mp4| -| parameterOne | [CustomEnum](#Enumeration)| Yes | Yes | Describe the attributes. The requirements are similar to those for the parameter description. | +| parameterOne | [CustomEnum](#enums) | Yes | Yes | Describe the attributes. The requirements are similar to those for the parameter description. | ## Change History | Change Description| Date| diff --git a/en/device-dev/guide/device-iotcamera-control-demo-photodevguide.md b/en/device-dev/guide/device-iotcamera-control-demo-photodevguide.md deleted file mode 100644 index 013f080c0dd6f0fb49f96ecf2cfa380290215f12..0000000000000000000000000000000000000000 --- a/en/device-dev/guide/device-iotcamera-control-demo-photodevguide.md +++ /dev/null @@ -1,391 +0,0 @@ -# Photographing - -## When to Use - -Use the camera module APIs to capture frames \(photographing\). - -## Available APIs - -**Table 1** APIs for photographing - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Class

-

Function

-

Description

-

CameraKit

-

int32_t GetCameraIds(std::list<string> cameraList)

-

Obtains IDs of cameras that are currently available.

-

CameraKit

-

CameraAbility& GetCameraAbility(string cameraId)

-

Obtains the camera capability

-

CameraKit

-

void RegisterCameraDeviceCallback(CameraDeviceCallback* callback, EventHandler* handler)

-

Registers a camera callback for camera status changes.

-

CameraKit

-

void UnregisterCameraDeviceCallback(CameraDeviceCallback* callback)

-

Unregisters a camera callback.

-

CameraKit

-

void CreateCamera(string cameraId, CameraStateCallback* callback, EventHandler* handler)

-

Creates a Camera instance.

-

Camera

-

string GetCameraId()

-

Obtains the camera ID.

-

Camera

-

CameraConfig& GetCameraConfig()

-

Obtains the camera configuration.

-

Camera

-

FrameConfig& GetFrameConfig(int32_t type)

-

Obtains the frame configuration.

-

Camera

-

void Configure(CameraConfig& config)

-

Configures the camera using the CameraConfig object.

-

Camera

-

void Release()

-

Releases the Camera object and associated resources.

-

Camera

-

int TriggerLoopingCapture(FrameConfig& frameConfig)

-

Starts looping-frame capture.

-

Camera

-

void StopLoopingCapture()

-

Stops looping-frame capture.

-

Camera

-

int32_t TriggerSingleCapture(FrameConfig& frameConfig)

-

Starts single-frame capture.

-

CameraConfig

-

void SetFrameStateCallback(FrameStateCallback* callback, EventHandler* handler);

-

Sets a frame state callback to respond to state changes.

-

CameraConfig

-

static CameraConfig* CreateCameraConfig()

-

Creates a CameraConfig instance.

-

CameraAbility

-

std::list<Size> GetSupportedSizes(int format)

-

Obtains the supported image sizes for a specified image format.

-

CameraAbility

-

std::list<T> GetParameterRange(uint32_t key)

-

Obtains the parameter value range based on a specified parameter key.

-

CameraDevice

-

CameraDeviceCallback()

-

A constructor used to create a CameraDeviceCallback instance.

-

CameraDevice

-

void OnCameraStatus​(std::string cameraId, int32_t status)

-

Called when the camera device status changes.

-

CameraStateCallback

-

CameraStateCallback​()

-

A constructor used to create a CameraStateCallback instance.

-

CameraStateCallback

-

void OnConfigured​(Camera& camera)

-

Called when the camera is configured.

-

CameraStateCallback

-

void OnConfigureFailed​(Camera& camera,int32_t errorCode)

-

Called when the camera fails to be configured.

-

CameraStateCallback

-

void OnCreated​(Camera& camera)

-

Called when the camera is successfully created.

-

CameraStateCallback

-

void OnCreateFailed​(std::string cameraId,int32_t errorCode)

-

Called when the camera fails to be created.

-

CameraStateCallback

-

void OnReleased​(Camera& camera)

-

Called when the camera is released.

-

FrameStateCallback

-

FrameStateCallback​()

-

A constructor used to create a FrameStateCallback instance.

-

FrameStateCallback

-

void OnFrameFinished(Camera& camera, FrameConfig& frameConfig, FrameResult& frameResult)

-

Called when the frame capture is completed.

-

FrameStateCallback

-

void OnFrameError​(Camera& camera, FrameConfig& frameConfig, int32_t errorCode, FrameResult& frameResult)

-

Called when the frame capture fails.

-

FrameConfig

-

int32_t GetFrameConfigType()

-

Obtains the frame configuration type.

-

FrameConfig

-

std::list<OHOS::Surface> GetSurfaces()

-

Obtains a list of surface objects (shared memories).

-

FrameConfig

-

void AddSurface(OHOS::AGP::UISurface& surface);

-

Adds a surface.

-

FrameConfig

-

void RemoveSurface(OHOS::AGP::UISurface& surface);

-

Removes a surface.

-
- -## Limitations and Constraints - -None - -## How to Develop - -1. Extend the **CameraDeviceCallback** class and call **OnCameraStatus** to customize operations when the camera device changes, for example, when a camera becomes available or unavailable. - - ``` - class SampleCameraDeviceCallback : public CameraDeviceCallback { - void OnCameraStatus(std::string cameraId, int32_t status) override - { - // Do something when camera is available or unavailable. - } - }; - ``` - -2. Extend the **FrameStateCallback** class. After obtaining the frame data, save the data as a file. - - ``` - static void SampleSaveCapture(const char *p, uint32_t size) - { - cout << "Start saving picture" << endl; - struct timeval tv; - gettimeofday(&tv, NULL); - struct tm *ltm = localtime(&tv.tv_sec); - if (ltm != nullptr) { - ostringstream ss("Capture_"); - ss << "Capture" << ltm->tm_hour << "-" << ltm->tm_min << "-" << ltm->tm_sec << ".jpg"; - - ofstream pic("/sdcard/" + ss.str(), ofstream::out | ofstream::trunc); - cout << "write " << size << " bytes" << endl; - pic.write(p, size); - cout << "Saving picture end" << endl; - } - } - - class TestFrameStateCallback : public FrameStateCallback { - void OnFrameFinished(Camera &camera, FrameConfig &fc, FrameResult &result) override - { - cout << "Receive frame complete inform." << endl; - if (fc.GetFrameConfigType() == FRAME_CONFIG_CAPTURE) { - cout << "Capture frame received." << endl; - list surfaceList = fc.GetSurfaces(); - for (Surface *surface : surfaceList) { - SurfaceBuffer *buffer = surface->AcquireBuffer(); - if (buffer != nullptr) { - char *virtAddr = static_cast(buffer->GetVirAddr()); - if (virtAddr != nullptr) { - SampleSaveCapture(virtAddr, buffer->GetSize()); - } - surface->ReleaseBuffer(buffer); - } - delete surface; - } - delete &fc; - } - } - }; - ``` - -3. Extend the **CameraStateCallback** class and customize operations when the camera state changes \(configuration successful or failed, and creation successful or failed\). - - ``` - class SampleCameraStateMng : public CameraStateCallback { - public: - SampleCameraStateMng() = delete; - SampleCameraStateMng(EventHandler &eventHdlr) : eventHdlr_(eventHdlr) {} - ~SampleCameraStateMng() - { - if (recordFd_ != -1) { - close(recordFd_); - } - } - void OnCreated(Camera &c) override - { - cout << "Sample recv OnCreate camera." << endl; - auto config = CameraConfig::CreateCameraConfig(); - config->SetFrameStateCallback(&fsCb_, &eventHdlr_); - c.Configure(*config); - cam_ = &c; - } - void OnCreateFailed(const std::string cameraId, int32_t errorCode) override {} - void OnReleased(Camera &c) override {} - }; - ``` - -4. Create a **CameraKit** instance to set and obtain camera information. - - ``` - CameraKit *camKit = CameraKit::GetInstance(); - list camList = camKit->GetCameraIds(); - string camId; - for (auto &cam : camList) { - cout << "camera name:" << cam << endl; - const CameraAbility *ability = camKit->GetCameraAbility(cam); - /* Find the camera that fits your ability. */ - list sizeList = ability->GetSupportedSizes(0); - if (find(sizeList.begin(), sizeList.end(), CAM_PIC_1080P) != sizeList.end()) { - camId = cam; - break; - } - } - ``` - -5. Create a **Camera** instance. - - ``` - EventHandler eventHdlr; // Create a thread to handle callback events. - SampleCameraStateMng CamStateMng(eventHdlr); - - camKit->CreateCamera(camId, CamStateMng, eventHdlr); - ``` - -6. Based on the callback design in steps 1 to 3, perform related operations until the **OnCreated** callback obtains **cam\_**. - - ``` - void OnCreated(Camera &c) override - { - cout << "Sample recv OnCreate camera." << endl; - auto config = CameraConfig::CreateCameraConfig(); - config->SetFrameStateCallback(&fsCb_, &eventHdlr_); - c.Configure(*config); - cam_ = &c; - } - - void Capture() - { - if (cam_ == nullptr) { - cout << "Camera is not ready." << endl; - return; - } - FrameConfig *fc = new FrameConfig(FRAME_CONFIG_CAPTURE); - Surface *surface = Surface::CreateSurface(); - if (surface == nullptr) { - delete fc; - return; - } - surface->SetWidthAndHeight(1920, 1080); /* 1920:width,1080:height */ - fc->AddSurface(*surface); - cam_->TriggerSingleCapture(*fc); - } - ``` - - diff --git a/en/device-dev/guide/device-iotcamera-control-demo-videodevguide.md b/en/device-dev/guide/device-iotcamera-control-demo-videodevguide.md deleted file mode 100644 index 96afe8a9d7a728e705e56b803619f02e95c4be9b..0000000000000000000000000000000000000000 --- a/en/device-dev/guide/device-iotcamera-control-demo-videodevguide.md +++ /dev/null @@ -1,38 +0,0 @@ -# Video Recording - -## When to Use - -Use the camera module APIs to capture video streams. - -## Available APIs - -For details, see the available APIs described in development guidelines on photographing. - -## Limitations and Constraints - -None - -## How to Develop - -1. Perform step 1 through step 4 described in development guidelines on photographing. -2. Obtain the **FrameConfig** instance for audio recording. - - ``` - /* Obtain the surface from the recorder. */ - Surface *surface = recorder_->GetSurface(0); - surface->SetWidthAndHeight(1920, 1080); - surface->SetQueueSize(3); - surface->SetSize(1024 * 1024); - /* Add the surface to the FrameConfig instance. */ - FrameConfig *fc = new FrameConfig(FRAME_CONFIG_RECORD); - fc->AddSurface(*surface); - ``` - -3. Start and stop video recording. - - ``` - stateCallback->camera_->TriggerLoopingCapture(*fc); // Start recording. - stateCallback->camera_->StopLoopingCapture(); // Stop recording. - ``` - - diff --git a/en/device-dev/guide/device-iotcamera-control-example.md b/en/device-dev/guide/device-iotcamera-control-example.md deleted file mode 100644 index e13ad94f9036eba83d7d9bf157d72dbe127a3d6a..0000000000000000000000000000000000000000 --- a/en/device-dev/guide/device-iotcamera-control-example.md +++ /dev/null @@ -1,45 +0,0 @@ -# Use Case - -- For details about the development board, compilation, burning, and image running, see [Quick Start](../quick-start/Readme-EN.md). A compilation result file of sample code is stored in **out/ipcamera\_hi3518ev300/dev\_tools/bin/camera\_sample**. You can copy the file to a TF card, or modify the compilation script of **camera\_sample** to copy the result to **rootfs.img**. - - Modify **output\_dir** in **applications/sample/camera/media/BUILD.gn**. - - - Before: **output\_dir = "$root\_out\_dir/dev\_tools"** - - After: **output\_dir = "$root\_out\_dir/"** - - Recompile the source code repository and burn the code into the development board. Then you can find the **camera\_sample** file in the **bin** directory of the board. - -- The sample code for camera development is stored in **applications/sample/camera/media/camera\_sample.cpp**. - - >![](../public_sys-resources/icon-notice.gif) **NOTICE:** - >You should insert a TF card \(maximum capacity: 128 GB\) for photographing and video recording functions. After the system is started, the TF card is automatically mounted to the **/sdcard** directory. If the TF card is inserted after the system is started, you have to manually mount the TF card. To view the photos and videos in the TF card, copy the content to a computer. The preview function does not require a TF card. - - -1. Run the **cd** command to go to the end path of the executable program and start **camera\_sample** by running the command in the following figure. - - **Figure 1** Starting camera\_sample - ![](figures/starting-camera_sample.png "starting-camera_sample") - - The control commands are displayed as shown in the preceding figure. Press **S** to stop the current operation \(including video recording and preview\), and press **Q** to exit the program. - -2. Press **1** to take a photo in JPG format. The photo is saved in the **/sdcard** directory and named **Capture\***. - - **Figure 2** Serial port logs displayed after the photographing command is executed - ![](figures/serial-port-logs-displayed-after-the-photographing-command-is-executed.png "serial-port-logs-displayed-after-the-photographing-command-is-executed") - - To view the saved file, exit the program and enter the file system. To start the program again, return to the previous step. - - **Figure 3** Saved files - ![](figures/saved-files.png "saved-files") - -3. Press **2** to start recording. The video file is in MP4 format and saved in the **/sdcard** directory with the name **Record\***. Press **S** to stop recording. - - **Figure 4** Serial port logs displayed after the recording command is executed - ![](figures/serial-port-logs-displayed-after-the-recording-command-is-executed.png "serial-port-logs-displayed-after-the-recording-command-is-executed") - -4. Press **Q** to exit. - - **Figure 5** Serial port logs displayed after the exit command is executed - ![](figures/serial-port-logs-displayed-after-the-exit-command-is-executed.png "serial-port-logs-displayed-after-the-exit-command-is-executed") - - diff --git a/en/device-dev/guide/device-iotcamera-control-overview.md b/en/device-dev/guide/device-iotcamera-control-overview.md deleted file mode 100644 index d67f97231ed8c18469818d1d0e1c43cb69ab1141..0000000000000000000000000000000000000000 --- a/en/device-dev/guide/device-iotcamera-control-overview.md +++ /dev/null @@ -1,10 +0,0 @@ -# Camera Control Overview - -This document describes how to use the IoT camera development board and the built-in camera of the development kit to implement photographing and video recording. - -You can perform operations provided in [Use Case](device-iotcamera-control-example.md) to learn more about development board peripheral control and then develop devices such as cameras. - -If you want to view the sample effect first, see [Use Case](device-iotcamera-control-example.md). To customize application behavior, modify the sample code by referring to APIs described in the next section. - -For details about basic concepts for camera development, see [Camera Overview](../subsystems/subsys-multimedia-camera-overview.md). - diff --git a/en/device-dev/kernel/kernel-mini-appx-code.md b/en/device-dev/kernel/kernel-mini-appx-code.md index 715a5dd6f51a7e148341489d8e55f4e176862ca4..188d3da02f28bc9174eb39e15f2e5219e2baca2b 100644 --- a/en/device-dev/kernel/kernel-mini-appx-code.md +++ b/en/device-dev/kernel/kernel-mini-appx-code.md @@ -1,4 +1,4 @@ -# Kernel Coding Specification +# Kernel Coding Specification This kernel coding specification is developed based on the general programming specifications in the industry. It defines the programming styles for kernel developers to follow. diff --git a/en/device-dev/security/security-guidelines-overall.md b/en/device-dev/security/security-guidelines-overall.md index 8c551e4d29637b69eb9d81437eb5360e87bad324..e3c6685ab0b5052b7e15780e0c1f45381e9479cc 100644 --- a/en/device-dev/security/security-guidelines-overall.md +++ b/en/device-dev/security/security-guidelines-overall.md @@ -94,7 +94,7 @@ For device with 128 KB to 128 MB of memory, the OpenHarmony lite kernel is recom - Secure boot must be enabled, and the trusted root must be in the chip and cannot be modified. In addition, you must consider the impact of secure upgrade (if available) on secure boot, that is, the signature or hash value of an image file must be updated after a secure upgrade. -## Data security +## Data Security ### Security Mechanism diff --git a/en/device-dev/security/security-privacy-protection.md b/en/device-dev/security/security-privacy-protection.md index 71557e17c7a2dde14fba1752b0fcb9d0b0d1b853..334f54d53554bd63054b2531de815f077db96e06 100644 --- a/en/device-dev/security/security-privacy-protection.md +++ b/en/device-dev/security/security-privacy-protection.md @@ -1,6 +1,6 @@ -# Privacy Protection +# Privacy Protection -## Overview +## Overview Personal data plays an increasingly important role in social economy and daily life along with the development of the Internet and informatization. Meanwhile, personal data leakage risks are increasing. As consumer product developers, you shall take more effective measures to protect users' personal data and improve their trust in your products. To protect consumers' privacy and improve their experience on privacy, you should set high-level privacy protection policies for your product. @@ -49,7 +49,7 @@ Personal data plays an increasingly important role in social economy and daily l - Users provide information proactively, such as scenarios where a user enters their identification number and bank card number to bind the bank card. -## Data Classification +## Data Classification Data is classified into five levels: very high, high, moderate, low, and public based on the data protection objectives and consequences \(the impact of legal risks caused by data leakage or damage on individuals, organizations, or the public\). @@ -116,7 +116,7 @@ Data is classified into five levels: very high, high, moderate, low, and public Note: For details about the definitions of privacy protection and data classification, see GDPR. -## General Privacy Design Rules +## General Privacy Design Rules To help you better complete privacy design for OpenHarmony products, we sort out general privacy design requirements. @@ -133,7 +133,7 @@ When collecting personal data, clearly and explicitly notify users of the data t Guided by the preceding principles, we have designed some examples for your reference. The figures below are examples of a privacy notice and a privacy statement, respectively. - **Figure 1** Examples of a privacy notice and a privacy statement + **Figure 1** Examples of a privacy notice and a privacy statement ![](figure/privacy-notice.png)![](figure/privacy-statement.png) @@ -190,9 +190,9 @@ You shall obtain consent from users and comply with applicable laws and regulati Data processing security shall be ensured in technical terms, which include encrypted data storage and secure data transfer. Security mechanisms or measures shall be enabled by default for a system. -- A protection mechanism shall be available for personal data access, including identity authentication and access control. Identity authentication \(such as username and password\) allows only authenticated users to access data in multi-user scenarios. Access control \(for example, [permission control](security-guidelines-overall.md#section852593153614)\) can be applied to restrict access to applications. +- A protection mechanism shall be available for personal data access, including identity authentication and access control. Identity authentication \(such as username and password\) allows only authenticated users to access data in multi-user scenarios. Access control \(for example, [permission control](../security/security-guidelines-overall.md)\) can be applied to restrict access to applications. - Secure storage of personal data on distributed devices must meet Huawei Universal Keystore \(HUKS\) requirements, including secure storage of keys and data. -- The transfer of personal data between distributed devices must meet the trust binding relationship between devices and security requirements of data transmission channels. For details, see [Security Guidelines](security-guidelines-overall.md#section26153183616). +- The transfer of personal data between distributed devices must meet the trust binding relationship between devices and security requirements of data transmission channels. For details, see [Device Interconnection Security](../security/security-guidelines-overall.md#device-interconnection-security). - Authentication data \(such as passwords and fingerprints\) shall be encrypted before being stored. **Localization** @@ -203,7 +203,7 @@ User data shall be preferentially processed on the local device. Data that canno If your product is designed for minors or you can identify, based on the collected user age data, that the end user is a minor, you shall particularly analyze issues related to minors' personal data protection based on relevant national laws in the target market. Your product shall obtain explicit consent from the holders of parental responsibility over minors. -## **Privacy Protection Requirements for Special Categories** +## **Privacy Protection Requirements for Special Categories** In addition to these general privacy requirements, consumer hardware products have the following requirements for special categories. You shall comply with these requirements during product design. diff --git a/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md b/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md index 0a65ca9e584e80c6b1bf8662c85e8759b4711750..d1cca7c960f6e22ba52860f799b9fa3e2994338b 100644 --- a/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md +++ b/en/device-dev/subsystems/subsys-ai-aiframework-devguide.md @@ -1,4 +1,4 @@ -# AI Framework Development Guide +# AI Framework Development ## **Overview** diff --git a/en/device-dev/subsystems/subsys-dfx-hitracechain.md b/en/device-dev/subsystems/subsys-dfx-hitracechain.md index 6639011302e78ba1e9931b24362c5790c24dd4a3..8e7ded998f75f6fde34134a1240486193431058d 100644 --- a/en/device-dev/subsystems/subsys-dfx-hitracechain.md +++ b/en/device-dev/subsystems/subsys-dfx-hitracechain.md @@ -1,10 +1,10 @@ -# HiTraceChain Development +# HiTraceChain Development -## Overview +## Overview HiTraceChain tracks the call chain with the same **traceid** throughout the inter-device, inter-process, and inter-thread service processes. It associates and displays the call relationship and various output information during the entire process, helping you analyze and locate faults and optimize the system. -## Use Cases +## Use Cases HiTraceChain can be used for the following purposes: @@ -14,32 +14,36 @@ HiTraceChain can be used for the following purposes: - Works with the IDE to debug the detailed service process and time consumption distribution for system optimization. - **Figure 1** Use cases of HiTraceChain + **Figure 1** Use cases of HiTraceChain + ![](figure/use-cases-of-hitrace.png "use-cases-of-hitrace") -### Usage Example +### Usage Example + +**Figure 2** Service calling process \(inter-device and inter-process synchronous call\) -**Figure 2** Service calling process \(inter-device and inter-process synchronous call\) ![](figure/service-calling-process-(inter-device-and-inter-process-synchronous-call).png "service-calling-process-(inter-device-and-inter-process-synchronous-call)") -1. Display the call relationship in the service process, analyze key paths and function dependency, and determine the time consumption and call frequency at each call point to detect performance bottlenecks. +1. Display the call relationship in the service process, analyze key paths and function dependency, and determine the time consumption and call frequency at each call point to detect performance bottlenecks. + + **Figure 3** Service calling process - **Figure 3** Service calling process - ![](figure/service-calling-process.png "service-calling-process") + ![](figure/service-calling-process.png "service-calling-process") - **Figure 4** Time delay in the service calling process - ![](figure/time-delay-in-the-service-calling-process.png "time-delay-in-the-service-calling-process") + **Figure 4** Time delay in the service calling process + + ![](figure/time-delay-in-the-service-calling-process.png "time-delay-in-the-service-calling-process") 2. Add **traceid** to logs and events automatically to facilitate comprehensive analysis and quick fault location. -## Available APIs +## Available APIs HiTraceChain provides C++ and C APIs. The upper-layer services mainly use HiTraceChain to start and stop call chain tracing. HiTraceChain is implemented at layer C. It works by transferring **traceid** throughout the service calling process. Before service processing, HiTraceChain sets **traceid** in the thread local storage \(TLS\) of the calling thread. During service processing, HiTraceChain obtains **traceid** from the contextual TLS of the calling thread and automatically adds it to the log and event information. After service processing is complete, HiTraceChain clears **traceid** from the TLS of the calling thread. -### Java, C++, and C APIs +### Java, C++, and C APIs **Table 1** Description of C++ and C APIs @@ -195,7 +199,7 @@ HiTraceChain is implemented at layer C. It works by transferring **traceid** t -### Parameters of C++ APIs +### Parameters of C++ APIs **Table 2** Parameters of C++ APIs @@ -428,7 +432,7 @@ HiTraceChain is implemented at layer C. It works by transferring **traceid** t -## Call Chain Processing +## Call Chain Processing Inter-device, inter-process, and inter-thread calls are implemented through the communication mechanism. **HiTraceChain** requires transfer of **traceid** in the communication mechanism. @@ -438,7 +442,8 @@ The following figure shows the process of transferring **traceid** in synchron Extended communication mechanisms can also follow this implementation. -**Figure 5** Call chain tracing in synchronous communication +**Figure 5** Call chain tracing in synchronous communication + ![](figure/call-chain-tracing-in-synchronous-communication.png "call-chain-tracing-in-synchronous-communication") The process is as follows: @@ -471,9 +476,9 @@ The process is as follows: 8. The service module on the client processes the transact reply response. 9. When the process ends, the service module on the client calls the **end\(\)** function to stop call chain tracing. -## How to Develop +## How to Develop -### C++ +### C++ 1. Develop the source code. @@ -499,7 +504,7 @@ The process is as follows: ``` -### C +### C 1. Develop the source code. diff --git a/en/device-dev/subsystems/subsys-tel-guide.md b/en/device-dev/subsystems/subsys-tel-guide.md index 9b204051bd6742a6cd6afbf550d67f8ac8186c9e..9ddc0393b11c42349822e2dbd1d30d8875d848c4 100644 --- a/en/device-dev/subsystems/subsys-tel-guide.md +++ b/en/device-dev/subsystems/subsys-tel-guide.md @@ -1,8 +1,8 @@ -# Telephony Development +# Telephony Development -## Initializing a Modem Vendor Library +## Initializing a Modem Vendor Library -### When to Use +### When to Use Initializing a modem vendor library means to implement **const HRilOps \*RilInitOps\(const struct HRilReport \*reportOps\)** function in the vendor library. This function is mainly used to: @@ -10,17 +10,17 @@ Initializing a modem vendor library means to implement **const HRilOps \*RilInit - Create a thread for reading modem nodes. In this thread, the data reported by the modem is read cyclically and parsed as a specific service event for reporting. - Return the function pointer of the service request API to RIL Adapter. -### Available APIs +### Available APIs The following table describes the API for initializing a modem vendor library. **Table 1** API for initializing a modem vendor library -| API | Description | +| API | Description | | -------- | -------- | -| const HRilOps \*RilInitOps(const struct HRilReport \* reportOps) | Provides an entry for running a modem vendor library.
Input parameter:
**reportOps**: Specifies the pointer to the event callback function, which is passed by RIL Adapter.
Return result: function pointer of the service request API. | +| const HRilOps \*RilInitOps(const struct HRilReport \* reportOps) | Provides an entry for running a modem vendor library.
Input parameter:
**reportOps**: Specifies the pointer to the event callback function, which is passed by RIL Adapter.
Return result: function pointer of the service request API. | -### How to Develop +### How to Develop 1. Set the event callback function pointers passed by RIL Adapter through **RilInitOps**. @@ -37,7 +37,7 @@ The following table describes the API for initializing a modem vendor library. ``` -1. Create the **g\_reader** main thread to enable message looping. +2. Create the **g\_reader** main thread to enable message looping. ``` pthread_attr_t t; @@ -47,7 +47,7 @@ The following table describes the API for initializing a modem vendor library. ``` -1. In the **g\_eventListeners** thread, use **open\(\)** to open a modem node and then create the **g\_reader** thread to read and process messages reported by the modem. +3. In the **g\_eventListeners** thread, use **open\(\)** to open a modem node and then create the **g\_reader** thread to read and process messages reported by the modem. ``` g_fd = open(g_devicePath, O_RDWR); // Open the device node specified by g_devicePath. @@ -57,7 +57,7 @@ The following table describes the API for initializing a modem vendor library. ``` -1. Return the function pointer of the service request API. +4. Return the function pointer of the service request API. ``` // Structure for the service request API of the call module @@ -105,9 +105,9 @@ The following table describes the API for initializing a modem vendor library. ``` -### Debugging and Verification +### Debugging and Verification -1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#preparations) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. For details about how to integrate a library file, see [Integrating Modem Vendor Libraries](#section590mcpsimp). +1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#how-to-obtain) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. For details about how to integrate a library file, see [Integrating Modem Vendor Libraries](#integrating-modem-vendor-libraries). ``` hdc_std file send libril_vendor.z.so /system/lib/ @@ -128,24 +128,24 @@ The following table describes the API for initializing a modem vendor library. ``` -## Responding to Modem Service Requests +## Responding to Modem Service Requests -### When to Use +### When to Use After receiving a specific telephony service request, RIL Adapter calls the target function pointer obtained in modem vendor library initialization to send a specific service request to the vendor library. Then, the vendor library processes the request based on the request ID. -### Available APIs +### Available APIs The following table describes the APIs for responding to modem service requests, with the dial module as an example. **Table 2** APIs for responding to modem service requests -| API | Description | +| API | Description | | -------- | -------- | -| void ReqDial(ReqDataInfo \*requestInfo, const void \*data, size_t dataLen); | Processes number dial requests.
Input parameters:
**requestInfo**: request type
**data**: called number
**dataLen**: data length
Return value: none | -| void (\*OnCallReport)(struct ReportInfo reportInfo, const void \*data, size_t dataLen); | Reports the execution result of a service request to RIL Adapter.
Input parameters:
**reportInfo**: request type
**data**: called number
**dataLen**: data length
Return value: none | +| void ReqDial(ReqDataInfo \*requestInfo, const void \*data, size_t dataLen); | Processes number dial requests.
Input parameters:
**requestInfo**: request type
**data**: called number
**dataLen**: data length
Return value: none | +| void (\*OnCallReport)(struct ReportInfo reportInfo, const void \*data, size_t dataLen); | Reports the execution result of a service request to RIL Adapter.
Input parameters:
**reportInfo**: request type
**data**: called number
**dataLen**: data length
Return value: none | -### How to Develop +### How to Develop 1. Implement processing of dial requests in the **ReqDial\(\)** API. @@ -199,9 +199,9 @@ The following table describes the APIs for responding to modem service requests, ``` -### Debugging and Verification +### Debugging and Verification -1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#preparations) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. +1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#how-to-obtain) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. ``` hdc_std file send libril_vendor.z.so /system/lib/ @@ -242,23 +242,23 @@ The following table describes the APIs for responding to modem service requests, ``` -## Reporting Modem Events +## Reporting Modem Events -### When to Use +### When to Use A modem node thread reads the messages reported by the modem cyclically, parses the messages into specific events, and then reports the events to RIL Adapter. -### Available APIs +### Available APIs The following table describes the API for reporting modem events. **Table 3** API for reporting modem events -| API | Description | +| API | Description | | -------- | -------- | -| void OnNotifyOps(const char \*s, const char \*smsPdu) | Distributes the events reported by the modem.
Input parameters:
**s**: AT command prefix
**smsPdu**: PDU of the SMS message
Return value: none | +| void OnNotifyOps(const char \*s, const char \*smsPdu) | Distributes the events reported by the modem.
Input parameters:
**s**: AT command prefix
**smsPdu**: PDU of the SMS message
Return value: none | -### How to Develop +### How to Develop 1. Call **OnNotifyOps\(\)** in the g\_reader thread of the modem device node to parse reported modem events. On determining the command type, call **OnXxxReport\(\)** to report the parsed module events to the hril layer. @@ -290,7 +290,7 @@ The following table describes the API for reporting modem events. ``` -1. Distribute the reported events from the **hril** layer to the Telephony Service layer. +2. Distribute the reported events from the **hril** layer to the Telephony Service layer. ``` // Report the call status proactively. @@ -316,9 +316,9 @@ The following table describes the API for reporting modem events. ``` -### Debugging and Verification +### Debugging and Verification -1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#preparations) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. +1. Use the [hdc\_std](../subsystems/subsys-toolchain-hdc-guide.md#how-to-obtain) tool to connect to a debugging device. Then, run the following command to send the generated **libril\_vendor.z.so** library file to the **/system/lib/** directory of the device. ``` hdc_std file send libril_vendor.z.so /system/lib/ @@ -370,18 +370,18 @@ The following table describes the API for reporting modem events. ``` -### Development Examples +### Development Examples - **Outgoing Call** The following figure shows the API calling for an outgoing call. **Figure 1** Time sequence of API calling for an outgoing call - + ![](figure/en-us_image_0000001171507146.png) - When an application initiates an outgoing call, RIL Adapter receives a call request, and the **hril** layer invokes the **ReqDial\(\)** function. In **ReqDial\(\)**, the data passed by the Telephony Service is encapsulated as an AT command and sent to the modem. After executing the dial command, the modem reports the execution result to RIL Adapter through **OnCallReport\(\)**. + When an application initiates an outgoing call, RIL Adapter receives a call request, and the **hril** layer invokes the **ReqDial\(\)** function. In **ReqDial\(\)**, the data passed by the Telephony Service is encapsulated as an AT command and sent to the modem. After executing the dial command, the modem reports the execution result to RIL Adapter through **OnCallReport\(\)**. ``` // Callback function pointer of the call module @@ -456,13 +456,13 @@ The following table describes the API for reporting modem events. The following figure shows the API calling of an incoming call. **Figure 2** Time sequence of API calling for an incoming call - + ![](figure/en-us_image_0000001214727595.png) - The **g\_reader** thread cyclically reads the messages reported by the modem. When the modem receives an incoming call event, it actively reports the information about the incoming call. + The **g\_reader** thread cyclically reads the messages reported by the modem. When the modem receives an incoming call event, it actively reports the information about the incoming call. - The **g\_reader** thread calls **OnNotifyOps\(\)** to parse the reported information. If the parsed data reported by the modem starts with characters such as **+CRING** or **RING**, it indicates that an incoming call event exists. In this case, the event is reported to RIL Adapter through **OnCallReport\(reportInfo, NULL, 0\)**. + The **g\_reader** thread calls **OnNotifyOps\(\)** to parse the reported information. If the parsed data reported by the modem starts with characters such as **+CRING** or **RING**, it indicates that an incoming call event exists. In this case, the event is reported to RIL Adapter through **OnCallReport\(reportInfo, NULL, 0\)**. ``` // Parse the data reported by the modem as events proactively reported by the corresponding module. @@ -492,11 +492,11 @@ The following table describes the API for reporting modem events. ``` -## Integrating Modem Vendor Libraries +## Integrating Modem Vendor Libraries -### Configuring Compilation Information +### Configuring Compilation Information -Compile the modem vendor library into a dynamic library by using **BUILD.gn**. Upon startup, RIL Adapter loads the dynamic library to the system in dlopen mode and then initializes the library. For details about how to implement vendor library initialization, see [Initializing a Modem Vendor Library](#section211mcpsimp). The following is an example of **BUILD.gn**: +Compile the modem vendor library into a dynamic library by using **BUILD.gn**. Upon startup, RIL Adapter loads the dynamic library to the system in dlopen mode and then initializes the library. For details about how to implement vendor library initialization, see [Initializing a Modem Vendor Library](#initializing-a-modem-vendor-library). The following is an example of **BUILD.gn**: ``` import("//build/ohos.gni") @@ -523,7 +523,7 @@ ohos_shared_library("ril_vendor") { // Modem vendor library } ``` -### Debugging and Verification +### Debugging and Verification 1. Compile the code. 2. Check whether **libril\_vendor.z.so** exists in the **/out/{device_name}/telephony/ril\_adapter** directory. If yes, the integration is successful. Otherwise, correct the error and perform debugging and verification again. diff --git a/en/device-dev/website.md b/en/device-dev/website.md index de8c53fb7d2a4714f6a2d1c3a1077013330eca24..6cfcbb65bcd6cf29218f11a58f8f67667d061f9c 100644 --- a/en/device-dev/website.md +++ b/en/device-dev/website.md @@ -395,6 +395,7 @@ - [Doubly Linked List](kernel/kernel-small-apx-dll.md) - [Bitwise Operation](kernel/kernel-small-apx-bitwise.md) - [Standard Library](kernel/kernel-small-apx-library.md) + - [Kernel Coding Specification](kernel/kernel-mini-appx-code.md) - Kernel for Standard Systems - [Linux Kernel Overview](kernel/kernel-standard-overview.md) - [Applying Patches on OpenHarmony Development Boards](kernel/kernel-standard-patch.md) @@ -450,6 +451,7 @@ - Peripheral Driver Usage - [Audio](driver/driver-peripherals-audio-des.md) - [Camera](driver/driver-peripherals-camera-des.md) + - [Codec](driver/driver-peripherals-codec-des.md) - [Facial Authentication](driver/driver-peripherals-face_auth-des.md) - [Fingerprint Authentication](driver/driver-peripherals-fingerprint_auth-des.md) - [LCD](driver/driver-peripherals-lcd-des.md) @@ -502,21 +504,7 @@ - [Utils Overview](subsystems/subsys-utils-overview.md) - [Utils Development](subsystems/subsys-utils-guide.md) - [Utils FAQ](subsystems/subsys-utils-faqs.md) - - AI Framework - - [AI Engine Framework](subsystems/subsys-aiframework-guide.md) - - [Development Environment](subsystems/subsys-aiframework-envbuild.md) - - Technical Specifications - - [Code Management](subsystems/subsys-aiframework-tech-codemanage.md) - - [Naming](subsystems/subsys-aiframework-tech-name.md) - - [API Development](subsystems/subsys-aiframework-tech-interface.md) - - Development Guidelines - - [SDK](subsystems/subsys-aiframework-devguide-sdk.md) - - [Plug-in](subsystems/subsys-aiframework-devguide-plugin.md) - - [Configuration File](subsystems/subsys-aiframework-devguide-conf.md) - - Development Examples - - [KWS SDK](subsystems/subsys-aiframework-demo-sdk.md) - - [KWS Plug-in](subsystems/subsys-aiframework-demo-plugin.md) - - [KWS Configuration File](subsystems/subsys-aiframework-demo-conf.md) + - [AI Framework Development](subsystems/subsys-ai-aiframework-devguide.md) - Data Management - RDB - [RDB Overview](subsystems/subsys-data-relational-database-overview.md) @@ -547,7 +535,7 @@ - [Development on Application Permission Management](subsystems/subsys-security-rightmanagement.md) - [Development on IPC Authentication](subsystems/subsys-security-communicationverify.md) - [Development on Device Security Level Management](subsystems/subsys-security-devicesecuritylevel.md) - + - [Development on HUKS](subsystems/subsys-security-huks-guide.md) - Startup - [Startup](subsystems/subsys-boot-overview.md) - init Module @@ -561,11 +549,11 @@ - [bootstrap Module](subsystems/subsys-boot-bootstrap.md) - [FAQs](subsystems/subsys-boot-faqs.md) - [Reference](subsystems/subsys-boot-ref.md) - - DFX +- DFX - [DFX](subsystems/subsys-dfx-overview.md) - [HiLog Development](subsystems/subsys-dfx-hilog-rich.md) - [HiLog\_Lite Development](subsystems/subsys-dfx-hilog-lite.md) - - [HiTrace Development](subsystems/subsys-dfx-hitrace.md) + - [HiTraceChain Development](subsystems/subsys-dfx-hitracechain.md) - [HiCollie Development](subsystems/subsys-dfx-hicollie.md) - HiSysEvent Development - [HiSysEvent Logging Configuration](subsystems/subsys-dfx-hisysevent-logging-config.md) @@ -577,7 +565,7 @@ - [HiChecker Development](subsystems/subsys-dfx-hichecker.md) - [FaultLogger Development](subsystems/subsys-dfx-faultlogger.md) - [Hiview Development](subsystems/subsys-dfx-hiview.md) - + - Featured Topics - HPM Part - [HPM Part Overview](hpm-part/hpm-part-about.md) @@ -592,13 +580,6 @@ - WLAN-connected Products - [LED Peripheral Control](guide/device-wlan-led-control.md) - [Third-Party SDK Integration](guide/device-wlan-sdk.md) - - Cameras Without a Screen - - Camera Control - - [Overview](guide/device-iotcamera-control-overview.md) - - Development Guidelines - - [Photographing](guide/device-iotcamera-control-demo-photodevguide.md) - - [Video Recording](guide/device-iotcamera-control-demo-videodevguide.md) - - [Use Case](guide/device-iotcamera-control-example.md) - Cameras with a Screen - Screen and Camera Control - [Overview](guide/device-camera-control-overview.md) @@ -643,11 +624,7 @@ - [Kernel](faqs/faqs-kernel.md) - [Porting](faqs/faqs-porting.md) - [Startup](faqs/faqs-startup.md) - - [System Applications](faqs/faqs-system-applications.md) - - - - + - [System Applications](faqs/faqs-system-applications.md) diff --git a/en/readme/startup.md b/en/readme/startup.md index 4d1d1780815533373ea44576ea746c119625d80d..5f12643fffc97c3a896d8fe918dde75a4e9c91a6 100644 --- a/en/readme/startup.md +++ b/en/readme/startup.md @@ -1,6 +1,6 @@ -# Startup +# Startup -## Introduction +## Introduction The startup subsystem is responsible for starting key system processes and services after the kernel is started and before applications are started. The subsystem consists of the following modules: @@ -8,7 +8,7 @@ The startup subsystem is responsible for starting key system processes and servi This module can be used on platforms powered by LiteOS Cortex-A or Linux kernel. - The module starts system service processes from the time the kernel loads the first user-space process to the time the first application is started. In addition to loading key system processes, it needs to configure their permissions during the startup and keep the specified process alive after sub-processes are started. If a key process exits abnormally, the module needs to perform a system restart. For details, see [init Module](../device-dev/subsystems/subsys-boot-init.md). + The module starts system service processes from the time the kernel loads the first user-space process to the time the first application is started. In addition to loading key system processes, it needs to configure their permissions during the startup and keep the specified process alive after sub-processes are started. If a key process exits abnormally, the module needs to perform a system restart. For details, see [init Module](../device-dev/subsystems/subsys-boot-init-cfg.md). - appspawn @@ -27,58 +27,22 @@ The startup subsystem is responsible for starting key system processes and servi This module obtains and sets system attributes. - The module can be used on all platforms. Supported system attributes consist of default, OEM-specified, and custom system attributes. OEM-specified system attributes provide only default values. The specific values need to be adjusted as required. For details, see [syspara Module](../device-dev/subsystems/subsys-boot-syspara.md). + The module can be used on all platforms. Supported system attributes consist of default, OEM-specified, and custom system attributes. OEM-specified system attributes provide only default values. The specific values need to be adjusted as required. For details, see [syspara Module](../device-dev/subsystems/subsys-boot-init-sysparam.md). -## Directory Structure +## Directory Structure **Table 1** Directory structure of the source code for the startup subsystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Directory

-

Description

-

Applicable Platform

-

base/startup/appspawn_lite

-

appspawn module of the Lite edition for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them.

-
Platforms using the LiteOS Cortex-A kernel -

base/startup/appspawn_standard

-

appspawn module of the Standard version for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them.

-
Platforms using the Linux kernel -

base/startup/bootstrap_lite

-

bootstrap module for starting all services except core system services.

-
Platforms using the LiteOS Cortex-M kernel -

base/startup/init_lite

-

init_lite module for implementing the init process, which is the first user-space process loaded after the kernel is initialized. Upon startup, the process parses the configuration file in **/etc/init.cfg**. Based on the parsing result, the process then starts other key system processes and grants required permissions to them.

-
Platforms using the LiteOS Cortex-A or Linux kernel

base/startup/syspara_lite

-

syspara module that provides APIs to obtain device information, including the product name, brand name, category name, and manufacturer name.

-
All platforms
+| Directory | Description | Applicable Platform | +| ------------------------------ | ------------------------------------------------------------ | --------------------------------------------------- | +| base/startup/appspawn_lite | appspawn module of the Lite edition for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them. | Platforms using the LiteOS Cortex-A kernel | +| base/startup/appspawn_standard | appspawn module of the Standard version for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them. | Platforms using the Linux kernel | +| base/startup/bootstrap_lite | bootstrap module for starting all services except core system services. | Platforms using the LiteOS Cortex-M kernel | +| base/startup/init_lite | init_lite module for implementing the init process, which is the first user-space process loaded after the kernel is initialized. Upon startup, the process parses the configuration file in **/etc/init.cfg**. Based on the parsing result, the process then starts other key system processes and grants required permissions to them. | Platforms using the LiteOS Cortex-A or Linux kernel | +| base/startup/syspara_lite | syspara module that provides APIs to obtain device information, including the product name, brand name, category name, and manufacturer name. | All platforms | + + ``` @@ -111,7 +75,7 @@ base/startup/ └── simulator # Simulator adaptation ``` -## Repositories Involved +## Repositories Involved [Startup subsystem](../device-dev/subsystems/subsys-boot-overview.md) @@ -123,4 +87,4 @@ base/startup/ [startup_init_lite](https://gitee.com/openharmony/startup_init_lite) -[startup\_syspara\_lite](https://gitee.com/openharmony/startup_syspara_lite) +[startup\_syspara\_lite](https://gitee.com/openharmony/startup_syspara_lite) \ No newline at end of file