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