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 '@ohos.print'; 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 this.setCupsPrinter(uri, this.removeSpaces(printerName)); 46 getCapsCallback(result); 47 }).catch((error) => { 48 Log.error(TAG, 'queryPrinterCapabilityByUri error: ' + JSON.stringify(error)); 49 getCapsCallback(ERROR); 50 }); 51 Log.debug(TAG, 'getCapabilities end'); 52 } 53 54 public setCupsPrinter(uri: string, name: string): void { 55 Log.debug(TAG, 'setCupsPrinter enter'); 56 if (print === undefined) { 57 Log.error(TAG, 'print is undefined'); 58 return; 59 } 60 // @ts-ignore 61 print.addPrinterToCups(uri, name).then((result) => { 62 Log.debug(TAG, 'addPrinterToCups result: ' + JSON.stringify(result)); 63 }).catch((error) => { 64 Log.error(TAG, 'addPrinterToCups error: ' + JSON.stringify(error)); 65 }); 66 } 67 68 private removeSpaces(name: string): string { 69 if (CheckEmptyUtils.checkStrIsEmpty(name)) { 70 return ''; 71 } 72 return name.replace(/\s+/g, '_'); 73 } 74}