• 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-nocheck
17import print from '@ohos.print';
18import { Constants, AppCommonEvent, AppStorageKeyName} from '@ohos/common';
19import { PrintJobState, PrintJobSubState } from '@ohos/common';
20import AppStorageHelper from '../Common/Adapter/AppStorageHelper';
21import { Log } from '@ohos/common';
22import { PrintJobModel } from '../Model/PrintJobModel';
23import { PrintJob } from '../Model/PrintJob';
24import FileUtil from '../Common/Utils/FileUtil';
25
26const TAG = '[PrintJobController]:';
27
28/**
29 * PrintJobController
30 *
31 */
32export class PrintJobController {
33  private mPrintJobModel: PrintJobModel = new PrintJobModel();
34  private mJobId: number = 0;
35
36  /**
37   * init
38   *
39   */
40  public init(): void {
41    Log.info(TAG, 'PrintJobController init');
42    AppStorageHelper.createValue<Array<PrintJob>>(this.getModel().mPrintJobs, AppStorageKeyName.JOB_QUEUE_NAME);
43    this.registerPrintJobCallback();
44  }
45
46  /**
47   * on destroy
48   */
49  public destroy(): void {
50    Log.info(TAG, 'PrintJobController destroy');
51    this.unregisterPrintJobCallback();
52  }
53
54  /**
55   * start print
56   *
57   * @param job print job Info
58   */
59  public startPrint(job: PrintJob): Promise<boolean> {
60    Log.info(TAG, 'startPrint, jobId =' + JSON.stringify(job.jobId));
61    let startTime = 'startPrintTime';
62    AppStorageHelper.createValue<number>(new Date().getTime(), startTime);
63    return new Promise((resolve) => {
64      let printJobs: Array<PrintJob> = this.getModel().mPrintJobs;
65      for (let index = 0; index < printJobs.length; index++) {
66        Log.info(TAG, ' job: ' + printJobs[index].jobId);
67        if (printJobs[index].jobId === job.jobId) {
68          this.getModel().updatePrintJob(index, job);
69          delete job.preview;
70          delete job.jobFiles;
71          if (printJobs[index].pageRange.pages.length === 0) {
72            job.pageRange = {
73              startPage: printJobs[index].pageRange.startPage,
74              endPage: printJobs[index].pageRange.endPage
75            };
76          } else {
77            job.pageRange = {
78              pages: printJobs[index].pageRange.pages
79            };
80          }
81          Log.debug(TAG, 'call startPrintJob');
82          print.startPrintJob(job).then((data) => {
83            Log.info(TAG, 'start Print success data : ' + JSON.stringify(data));
84            resolve(true);
85          }).catch((err) => {
86            Log.error(TAG, 'failed to start Print because ' + JSON.stringify(err));
87            // 任务下发失败
88            this.getModel()
89              .printJobStateChange(job.jobId, PrintJobState.PRINT_JOB_COMPLETED, PrintJobSubState.PRINT_JOB_COMPLETED_FAILED);
90            resolve(false);
91          });
92        }
93      }
94    });
95  }
96
97
98  /**
99   * cancle Print Job
100   *
101   * @param jobId job id
102   */
103  public cancelPrintJob(jobId: string): void {
104    Log.info(TAG, 'cancelPrintJob jobId = ' + JSON.stringify(jobId));
105    let printJobs = this.getModel().mPrintJobs;
106    for (let index = 0; index < printJobs.length; index++) {
107      if (printJobs[index].jobId === jobId) {
108        print.cancelPrintJob(jobId).then((data) => {
109          Log.info(TAG, 'cancel Print success data : ' + JSON.stringify(data));
110        }).catch((err) => {
111          Log.error(TAG, 'cancel to start Print because ' + JSON.stringify(err));
112        });
113        if (printJobs[index].jobState === PrintJobState.PRINT_JOB_QUEUED || printJobs[index].jobState === PrintJobState.PRINT_JOB_PREPARED) {
114          Log.debug(TAG, 'remove QUEUED PrintJob : ' + JSON.stringify(printJobs[index]));
115          setTimeout(() => {
116            this.getModel().removePrintJob(jobId);
117            if (this.getModel().mPrintJobs.length === 0) {
118              Log.info(TAG, 'no job need to show, terminate page');
119              let innerEvent = {
120                eventId: AppCommonEvent.TERMINATE_JOB_MANAGER_ABILITY_EVENT,
121                priority: emitter.EventPriority.HIGH
122              };
123              emitter.emit(innerEvent);
124            }
125          }, <number>Constants.SHOW_JOB_COMPLETED_TIMEOUT);
126        }
127        this.getModel().printJobStateChange(jobId, PrintJobState.PRINT_JOB_CANCELLING, PrintJobSubState.PRINT_JOB_BLOCK_UNKNOWN);
128      }
129    }
130  }
131
132  /**
133   * register printJob callback
134   */
135  private registerPrintJobCallback(): void {
136    Log.info(TAG, 'registerPrintJobCallback');
137    print.on('jobStateChange', this.onJobStateChanged);
138  }
139
140  /**
141   * print Job state change callback
142   *
143   * @param state printJob state
144   * @param job printJob
145   */
146  private onJobStateChanged = (state: print.PrintJobState, job: print.PrintJob): void => {
147    if (state === null || job === null) {
148      Log.error(TAG, 'device state changed null data');
149      return;
150    }
151    Log.info(TAG, 'on job state changed, state = ' + JSON.stringify(state));
152    this.deleteLocalSource(<number>state, <string>job.jobId);
153    switch (state) {
154      case PrintJobState.PRINT_JOB_PREPARED:
155      case PrintJobState.PRINT_JOB_QUEUED:
156      case PrintJobState.PRINT_JOB_RUNNING:
157      case PrintJobState.PRINT_JOB_BLOCKED:
158      case PrintJobState.PRINT_JOB_COMPLETED:
159        this.onPrintJobStateChange(job);
160        break;
161      default:
162        break;
163    }
164  };
165
166  /**
167   * deal print Job state change
168   *
169   * @param job printJob
170   */
171  private onPrintJobStateChange(job: print.PrintJob): void {
172    if (job === null) {
173      Log.info(TAG, 'onDeviceVerified for null data.');
174      return;
175    }
176    Log.info(TAG, 'on printJob state change, jobId = ' +
177    job.jobId + ' jobState= ' + job.jobState + 'jobSubState = ' + job.jobSubState);
178    this.getModel().printJobStateChange(job.jobId, job.jobState, job.jobSubState);
179  }
180
181  /**
182   * unregister printJob callback
183   */
184  private unregisterPrintJobCallback(): void {
185    Log.info(TAG, 'unregisterDeviceCallback');
186    print.off('jobStateChange', (data) => {
187      Log.info(TAG, 'off printJobStateChange data : ' + JSON.stringify(data));
188    });
189  }
190
191  /**
192   * create print Job
193   *
194   * @param jobId printJob id
195   * @return job state
196   */
197  public createPrintJob(jobId: string): number {
198    let newJob = new PrintJob([], [], jobId, null, PrintJobState.PRINT_JOB_PREPARED, 0, 0,
199      null, false, null, false, 0, 0, null, null, null);
200    this.getModel().addPrintJob(newJob);
201    Log.info(TAG, 'createPrintJob, jobId = ' + JSON.stringify(jobId));
202    return <number>newJob.jobState;
203  }
204
205  /**
206   * get model
207   *
208   * @return PrintJobModel
209   */
210  public getModel(): PrintJobModel {
211    return this.mPrintJobModel;
212  }
213
214  private async deleteLocalSource(state: number, jobId: string): void {
215    Log.debug(TAG, 'jobId: ' + jobId);
216    if (state === PrintJobState.PRINT_JOB_COMPLETED) {
217      Log.info(TAG, 'delete local source');
218      let printJob = this.mPrintJobModel.mPrintJobs.find((job) => {
219        return job.jobId === jobId;
220      });
221      if (printJob === undefined) {
222        Log.error(TAG, 'deleteLocalSource printJob is undefined');
223        return;
224      }
225      FileUtil.deleteSource(<string[]>printJob.jobFiles);
226    }
227  }
228
229  private convertToHwPrintJob(item: print.PrintJob): PrintJob {
230    if (!this.isValidPrintJob(item)) {
231      Log.info(TAG, `convertToHwPrintJob invalid job, jobId${item.jobId}}`);
232      return null;
233    }
234    return new PrintJob(item.jobFiles, item.fdList, item.jobId, item.printerId, item.jobState,
235      item.jobSubState, item.copyNumber, item.pageRange, item.isSequential, item.pageSize, item.isLandscape,
236      item.colorMode, item.duplexMode, item.margin, item.preview, item.option);
237  }
238
239  /**
240   * queryAllPrintJobs
241   */
242  async queryAllPrintJobs(printerId?: string): Promise<Array<PrintJob>> {
243    return new Promise((resolve) => {
244      print.queryAllPrintJobs().then((data) => {
245        Log.info(TAG, `queryAllPrintJobs data.length:${data?.length}`);
246        let retPrintJobs:Array<PrintJob> = [];
247        for (let item of data) {
248          let printJob = this.convertToHwPrintJob(item);
249          if (printJob === null) {
250            Log.warn(TAG, 'queryAllPrintJobs invalid job.');
251            continue;
252          }
253          if (printerId === undefined || hwPrintJob.printerId === printerId) {
254            retPrintJobs.push(printJob);
255          }
256        }
257        Log.info(TAG, `queryAllPrintJobs retPrintJobs.length:${retPrintJobs.length}`);
258        resolve(retPrintJobs);
259      }).catch((err) => {
260        Log.error(TAG, `failed to queryAllPrintJobs Cause:${JSON.stringify(err)}`);
261      });
262    });
263  }
264}
265