1/*
2 * Copyright (c) 2022 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 extension from '@ohos.app.ability.ServiceExtensionAbility';
17import window from '@ohos.window';
18import display from '@ohos.display';
19import rpc from '@ohos.rpc';
20import { GlobalContext } from '../common/utils/globalContext';
21import dialogRequest from '@ohos.app.ability.dialogRequest';
22
23const TAG = 'PermissionManager_Log: ';
24const BG_COLOR = '#00000000';
25const DEFAULT_CORNER_RADIUS_L = 16;
26const RESULT_CODE_1 = 1;
27const ACCESS_TOKEN = 'ohos.security.accesstoken.tokencallback';
28
29export default class ServiceExtensionAbility extends extension {
30  /**
31  * Lifecycle function, called back when a service extension is started for initialization.
32  */
33  onCreate(want): void {
34    console.info(TAG + 'ServiceExtensionAbility onCreate, ability name is ' + want.abilityName);
35
36    globalThis.windowNum = 0;
37  }
38
39  /**
40  * Lifecycle function, called back when a service extension is started or recall.
41  */
42  onRequest(want, startId): void {
43    console.info(TAG + 'ServiceExtensionAbility onRequest. start id is ' + startId);
44    console.info(TAG + 'want: ' + JSON.stringify(want));
45
46    try {
47      let dis = display.getDefaultDisplaySync();
48      let navigationBarRect = {
49        left: 0,
50        top: 0,
51        width: dis.width,
52        height: dis.height
53      };
54      this.createWindow('permissionDialog' + startId, window.WindowType.TYPE_DIALOG, navigationBarRect, want);
55    } catch (exception) {
56      console.error(TAG + 'Failed to obtain the default display object. Code: ' + JSON.stringify(exception));
57    };
58  }
59
60  /**
61  * Lifecycle function, called back before a service extension is destroyed.
62  */
63  onDestroy(): void {
64    console.info(TAG + 'ServiceExtensionAbility onDestroy.');
65  }
66
67  private async createWindow(name: string, windowType, rect, want): Promise<void> {
68    let requestInfo: dialogRequest.RequestInfo;
69    try {
70      requestInfo = dialogRequest.getRequestInfo(want);
71    } catch (err) {
72      console.error(`getRequestInfo err= ${JSON.stringify(err)}`);
73    }
74
75    console.info(TAG + 'create window start, requestInfo: ' + JSON.stringify(requestInfo));
76    let rectInfo = requestInfo ? requestInfo.windowRect : rect;
77    rectInfo = rectInfo.width === 0 ? rect : rectInfo;
78    try {
79      const win = await window.createWindow({ ctx: this.context, name, windowType });
80      console.info(TAG + 'createWindow end.');
81      let storage: LocalStorage = new LocalStorage({ 'want': want, 'win': win });
82      await this.BindDialogTarget(win, want);
83      console.info(TAG + 'bindDialogTarget end.');
84      await win.moveWindowTo(rectInfo.left, rectInfo.top);
85      console.info(TAG + 'moveWindowTo end.');
86      await win.resize(rectInfo.width, rectInfo.height);
87      console.info(TAG + 'resize end.');
88      await win.loadContent('pages/dialogPlus', storage);
89      win.setWindowBackgroundColor(BG_COLOR);
90      if (rectInfo.width < rect.width) {
91        win.setCornerRadius(DEFAULT_CORNER_RADIUS_L);
92      }
93      await win.showWindow();
94      console.info(TAG + 'showWindow end.');
95      globalThis.windowNum ++;
96      GlobalContext.store('windowNum', globalThis.windowNum);
97    } catch (err) {
98      console.error(TAG + `window create failed! err: ${JSON.stringify(err)}`);
99    }
100  }
101
102  private async BindDialogTarget(win, want): Promise<void> {
103    let proxy = want.parameters['ohos.ability.params.callback'].value;
104    win.bindDialogTarget(want.parameters['ohos.ability.params.token'].value, () => {
105      let option = new rpc.MessageOption();
106      let data = new rpc.MessageSequence();
107      let reply = new rpc.MessageSequence();
108      try {
109        data.writeInterfaceToken(ACCESS_TOKEN);
110        proxy.sendMessageRequest(RESULT_CODE_1, data, reply, option);
111      } catch (err) {
112        console.error(TAG + `write result failed: ${JSON.stringify(err)}`);
113      } finally {
114        data.reclaim();
115        reply.reclaim();
116      }
117      let windowNum = GlobalContext.load('windowNum');
118      windowNum --;
119      GlobalContext.store('windowNum', windowNum);
120      win.destroyWindow();
121      if (windowNum === 0) {
122        this.context.terminateSelf();
123      }
124    });
125  }
126};