• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * Copyright (c) 2021-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 { Log } from '../utils/Log';
17import { CheckEmptyUtils } from '../utils/CheckEmptyUtils';
18import AppResourceCacheManager from '../cache/AppResourceCacheManager';
19
20const KEY_ICON = 'icon';
21const KEY_NAME = 'name';
22const TAG = 'ResourceManager';
23
24/**
25 * Wrapper class for resourceManager interfaces.
26 */
27export class ResourceManager {
28  private constructor() {
29  }
30
31  static getInstance(): ResourceManager {
32    if (globalThis.ResourceManager == null) {
33      globalThis.ResourceManager = new ResourceManager();
34    }
35    return globalThis.ResourceManager;
36  }
37
38  private getAppResourceCacheManager(): AppResourceCacheManager {
39    if (globalThis.AppResourceCacheManager == null) {
40      globalThis.AppResourceCacheManager = new AppResourceCacheManager();
41    }
42    return globalThis.AppResourceCacheManager;
43  }
44
45  getCachedAppIcon(iconId, bundleName: string, moduleName: string) {
46    const cacheKey = `${iconId}${bundleName}${moduleName}`;
47    return this.getAppResourceCacheManager().getCache(cacheKey, KEY_ICON);
48  }
49
50  setAppResourceCache(cacheKey: string, cacheType: string, value: object | string): void {
51    this.getAppResourceCacheManager().setCache(cacheKey, cacheType, value);
52  }
53
54  deleteAppResourceCache(cacheKey: string, cacheType: string): void {
55    this.getAppResourceCacheManager().deleteCache(cacheKey, cacheType);
56  }
57
58  async updateIconCache(iconId, bundleName: string, moduleName: string): Promise<void> {
59    try {
60      let cacheKey = `${iconId}${bundleName}${moduleName}`;
61      const iconBase64 = this.getAppResourceCache(cacheKey, KEY_ICON);
62      if (!CheckEmptyUtils.isEmpty(iconBase64)) {
63        return;
64      }
65      Log.showDebug(TAG, `updateIconCache bundleName:${bundleName}, moduleName:${moduleName}, iconId: ${iconId}`);
66      let moduleContext = globalThis.desktopContext.createModuleContext(bundleName, moduleName);
67      if (moduleContext == null) {
68        return;
69      }
70      await moduleContext.resourceManager
71        .getMediaBase64(iconId)
72        .then((value)=> {
73          if (value != null) {
74            this.setAppResourceCache(cacheKey, KEY_ICON, value);
75          }
76        })
77        .finally(() => {
78          moduleContext = null;
79        });
80    } catch (error) {
81      Log.showError(TAG, `updateIconCache error ${error}`);
82    }
83  }
84
85  getAppIconWithCache(iconId, bundleName: string, moduleName: string, callback, defaultAppIcon) {
86    if (CheckEmptyUtils.isEmpty(iconId) || iconId <= 0) {
87      Log.showDebug(TAG, 'getAppIconWithCache defaultAppIcon');
88      callback(defaultAppIcon);
89    } else {
90      const cacheKey = `${iconId}${bundleName}${moduleName}`;
91      const iconBase64 = this.getAppResourceCache(cacheKey, KEY_ICON);
92      if (CheckEmptyUtils.isEmpty(iconBase64)) {
93        if (this.isResourceManagerEmpty()) {
94          Log.showError(TAG, 'getAppIconWithCache resourceManager is empty');
95          callback(defaultAppIcon);
96          return;
97        }
98        try {
99          Log.showDebug(TAG, `getAppIconWithCache bundleName:${bundleName}, moduleName:${moduleName}, iconId:${iconId}`);
100          let moduleContext = globalThis.desktopContext.createModuleContext(bundleName, moduleName);
101          moduleContext.resourceManager
102            .getMediaBase64(iconId)
103            .then((value: string)=> {
104              if (value != null) {
105                this.setAppResourceCache(cacheKey, KEY_ICON, value);
106                callback(value);
107              }
108              else {
109                callback(defaultAppIcon);
110              }
111            })
112            .finally(() => {
113              moduleContext = null;
114            });
115        } catch (error) {
116          Log.showError(TAG, `getAppIconWithCache error ${error}`);
117          callback(defaultAppIcon);
118        }
119      } else {
120        callback(iconBase64);
121      }
122    }
123  }
124
125  async getAppNameSync(labelId, bundleName: string, moduleName:string, appName: string) {
126    if (CheckEmptyUtils.isEmpty(labelId) || labelId <= 0 || CheckEmptyUtils.checkStrIsEmpty(bundleName)) {
127      Log.showDebug(TAG, `getAppNameSync param empty! appName: ${appName}`);
128      return appName;
129    } else {
130      const cacheKey = `${labelId}${bundleName}${moduleName}`;
131      let resMgrName = null;
132      if (this.isResourceManagerEmpty()) {
133        return appName;
134      }
135      Log.showDebug(TAG, `getAppNameSync bundleName:${bundleName}, moduleName:${moduleName}, iconId:${labelId}`);
136      let moduleContext = globalThis.desktopContext.createModuleContext(bundleName, moduleName);
137      await moduleContext.resourceManager
138        .getString(labelId)
139        .then((res) => {
140          resMgrName = res;
141        })
142        .catch((err) => {
143          Log.showError(TAG, `getAppNameSync getString error: ${JSON.stringify(err)}`);
144        })
145        .finally(() => {
146          moduleContext = null;
147        });
148      if (resMgrName != null) {
149        return resMgrName;
150      } else {
151        return appName;
152      }
153    }
154  }
155
156  getAppNameWithCache(labelId: number, bundleName: string, moduleName: string, appName: string, callback) {
157    if (CheckEmptyUtils.isEmpty(labelId) || labelId <= 0) {
158      Log.showDebug(TAG, `getAppNameWithCache ResourceManager getAppName callback: ${appName}`);
159      callback(appName);
160    } else {
161      const cacheKey = `${labelId}${bundleName}${moduleName}`;
162      const name = this.getAppResourceCache(cacheKey, KEY_NAME);
163      if (CheckEmptyUtils.isEmpty(name)) {
164        if (this.isResourceManagerEmpty()) {
165          return appName;
166        }
167        try {
168          Log.showDebug(TAG, `getAppNameWithCache bundleName:${bundleName}, moduleName:${moduleName}, iconId:${labelId}`);
169          let moduleContext = globalThis.desktopContext.createModuleContext(bundleName, moduleName);
170          moduleContext.resourceManager
171            .getString(labelId)
172            .then((value) => {
173              if (CheckEmptyUtils.checkStrIsEmpty(value)) {
174                Log.showDebug(TAG, `getAppNameWithCache getAppName getString ERROR! value is empty id ${labelId}`);
175                callback(appName);
176              } else {
177                this.setAppResourceCache(cacheKey, KEY_NAME, value);
178                callback(value);
179              }
180            })
181            .finally(() => {
182              moduleContext = null;
183            });
184        } catch (err) {
185          Log.showError(TAG, `getAppNameWithCache error: ${JSON.stringify(err)}`);
186          callback(appName);
187        }
188      } else {
189        callback(name);
190      }
191    }
192  }
193
194  /**
195     * Get app resource cache.
196     *
197     * @param {string} cacheKey
198     * @param {string} cacheType
199     */
200  getAppResourceCache(cacheKey, cacheType) {
201    return this.getAppResourceCacheManager().getCache(cacheKey, cacheType);
202  }
203
204  /**
205   * get string by resource.id.
206   *
207   * @param {number} resource.id
208   * @param {function} callback(value)
209   */
210  getStringById(resId: number, callback: (value: string) => void): void {
211    if (this.isResourceManagerEmpty()) {
212      Log.showDebug(TAG, 'resourceManager is empty');
213      callback('');
214      return;
215    }
216    try {
217      globalThis.desktopContext.resourceManager.getString(resId).then((value) => {
218        callback(value);
219      });
220    } catch (err) {
221      Log.showError(TAG, `getStringById error: ${JSON.stringify(err)}`);
222      callback('');
223    }
224  }
225
226  private isResourceManagerEmpty(): boolean {
227    return CheckEmptyUtils.isEmpty(globalThis.desktopContext)
228    || CheckEmptyUtils.isEmpty(globalThis.desktopContext.resourceManager);
229  }
230
231  async getStringByResource(res: Resource): Promise<string>{
232    const json = JSON.parse(JSON.stringify(res));
233    const id = json.id;
234    return await this.getStringByIdSync(id);
235  }
236
237  /**
238   * get string by resource.id.
239   *
240   * @param {number} resource.id
241   * @return {string} resource name
242   */
243  async getStringByIdSync(resId: number): Promise<string> {
244    let resMgrName = '';
245    if (resId <= 0) {
246      return resMgrName;
247    } else {
248      if (this.isResourceManagerEmpty()) {
249        return resMgrName;
250      }
251      try {
252        resMgrName = await globalThis.desktopContext.resourceManager.getString(resId);
253      } catch (err) {
254        Log.showError(TAG, `getStringByIdSync error: ${JSON.stringify(err)}`);
255      }
256      return resMgrName;
257    }
258  }
259
260  clearAppResourceCache(): void {
261    this.getAppResourceCacheManager().clearCache();
262  }
263}