• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2021 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 {
17  getValue,
18  Log
19} from '../../../utils/index';
20
21interface dpiConstructor {
22  new(options: object): Dpi;
23}
24
25export interface DPIInterface {
26  instance?: { dpi: dpiConstructor };
27}
28
29interface VMInterface {
30  $r: Function;
31  _dpi: Function;
32}
33
34const instances = {};
35
36/**
37 * This class provides multi-resolution display support.
38 */
39class Dpi {
40  public image: object;
41
42  constructor(options) {
43    this.image = options.images;
44  }
45
46  /**
47   * Check the value of the key in images.
48   * @param {string} path - Source path.
49   * @return {Object | string} The value of the key if found.
50   */
51  public $r(path: string): object | string {
52    if (typeof path !== 'string') {
53      Log.warn(`Invalid parameter type: The type of 'path' should be string, not ${typeof path}.`);
54      return;
55    }
56    const images = this.image;
57    let res;
58    for (const index in images) {
59      res = getValue(path, images[index]);
60      if (res) {
61        return res;
62      }
63    }
64    return path;
65  }
66
67  /**
68  * Extend _dpi to Vm.
69  * @param {VMInterface} Vm - The Vm.
70  */
71  public extend(Vm: VMInterface): void {
72    Object.defineProperty(Vm, '_dpi', {
73      configurable: true,
74      enumerable: true,
75      get: function proxyGetter() {
76        return this.dpi ? this.dpi : global.aceapp.dpi;
77      }
78    });
79    Vm.$r = function(key: string): string {
80      const dpi = this._dpi;
81      return dpi.$r(key);
82    };
83  }
84}
85
86/**
87 * Init the dpi object.
88 */
89export default {
90  create: (id: number): DPIInterface => {
91    instances[id] = [];
92    if (typeof global.dpi === 'function') {
93      return {};
94    }
95    const dpiObject = {
96      dpi: class extends Dpi {
97        constructor(options) {
98          super(options);
99          instances[id].push(this);
100        }
101      }
102    };
103    return {
104      instance: dpiObject
105    };
106  },
107  destroy: (id: number): void => {
108    delete instances[id];
109  }
110};
111