All files / src/lib scanner.ts

100% Statements 174/174
100% Branches 50/50
100% Functions 28/28
100% Lines 168/168

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 54915x       15x 15x   15x 15x 15x 15x 15x     15x 15x 15x                   15x                               30x                                                             86x 172x 86x         86x 86x 1x   85x 1x           84x 84x 84x 84x 84x   84x 84x 84x   84x 84x   84x 84x 1x     84x                   15x 49x 48x   49x                 155x 155x 155x 155x     155x 155x         2x     155x 154x         155x   155x                 15x 18x 18x         18x                     15x 2x       2x                                                           15x   25x   14x 2x         12x 2x 1x   2x 2x 2x 2x           12x   1x 1x   1x 1x   9x 9x   1x 1x     12x 2x               10x 10x   10x 10x 10x 10x     2x 2x                 10x 1x 1x 1x       1x   10x                             15x 17x           15x 96x                                                       15x 126x 68x 2x   66x   58x 3x 1x   2x     55x     126x                   15x 1x                 15x 8x                     15x 61x                     15x 269x                                   15x 12x   12x 12x 12x 12x 2x 2x         2x 3x 3x   2x   12x 1x 1x 1x       1x   12x                                 15x 89x   89x                 15x 1x   1x     15x 22x 20x   2x 2x 1x       1x                 15x 21x   21x 19x   12x 12x 12x 12x 12x   2x 2x 2x   1x 1x 1x   2x 2x   1x 1x   1x       15x                          
import { EventEmitter, ListenerFn } from "eventemitter3";
 
import { EngineSentMessageData, EngineWorker } from "./workers/engineWorker";
 
import { blurryRecognitionPreloader, engineLoader, userLicenseKey } from "../index";
import { Barcode, BarcodeWASMResult } from "./barcode";
import { BrowserCompatibility } from "./browserCompatibility";
import { BrowserHelper } from "./browserHelper";
import { CustomError } from "./customError";
import { EngineLoader } from "./engineLoader";
import { ImageSettings } from "./imageSettings";
import { Parser } from "./parser";
import { ParserField } from "./parserField";
import { ParserResult } from "./parserResult";
import { ScanResult } from "./scanResult";
import { ScanSettings } from "./scanSettings";
import { UnsupportedBrowserError } from "./unsupportedBrowserError";
 
/**
 * @hidden
 */
type EventName = "ready" | "licenseKeyFeaturesReady" | "newScanSettings";
 
/**
 * @hidden
 */
class ScannerEventEmitter extends EventEmitter<string> {}
 
/**
 * A low-level scanner interacting with the external Scandit Engine library.
 * Used to set up scan / image settings and to process single image frames.
 *
 * The loading of the external Scandit Engine library can take some time, the [[on]] method targeting the [[ready]]
 * event can be used to set up a listener function to be called when the library is loaded and the [[isReady]] method
 * can return the current status. The scanner will be ready to start scanning when the library is fully loaded.
 *
 * By default the external Scandit Engine library is preloaded in order to reduce the initialization time as much as
 * possible.
 *
 * In the special case where a single [[Scanner]] instance is shared between multiple active [[BarcodePicker]]
 * instances, the fairness in resource allocation for processing images between the different pickers is not guaranteed.
 */
export class Scanner {
  private readonly engineWorker: EngineWorker;
  private readonly eventEmitter: ScannerEventEmitter;
 
  private scanSettings: ScanSettings;
  private imageSettings?: ImageSettings;
  private workerParseRequestId: number;
  private workerScanRequestId: number;
  private workerScanQueueLength: number;
  private isReadyToWork: boolean;
  private licenseKeyFeatures?: object;
  private imageDataConversionContext?: CanvasRenderingContext2D;
  private activeBlurryRecognitionSymbologies: Set<Barcode.Symbology>;
  private blurryRecognitionAvailable: boolean;
 
