• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 */
15import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
16import window from '@ohos.window';
17import display from '@ohos.display';
18import inputMethod from '@ohos.inputMethod';
19import prompt from '@ohos.prompt';
20import commonEvent from '@ohos.commonEvent';
21
22let TAG = '[InputMethodChooseDialog]';
23let commonEvent1 = 'usual.event.PACKAGE_ADDED';
24let commonEvent2 = 'usual.event.PACKAGE_REMOVED';
25let subscribeInfo = {
26  events: [commonEvent1, commonEvent2]
27};
28const EXIT_TIME = 1000;
29export default class ServiceExtAbility extends ServiceExtensionAbility {
30  onCreate(want): void {
31    console.log(TAG, 'onCreate');
32    globalThis.windowNum = 0;
33  }
34
35  onRequest(want, startId): void {
36    console.log(TAG, 'onRequest execute');
37    globalThis.abilityWant = want;
38    display.getDefaultDisplay().then(() => {
39      let dialogRect = {
40        left: 50,
41        top: 900,
42        width: 300,
43        height: 300,
44      };
45      let windowConfig = {
46        name:'inputmethod Dialog',
47        windowType:window.WindowType.TYPE_FLOAT,
48        ctx:this.context
49      };
50      this.getInputMethods().then(() => {
51        this.createWindow(windowConfig, dialogRect);
52      });
53    }).catch((err) => {
54      console.log(TAG + 'getDefaultDisplay err:' + JSON.stringify(err));
55    });
56
57    commonEvent.createSubscriber(subscribeInfo, (error, subcriber) => {
58      commonEvent.subscribe(subcriber, (error, commonEventData) => {
59        if (commonEventData.event === commonEvent1 || commonEventData.event === commonEvent2) {
60          console.log(TAG + 'commonEvent:' + JSON.stringify(commonEvent1));
61          this.updateImeList();
62        }
63      });
64    });
65
66    globalThis.chooseInputMethods = ((prop: inputMethod.InputMethodProperty): void => {
67      inputMethod.switchInputMethod(prop).then((err) => {
68        if (!err) {
69          console.log(TAG + 'switchInputMethod failed,' + JSON.stringify(err));
70          prompt.showToast({
71            message: 'switch failed', duration: 200
72          });
73        } else {
74          console.log(TAG + 'switchInputMethod success');
75          prompt.showToast({
76            message: 'switch success', duration: 200
77          });
78        }
79        setTimeout(() => {
80          this.releaseContext();
81        }, EXIT_TIME);
82      });
83    });
84  }
85
86  onDestroy(): void {
87    console.log(TAG + 'ServiceExtAbility destroyed');
88    this.releaseContext();
89  }
90
91  private async createWindow(config: window.Configuration, rect): Promise<void> {
92    console.log(TAG + 'createWindow execute');
93    try {
94      if (globalThis.windowNum > 0) {
95        this.updateImeList();
96        return;
97      }
98      try {
99        await window.createWindow(config, async (err, data) => {
100          if (err.code) {
101            console.error('Failed to create the window. Cause: ' + JSON.stringify(err));
102            return;
103          }
104          const win = data;
105          globalThis.extensionWin = win;
106          console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data));
107          win.on('windowEvent', async (data) => {
108            console.log(TAG + 'windowEvent:' + JSON.stringify(data));
109            if (data === window.WindowEventType.WINDOW_INACTIVE) {
110              await this.releaseContext();
111            }
112          });
113          await win.moveTo(rect.left, rect.top);
114          await win.resetSize(rect.width, rect.height);
115          await win.loadContent('pages/index');
116          await win.show();
117          globalThis.windowNum++;
118          console.log(TAG + 'window create successfully');
119        });
120      } catch (exception) {
121        console.error('Failed to create the window. Cause: ' + JSON.stringify(exception));
122      }
123      globalThis.context = this.context;
124    } catch {
125      console.info(TAG + 'window create failed');
126    }
127  }
128
129  private async getInputMethods(): Promise<void> {
130    globalThis.inputMethodList = [];
131    try {
132      let enableList = await inputMethod.getSetting().getInputMethods(true);
133      let disableList = await inputMethod.getSetting().getInputMethods(false);
134      globalThis.inputMethodList = [...enableList, ...disableList];
135    } catch {
136      console.log(TAG + 'getInputMethods failed');
137    }
138  }
139
140  private async updateImeList(): Promise<void> {
141    await this.getInputMethods().then(async () => {
142      await globalThis.extensionWin.loadContent('pages/index');
143      if (!globalThis.extensionWin.isWindowShowing()) {
144        await globalThis.extensionWin.show();
145      }
146    });
147  }
148
149  private async releaseContext(): Promise<void> {
150    if (globalThis.context !== null) {
151      await globalThis.extensionWin.destroy();
152      await globalThis.context.terminateSelf();
153      globalThis.context = null;
154    }
155  }
156};
157