• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023-2023 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
16// @ts-ignore
17import { print } from '@kit.BasicServicesKit';
18import CheckEmptyUtils, { Log } from '@ohos/common';
19
20const TAG = 'NativeApi';
21const ERROR = -1
22
23export class NativeApi {
24  private static instance: NativeApi;
25
26  public static getInstance(): NativeApi {
27    Log.info(TAG, 'getInstance enter');
28    if (this.instance === undefined) {
29      this.instance = new NativeApi();
30    }
31    return this.instance;
32  }
33
34  public getCapabilities(uri: string, printerName: string, getCapsCallback: (result) => void): void {
35    Log.debug(TAG, 'getCapabilities enter');
36    if (print === undefined) {
37      Log.error(TAG, 'print is undefined');
38      getCapsCallback(ERROR);
39      return;
40    }
41    Log.debug(TAG, 'getCapabilities start');
42    // @ts-ignore
43    print.queryPrinterCapabilityByUri(uri).then((result) => {
44      Log.debug(TAG, 'queryPrinterCapabilityByUri result: ' + JSON.stringify(result));
45      try {
46        let options = JSON.parse(result.options);
47        this.setCupsPrinter(uri, this.removeSpaces(printerName), options.make);
48      } catch (error) {
49        Log.error(TAG, 'parse options error: ' + JSON.stringify(error));
50        this.setCupsPrinter(uri, this.removeSpaces(printerName), '');
51      }
52      getCapsCallback(result);
53    }).catch((error) => {
54      Log.error(TAG, 'queryPrinterCapabilityByUri error: ' + JSON.stringify(error));
55      getCapsCallback(ERROR);
56    });
57    Log.debug(TAG, 'getCapabilities end');
58  }
59
60  public setCupsPrinter(uri: string, name: string, make: string): void {
61    Log.debug(TAG, 'setCupsPrinter enter');
62    if (print === undefined) {
63      Log.error(TAG, 'print is undefined');
64      return;
65    }
66    // @ts-ignore
67    print.addPrinterToCups(uri, name, make).then((result) => {
68      Log.debug(TAG, 'addPrinterToCups result: ' + JSON.stringify(result));
69    }).catch((error) => {
70      Log.error(TAG, 'addPrinterToCups error: ' + JSON.stringify(error));
71    });
72  }
73
74  private removeSpaces(name: string): string {
75    if (CheckEmptyUtils.checkStrIsEmpty(name)) {
76      return '';
77    }
78    return name.replace(/\s+/g, '_');
79  }
80}