  /**
   * Create a Scanner instance.
   *
   * It is required to having configured the library via [[configure]] before this object can be created.
   *
   * Before processing an image the relative settings must also have been set.
   *
   * If the library has not been correctly configured yet a `LibraryNotConfiguredError` error is thrown.
   *
   * If a browser is incompatible a `UnsupportedBrowserError` error is thrown.
   *
   * @param scanSettings <div class="tsd-signature-symbol">Default =&nbsp;new ScanSettings()</div>
   * The configuration object for scanning options.
   * @param imageSettings <div class="tsd-signature-symbol">Default =&nbsp;undefined</div>
   * The configuration object to define the properties of an image to be scanned.
   */
  constructor({
    scanSettings = new ScanSettings(),
    imageSettings,
  }: {
    scanSettings?: ScanSettings;
    imageSettings?: ImageSettings;
  } = {}) {
    const browserCompatibility: BrowserCompatibility = BrowserHelper.checkBrowserCompatibility();
    if (!browserCompatibility.scannerSupport) {
      throw new UnsupportedBrowserError(browserCompatibility);
    }
    if (userLicenseKey == null) {
      throw new CustomError({
        name: "LibraryNotConfiguredError",
        message: "The library has not correctly been configured yet, please call 'configure' with valid parameters",
      });
    }
 
    this.eventEmitter = new EventEmitter();
    this.isReadyToWork = false;
    this.workerScanQueueLength = 0;
    this.workerParseRequestId = 0;
    this.workerScanRequestId = 0;
 
    this.engineWorker = engineLoader.getEngineWorker();
    this.engineWorker.onmessage = this.engineWorkerOnMessage.bind(this);
    EngineLoader.load(this.engineWorker);
 
    this.activeBlurryRecognitionSymbologies = new Set();
    this.blurryRecognitionAvailable = false;
 
    this.applyScanSettings(scanSettings);
    if (imageSettings != null) {
      this.applyImageSettings(imageSettings);
    }
 
    blurryRecognitionPreloader.on("blurryTablesUpdate", this.handleBlurryTablesUpdate.bind(this));
  }
 
  /**
   * Stop/reset the internal WebWorker and destroy the scanner itself; ensuring complete cleanup.
   *
   * This method should be called after you don't plan to use the scanner anymore,
   * before the object is automatically cleaned up by JavaScript.
   * The scanner must not be used in any way after this call.
   */
  public destroy(): void {
    if (this.engineWorker != null) {
      engineLoader.returnEngineWorker(this.engineWorker);
    }
    this.eventEmitter.removeAllListeners();
  }
 
  /**
   * Apply a new set of scan settings to the scanner (replacing old settings).
   *
   * @param scanSettings The scan configuration object to be applied to the scanner.
   * @returns The updated [[Scanner]] object.
   */
  public applyScanSettings(scanSettings: ScanSettings): Scanner {
    this.scanSettings = scanSettings;
    blurryRecognitionPreloader.updateBlurryRecognitionPriority(this.scanSettings);
    const activeBlurryRecognitionSymbologies: Barcode.Symbology[] = blurryRecognitionPreloader.getEnabledSymbologies(
      this.scanSettings
    );
    this.blurryRecognitionAvailable = blurryRecognitionPreloader.isBlurryRecognitionAvailable(this.scanSettings);
    this.engineWorker.postMessage({
      type: "settings",
      settings: this.scanSettings.toJSONString(),
      blurryRecognitionAvailable: this.blurryRecognitionAvailable,
      blurryRecognitionRequiresUpdate: activeBlurryRecognitionSymbologies.some((symbology) => {
        return !this.activeBlurryRecognitionSymbologies.has(symbology);
      }),
    });
    if (this.blurryRecognitionAvailable) {
      this.activeBlurryRecognitionSymbologies = new Set([
        ...this.activeBlurryRecognitionSymbologies,
        ...activeBlurryRecognitionSymbologies,
      ]);
    }
    this.eventEmitter.emit("newScanSettings", this.scanSettings);
 
    return this;
  }
 
  /**
   * Apply a new set of image settings to the scanner (replacing old settings).
   *
   * @param imageSettings The image configuration object to be applied to the scanner.
   * @returns The updated [[Scanner]] object.
   */
  public applyImageSettings(imageSettings: ImageSettings): Scanner {
    this.imageSettings = imageSettings;
    this.engineWorker.postMessage({
      type: "image-settings",
      imageSettings,
    });
 
    return this;
  }
 
