• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import bundleResourceManager from '@ohos.bundle.bundleResourceManager';
17import display from '@ohos.display';
18import window from '@ohos.window';
19import {
20  titleTrim,
21  calContainerWidth,
22  getFontSizeScale,
23  sourceToVp,
24  getLimitFontSize } from '../common/utils';
25import Constants from '../common/constant';
26import fs from '@ohos.file.fs';
27import configPolicy from '@ohos.configPolicy';
28import { EnableNotificationDialog } from '../ServiceExtAbility/NotificationServiceExtAbility';
29import { Callback} from '@ohos.base';
30import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession';
31import i18n from '@ohos.i18n';
32import { MeasureOptions } from '@ohos.measure';
33import { MeasureUtils } from '@ohos.arkui.UIContext';
34import common from '@ohos.app.ability.common';
35
36const TAG = 'NotificationDialog_Service ';
37
38const LAN_EN = 'These may include banners, sounds and more. You can change this in Settings.';
39const LAN_CN = '通知提醒方式可能包括横幅、响铃等。可前往“设置” 更改。';
40const LAN_HK = '通知提醒方式可能包括橫幅、響鬧等。可前往「設定」更改。';
41const LAN_TW = '通知提醒方式可能包括橫幅、響鈴等。可前往「設定」變更。';
42const LAN_BO = 'བརྡ་ཐོ་དྲན་སྐུལ་གྱི་ཐབས་ལམ་ལ་སྒོ་ལྕགས་བརྙན་ཡོལ་དང་། འཕྲེད་བྱང་། དྲིལ་སྒྲ། སྦིར་བརྡ་སོགས་ཚུད་སྲིད། ༼སྒྲིག་འགོད་༽ལ་བསྐྱོད་ནས་བཅོས་ཆོག';
43const LAN_UG = 'قۇلۇپ ئېكرانى، بالداق، ئاۋاز ۋە تىترەش شۇلارنىڭ ئىچىدە. تەڭشەكتىن ئۆزگەرتەلەيسىز.';
44
45const permission: Record<string, Resource> = {
46  'label': $r('app.string.group_label_notification'),
47  'icon': $r('app.media.ic_public_ring'),
48  'reason': $r('app.string.reason'),
49};
50
51let storage = LocalStorage.getShared();
52
53@Extend(Button) function customizeButton() {
54  .type(ButtonType.Normal)
55  .backgroundColor($r('sys.color.comp_background_tertiary'))
56  .fontColor($r('sys.color.font_emphasize'))
57  .fontSize(
58    getLimitFontSize(
59      sourceToVp($r('sys.float.Body_L')),
60      getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX))
61  )
62  .fontWeight(FontWeight.Medium)
63  .height(Constants.PC_BUTTON_HEIGHT)
64  .width('50%')
65  .borderRadius(Constants.PC_RDIUS_8)
66  .flexGrow(Constants.FLEX_GROW)
67}
68
69@Entry(storage)
70@Component
71struct NotificationDialogPage {
72  @StorageLink('isUpdate') isUpdate: number = 0;
73
74  privacyDialogController: CustomDialogController = new CustomDialogController({
75    builder: PermissionDialog({ isUpdate: $isUpdate }),
76    autoCancel: false,
77    alignment: DialogAlignment.Center,
78    customStyle: true,
79    cornerRadius: Constants.PC_RDIUS_16,
80    maskColor: $r('sys.color.ohos_id_color_mask_thin'),
81    onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
82      console.info(TAG, `dialog onWillDismiss reason= : ${JSON.stringify(dismissDialogAction.reason)}`);
83    }
84  });
85
86  build() {}
87
88  aboutToAppear() {
89    this.privacyDialogController.open();
90  }
91
92  onPageShow() {
93  }
94}
95
96@CustomDialog
97struct PermissionDialog {
98  @State appName: string = '';
99  @State content: string = LAN_CN;
100  @State naviHeight: number = 0;
101  @State isBottomPopover: boolean = false;
102  @StorageLink('clicked') clicked: boolean = false;
103  @Link @Watch('updateOnPageShow') isUpdate: number;
104  dialog?: EnableNotificationDialog;
105  session?: UIExtensionContentSession;
106  controller?: CustomDialogController;
107  @State titleContainerWidth: string | number = 'auto';
108
109  build() {
110    Row() {
111      Flex({ justifyContent: FlexAlign.Center, alignItems: this.isBottomPopover ? ItemAlign.End : ItemAlign.Center }) {
112        Column() {
113          Scroll() {
114            Column() {
115              Row() {
116                Image(permission.icon)
117                .width(Constants.DIALOG_ICON_WIDTH)
118                .height(Constants.DIALOG_ICON_HEIGHT)
119                .margin({
120                  top: Constants.PC_ICON_MARGIN_TOP
121                })
122                .draggable(false)
123              }
124              Row() {
125                Flex({ justifyContent: FlexAlign.Center }) {
126                  Text($r('app.string.group_label_notification', this.appName))
127                  .fontSize($r('sys.float.Title_S'))
128                  .fontColor($r('sys.color.font_primary'))
129                  .fontWeight(FontWeight.Bold)
130                  .minFontSize(
131                    getLimitFontSize(Constants.TITLE_MIN_FONT_SIZE,
132                      getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX))
133                  )
134                  .maxFontSize(
135                    getLimitFontSize(sourceToVp($r('sys.float.Title_S')),
136                      getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX))
137                  )
138                  .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
139                  .maxLines(2)
140                  .textOverflow({overflow: TextOverflow.Ellipsis})
141                  .width(this.titleContainerWidth)
142                  .textAlign(TextAlign.Center)
143                }
144                .margin({
145                  left: Constants.PC_TITLE_MARGIN_SIDE,
146                  right: Constants.PC_TITLE_MARGIN_SIDE,
147                  top: Constants.PC_TITLE_MARGIN_TOP,
148                })
149                .onSizeChange((oldValue: SizeOptions, newValue: SizeOptions) => {
150                    let containerWidth = newValue.width as number;
151                    let options: MeasureOptions = {
152                      textContent: $r('app.string.group_label_notification', this.appName),
153                      fontSize: getLimitFontSize(sourceToVp($r('sys.float.Title_S')),
154                      getFontSizeScale(getContext(this) as common.UIAbilityContext, Constants.FONT_SCALE_MAX)),
155                      fontWeight: FontWeight.Bold,
156                    };
157                    this.titleContainerWidth = calContainerWidth(containerWidth, options,
158                      Constants.CROSS_LINE_RATIO, this.getUIContext().getMeasureUtils());
159                    console.info(TAG, `onSizeChange titleContainerWidth: ${this.titleContainerWidth}`);
160                  })
161              }
162              Row() {
163                Flex({ justifyContent: FlexAlign.Center }) {
164                  Text() {
165                    Span(this.content)
166                  }
167                  .fontSize(
168                    getLimitFontSize(sourceToVp($r('sys.float.Body_L')),
169                      getFontSizeScale(getContext(this) as common.UIAbilityContext))
170                  )
171                  .fontWeight(FontWeight.Medium)
172                  .fontColor($r('sys.color.font_primary'))
173                }
174                .margin({
175                  left: Constants.PC_CONTENT_MARGIN_SIDE,
176                  right: Constants.PC_CONTENT_MARGIN_SIDE,
177                  top: Constants.PC_CONTENT_MARGIN_TOP
178                })
179              }
180              Row() {
181                Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
182                  Button($r('app.string.BAN'))
183                    .onClick(async (): Promise<void> => {
184                    await this.enableNotification(false);
185                    })
186                    .customizeButton()
187                    .margin({right: Constants.BUTTON_RIGHT})
188                  Button($r('app.string.ALLOW'))
189                    .onClick(async (): Promise<void> => {
190                      await this.enableNotification(true);
191                    })
192                    .customizeButton()
193                    .margin({left: Constants.BUTTON_LEFT})
194                }
195                .margin({
196                  left: Constants.PC_OPERATE_MARGIN_SIDE,
197                  right: Constants.PC_OPERATE_MARGIN_SIDE,
198                  top: Constants.PC_OPERATE_MARGIN_TOP,
199                  bottom: Constants.PC_OPERATE_MARGIN_BUTTOM
200                })
201              }
202            }
203          }
204          .constraintSize({ maxHeight: '90%' })
205        }
206        .borderRadius(Constants.PC_RDIUS_16)
207        .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK)
208        .width(Constants.PC_DIALOG_WIDTH)
209        .outline({
210            width: 1,
211            color: Constants.PC_OUTLINE_COLOR,
212            radius: Constants.PC_RDIUS_16
213          })
214        .clip(true)
215      }
216      .width(Constants.FULL_WIDTH)
217      .height(Constants.FULL_HEIGHT)
218    }
219  }
220
221  async aboutToAppear(): Promise<void> {
222    this.dialog = storage.get('dialog') as EnableNotificationDialog;
223    this.session = storage.get('session') as UIExtensionContentSession;
224    this.updateAvoidWindow();
225    this.updateSubWindowSize();
226    try {
227      await this.updateStatus();
228    } catch (err) {
229      console.error(TAG, `aboutToAppear error : ${err?.code}`);
230      await this.dialog?.destroyException();
231      await this.session?.terminateSelf();
232    }
233  }
234
235  async aboutToDisappear(): Promise<void> {
236    console.info(TAG, `aboutToDisappear`);
237    this.session?.terminateSelf();
238  }
239
240  async updateOnPageShow(): Promise<void> {
241    if (this.isUpdate > 0) {
242      await this.updateStatus();
243    }
244  }
245
246  async updateStatus(): Promise<void> {
247    let bundleNameObj = this.dialog?.want.parameters?.bundleName;
248    let bundleName = bundleNameObj ? bundleNameObj.toString() : '';
249    await this.updateApplicationName(bundleName);
250  }
251
252  async updateApplicationName(bundleName: string): Promise<void> {
253    console.info(TAG, `updateApplicationName bundleName: ${bundleName}`);
254    try {
255      let bundleFlags = bundleResourceManager.ResourceFlag.GET_RESOURCE_INFO_ALL;
256      let resourceInfo = bundleResourceManager.getBundleResourceInfo(bundleName, bundleFlags);
257      console.info(TAG, `applicationName name : ${JSON.stringify(resourceInfo.label)}`);
258      let appName = resourceInfo.label;
259      this.appName = titleTrim(appName);
260      console.info(TAG, `hap label: ${this.appName}`);
261
262      let systemLanguage: string = i18n.System.getSystemLanguage();
263      console.info(TAG, `language: ${systemLanguage}`);
264      if (systemLanguage.indexOf('zh-Hans') != -1) {
265        this.content = LAN_CN;
266      } else if (systemLanguage.indexOf('zh-Hant') != -1) {
267        this.content = LAN_TW;
268      } else if (systemLanguage.indexOf('en') != -1) {
269        this.content = LAN_EN;
270      } else if (systemLanguage.indexOf('ug') != -1) {
271        this.content = LAN_UG;
272      } else if (systemLanguage.indexOf('bo') != -1) {
273        this.content = LAN_BO;
274      }
275
276    } catch (err) {
277      console.error(TAG, `applicationName error : ${err?.code}`);
278    }
279  }
280
281  updateAvoidWindow(): void {
282    let type = window.AvoidAreaType.TYPE_SYSTEM;
283    try {
284      this.dialog?.extensionWindow.on('avoidAreaChange', (data): void => {
285        if (data.type == window.AvoidAreaType.TYPE_SYSTEM) {
286          console.info(TAG, `avoidAreaChange: ${JSON.stringify(data)}`);
287          this.naviHeight = data.area.bottomRect.height;
288        }
289      });
290      let avoidArea = this.dialog?.extensionWindow.getWindowAvoidArea(type);
291      if (avoidArea != undefined) {
292        console.info(TAG, `avoidArea: ${JSON.stringify(avoidArea)}`);
293        this.naviHeight = avoidArea.bottomRect.height;
294      }
295    } catch (err) {
296      console.error(TAG, `Failed to obtain the area. Cause: ${err?.code}`);
297    }
298  }
299
300  updateSubWindowSize(): void {
301    try {
302      this.dialog?.extensionWindow.on('windowSizeChange', (data):void => {
303        let windowRect = this.dialog?.extensionWindow.properties?.uiExtensionHostWindowProxyRect;
304        console.info(TAG, `windowSizeChange event, size = ${windowRect?.left}-${windowRect?.top}-${windowRect?.width}-${windowRect?.height}`);
305        this.dialog?.subWindow?.moveWindowTo(windowRect?.left, windowRect?.top);
306        this.dialog?.subWindow?.resize(windowRect?.width, windowRect?.height);
307      });
308    } catch (err) {
309      console.error(TAG, `updateSubWindowSize error. Cause: ${err?.code}`);
310    }
311  }
312
313  async enableNotification(enabled: boolean): Promise<void> {
314    console.info(TAG, `NotificationDialog enableNotification: ${enabled}`);
315    try {
316      await this.dialog?.publishButtonClickedEvent(enabled);
317      this.clicked = true;
318    } catch (err) {
319      console.error(TAG, `NotificationDialog enable error, code is ${err?.code}`);
320      await this.dialog?.destroyException();
321    } finally {
322      await this.dialog?.subWindow?.destroyWindow();
323      this.session?.terminateSelf();
324    }
325  }
326}