  /**
   * Clear the scanner session.
   *
   * This removes all recognized barcodes from the scanner session and allows them to be scanned again in case a custom
   * *codeDuplicateFilter* was set in the [[ScanSettings]].
   *
   * @returns The updated [[Scanner]] object.
   */
  public clearSession(): Scanner {
    this.engineWorker.postMessage({
      type: "clear-session",
    });
 
    return this;
  }
 
  /**
   * Process a given image using the previously set scanner and image settings,
   * recognizing codes and retrieving the result as a list of barcodes (if any).
   *
   * Multiple requests done without waiting for previous results will be queued and handled in order.
   *
   * If *highQualitySingleFrameMode* is enabled the image will be processed with really accurate internal settings,
   * resulting in much slower but more precise scanning results. This should be used only for single images not part
   * of a continuous video stream.
   *
   * Passing image data as a *Uint8Array* is the fastest option, passing a *HTMLImageElement*
   * will incur in additional operations.
   *
   * Data passed to this function is "detached"/"neutered" becoming unusable as it's being passed to the external
   * Scandit Engine library. You can access the same data once it's returned in the [[ScanResult.imageData]] property.
   *
   * Depending on the current image settings, given *imageData* and scanning execution, any of the following errors
   * could be the rejected result of the returned promise:
   * - `NoImageSettings`
   * - `ImageSettingsDataMismatch`
   * - `ScanditEngineError`
   *
   * @param imageData The image data given as byte array or image element, complying with the previously set
   * image settings.
   * @param highQualitySingleFrameMode Whether to process the image as a high quality single frame.
   * @returns A promise resolving to the [[ScanResult]] object.
   */
  public processImage(
    imageData: Uint8Array | HTMLImageElement,
    highQualitySingleFrameMode: boolean = false
  ): Promise<ScanResult> {
    if (this.imageSettings == null) {
      return Promise.reject(
        new CustomError({ name: "NoImageSettings", message: "No image settings set up in the scanner" })
      );
    }
 
    if (imageData instanceof HTMLImageElement) {
      if (this.imageDataConversionContext == null) {
        this.imageDataConversionContext = <CanvasRenderingContext2D>document.createElement("canvas").getContext("2d");
      }
      this.imageDataConversionContext.canvas.width = imageData.naturalWidth;
      this.imageDataConversionContext.canvas.height = imageData.naturalHeight;
      this.imageDataConversionContext.drawImage(imageData, 0, 0, imageData.naturalWidth, imageData.naturalHeight);
      imageData = new Uint8Array(
        this.imageDataConversionContext.getImageData(0, 0, imageData.naturalWidth, imageData.naturalHeight).data.buffer
      );
    }
 
    let channels: number;
    switch (this.imageSettings.format.valueOf()) {
      case ImageSettings.Format.GRAY_8U:
        channels = 1;
        break;
      case ImageSettings.Format.RGB_8U:
        channels = 3;
        break;
      case ImageSettings.Format.RGBA_8U:
        channels = 4;
        break;
      default:
        channels = 1;
        break;
    }
 
    if (this.imageSettings.width * this.imageSettings.height * channels !== imageData.length) {
      return Promise.reject(
        new CustomError({
          name: "ImageSettingsDataMismatch",
          message: "The provided image data doesn't match the previously set image settings",
        })
      );
    }
 
    this.workerScanRequestId++;
    this.workerScanQueueLength++;
 
    return new Promise<ScanResult>((resolve, reject) => {
      const workResultEvent: string = `workResult-${this.workerScanRequestId}`;
      const workErrorEvent: string = `workError-${this.workerScanRequestId}`;
      this.eventEmitter.once(
        workResultEvent,
        (workResult: { scanResult: BarcodeWASMResult[] }, returnedImageData: Uint8Array) => {
          this.eventEmitter.removeAllListeners(workErrorEvent);
          resolve(
            new ScanResult(
              workResult.scanResult.map(Barcode.createFromWASMResult),
              returnedImageData,
              <ImageSettings>this.imageSettings
            )
          );
        }
      );
      this.eventEmitter.once(workErrorEvent, (error: { errorCode: number; errorMessage: string }, _: Uint8Array) => {
        console.error(`Scandit Engine error (${error.errorCode}):`, error.errorMessage);
        this.eventEmitter.removeAllListeners(workResultEvent);
        const errorObject: Error = new CustomError({
          name: "ScanditEngineError",
          message: `${error.errorMessage} (${error.errorCode})`,
        });
        reject(errorObject);
      });
      this.engineWorker.postMessage(
        {
          type: "work",
          requestId: this.workerScanRequestId,
          data: <Uint8Array>imageData,
          highQualitySingleFrameMode,
        },
        [(<Uint8Array>imageData).buffer]
      );
    });
  }
 
  /**
   * @returns Whether the scanner is currently busy processing an image.
   */
  public isBusyProcessing(): boolean {
    return this.workerScanQueueLength !== 0;
  }
 
  /**
   * @returns Whether the scanner has loaded the external Scandit Engine library and is ready to scan.
   */
  public isReady(): boolean {
    return this.isReadyToWork;
  }
 
  /**
   * Add the listener function to the listeners array for an event.
   *
   * No checks are made to see if the listener has already been added.
   * Multiple calls passing the same listener will result in the listener being added, and called, multiple times.
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function.
   * @returns The updated [[Scanner]] object.
   */
  // tslint:disable-next-line:bool-param-default
  public on(eventName: EventName, listener: ListenerFn): Scanner;
  /**
   * Add the listener function to the listeners array for the [[ready]] event, fired only once when the external
   * Scandit Engine library has been loaded and the scanner can thus start to scan barcodes.
   * If the external Scandit Engine library has already been loaded the listener is called immediately.
   *
   * No checks are made to see if the listener has already been added.
   * Multiple calls passing the same listener will result in the listener being added, and called, multiple times.
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function.
   * @returns The updated [[Scanner]] object.
   */
  public on(eventName: "ready", listener: () => void): Scanner;
  public on(eventName: EventName, listener: ListenerFn): Scanner {
    if (eventName === "ready") {
      if (this.isReadyToWork) {
        listener();
      } else {
        this.eventEmitter.once(eventName, listener, this);
      }
    } else if (eventName === "licenseKeyFeaturesReady") {
      if (this.licenseKeyFeatures != null) {
        listener(this.licenseKeyFeatures);
      } else {
        this.eventEmitter.once(eventName, listener, this);
      }
    } else {
      this.eventEmitter.on(eventName, listener, this);
    }
 
    return this;
  }
 
  /**
   * *See the [[on]] method.*
   *
   * @param eventName The name of the event to listen to.
   * @param listener The listener function.
   * @returns The updated [[Scanner]] object.
   */
  public addListener(eventName: EventName, listener: ListenerFn): Scanner {
    return this.on(eventName, listener);
  }
 
  /**
   * Create a new parser object.
   *
   * @param dataFormat The format of the input data for the parser.
   * @returns The newly created parser.
   */
  public createParserForFormat(dataFormat: Parser.DataFormat): Parser {
    return new Parser(this, dataFormat);
  }
 
  /**
   * Return the current image settings.
   *
   * Note that modifying this object won't directly apply these settings: the [[applyImageSettings]] method must be
   * called with the updated object.
   *
   * @returns The current image settings.
   */
  public getImageSettings(): ImageSettings | undefined {
    return this.imageSettings;
  }
 
  /**
   * Return the current scan settings.
   *
   * Note that modifying this object won't directly apply these settings: the [[applyScanSettings]] method must be
   * called with the updated object.
   *
   * @returns The current scan settings.
   */
  public getScanSettings(): ScanSettings {
    return this.scanSettings;
  }
 
  /**
   * @hidden
   *
   * Process a given string using the Scandit Parser library,
   * parsing the data in the given format and retrieving the result as a [[ParserResult]] object.
   *
   * Multiple requests done without waiting for previous results will be queued and handled in order.
   *
   * If parsing of the data fails the returned promise is rejected with a `ScanditEngineError` error.
   *
   * @param dataFormat The format of the given data.
   * @param dataString The string containing the data to be parsed.
   * @param options Options for the specific data format parser.
   * @returns A promise resolving to the [[ParserResult]] object.
   */
  public parseString(dataFormat: Parser.DataFormat, dataString: string, options?: object): Promise<ParserResult> {
    this.workerParseRequestId++;
 
    return new Promise<ParserResult>((resolve, reject) => {
      const parseStringResultEvent: string = `parseStringResult-${this.workerParseRequestId}`;
      const parseStringErrorEvent: string = `parseStringError-${this.workerParseRequestId}`;
      this.eventEmitter.once(parseStringResultEvent, (result: string) => {
        this.eventEmitter.removeAllListeners(parseStringErrorEvent);
        const parserResult: ParserResult = {
          jsonString: result,
          fields: [],
          fieldsByName: {},
        };
        (<ParserField[]>JSON.parse(result)).forEach((parserField) => {
          parserResult.fields.push(parserField);
          parserResult.fieldsByName[parserField.name] = parserField;
        });
        resolve(parserResult);
      });
      this.eventEmitter.once(parseStringErrorEvent, (error: { errorCode: number; errorMessage: string }) => {
        console.error(`Scandit Engine error (${error.errorCode}):`, error.errorMessage);
        this.eventEmitter.removeAllListeners(parseStringResultEvent);
        const errorObject: Error = new CustomError({
          name: "ScanditEngineError",
          message: `${error.errorMessage} (${error.errorCode})`,
        });
        reject(errorObject);
      });
      this.engineWorker.postMessage({
        type: "parse-string",
        requestId: this.workerParseRequestId,
        dataFormat,
        dataString,
        options: options == null ? "{}" : JSON.stringify(options),
      });
    });
  }
 
  /**
   * Remove the specified listener from the given event's listener array.
   *
   * @param eventName The name of the event from which to remove the listener.
   * @param listener The listener function to be removed.
   * @returns The updated [[Scanner]] object.
   */
  public removeListener(eventName: string, listener: ListenerFn): Scanner {
    this.eventEmitter.removeListener(eventName, listener);
 
    return this;
  }
 
  /**
   * Remove all listeners from the given event's listener array.
   *
   * @param eventName The name of the event from which to remove all listeners.
   * @returns The updated [[Scanner]] object.
   */
  public removeAllListeners(eventName: EventName): Scanner {
    this.eventEmitter.removeAllListeners(eventName);
 
    return this;
  }
 
  private handleBlurryTablesUpdate(): void {
    if (this.blurryRecognitionAvailable) {
      return;
    }
    this.blurryRecognitionAvailable = blurryRecognitionPreloader.isBlurryRecognitionAvailable(this.scanSettings);
    if (this.blurryRecognitionAvailable) {
      this.activeBlurryRecognitionSymbologies = new Set([
        ...this.activeBlurryRecognitionSymbologies,
        ...blurryRecognitionPreloader.getEnabledSymbologies(this.scanSettings),
      ]);
      this.engineWorker.postMessage({
        type: "settings",
        settings: this.scanSettings.toJSONString(),
        blurryRecognitionAvailable: true,
        blurryRecognitionRequiresUpdate: true,
      });
    }
  }
 
  private engineWorkerOnMessage(ev: MessageEvent): void {
    const data: EngineSentMessageData = ev.data;
 
    if (data[1] != null) {
      switch (data[0]) {
        case "license-key-features":
          this.isReadyToWork = true;
          this.licenseKeyFeatures = data[1];
          this.eventEmitter.emit("ready");
          this.eventEmitter.emit("licenseKeyFeaturesReady", this.licenseKeyFeatures);
          break;
        case "work-result":
          this.eventEmitter.emit(`workResult-${data[1].requestId}`, data[1].result, data[2]);
          this.workerScanQueueLength--;
          break;
        case "work-error":
          this.eventEmitter.emit(`workError-${data[1].requestId}`, data[1].error, data[2]);
          this.workerScanQueueLength--;
          break;
        case "parse-string-result":
          this.eventEmitter.emit(`parseStringResult-${data[1].requestId}`, data[1].result);
          break;
        case "parse-string-error":
          this.eventEmitter.emit(`parseStringError-${data[1].requestId}`, data[1].error);
          break;
        default:
          break;
      }
    }
  }
}
 
// istanbul ignore next
export namespace Scanner {
  /**
   * Fired when the external Scandit Engine library has been loaded and the scanner can thus start to scan barcodes.
   *
   * @asMemberOf Scanner
   * @event
   */
  // @ts-ignore
  declare function ready(): void;
}