All files / src/lib/barcodePicker gui.ts

93.46% Statements 429/459
81.22% Branches 173/213
88.46% Functions 46/52
93.36% Lines 422/452

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 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 88715x           15x   15x             15x 15x 15x 15x       15x 15x     15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x                                                                               80x                             80x 80x 80x 80x 80x 80x 80x 80x 80x   80x 80x 80x 80x 80x 80x   80x 80x 80x 80x 80x 80x 80x   80x   80x 15x   15x 15x 15x 15x   15x   15x   65x   65x     65x 64x 64x   1x     65x 65x 65x 65x 65x 65x 65x 65x   65x 65x   65x 65x 65x   65x 65x     80x 1x 1x   79x     80x 80x         80x   80x     15x 68x 52x   68x 52x   68x 52x   68x 1x   68x 68x 68x     15x 62x     15x 16x 16x 16x 16x     15x 11x 11x 11x 11x     15x 10x     15x 87x 87x       2x 2x 2x 2x     87x   87x 81x 81x 63x 18x 1x     6x       15x 36x 32x       32x   4x       15x 25x 24x 9x   15x     24x 4x               15x 76x 1x     75x   64x 64x 64x 64x   5x 5x 5x 5x     6x 6x 6x 6x       15x 133x 133x 131x   133x 133x 133x 133x 133x 133x     15x 133x 133x 131x   133x 133x 133x 133x 133x 133x     15x 75x 2x     73x   73x 5x 5x   68x 68x   68x         73x     15x 4x 2x 2x     4x 4x 4x 4x 4x   4x     15x 27x 24x 3x 1x       15x 6x 1x         5x 5x   3x         2x       1x 1x 1x   1x               1x                   1x     2x   2x         1x     1x   1x                   15x 5x     15x 23x 19x   4x       15x 23x 1x   22x       15x 22x 22x             15x 6x 3x 3x   3x 3x       15x 64x 64x 64x 64x 64x             64x 64x 64x 64x     15x 65x 65x 65x 65x 65x     15x 15x   15x       15x 15x         15x   15x   15x         15x   15x 15x 15x 15x 15x           15x 15x   15x   15x   15x 30x   15x 15x 15x   15x 15x   15x     15x 65x 65x   65x 65x   65x 65x   65x 65x     65x 65x 65x     15x 24x   24x 24x     15x 1x   1x 1x     15x 165x 165x   165x 165x   165x 151x     14x 5x   9x       15x 5x     15x 9x       9x   9x 3x 3x   3x 1x   2x     3x                 3x     6x 2x   4x     6x 6x   6x     15x 4x                         15x 6x     15x 3x       3x 3x 1x 1x   2x 1x 1x   1x 1x       6x     15x   3x 3x 3x   3x 3x             3x 6x 3x 3x     15x 4x 4x 3x 3x 3x 3x 3x   3x 3x 3x                   3x     3x     3x     3x 3x       15x 5x 5x 5x   5x 5x 1x   1x   4x 4x 7x   4x 6x   10x         2x 2x 3x 1x 2x         2x   3x   4x               65x 65x 65x 65x 65x 65x 130x       65x 65x 65x 65x 65x 65x 130x                         15x 79x       79x 79x 79x 79x     15x 67x 66x   67x 66x       15x                                                                           15x  
import { ResizeObserver as ResizeObserverPolyfill } from "@juggle/resize-observer";
 
/**
 * @hidden
 */
// tslint:disable-next-line: variable-name no-any
const ResizeObserver: typeof ResizeObserverPolyfill = (<any>window).ResizeObserver ?? ResizeObserverPolyfill;
 
import {
  laserActiveImage,
  laserPausedImage,
  scanditLogoImage,
  switchCameraImage,
  toggleTorchImage,
} from "../assets/base64assets";
import { BrowserHelper } from "../browserHelper";
import { Camera } from "../camera";
import { CameraAccess } from "../cameraAccess";
import { ImageSettings } from "../imageSettings";
import { Scanner } from "../scanner";
import { ScanSettings } from "../scanSettings";
import { SearchArea } from "../searchArea";
import { SingleImageModePlatformSettings, SingleImageModeSettings } from "../singleImageModeSettings";
import { BarcodePicker } from "./barcodePicker";
import { CameraManager } from "./cameraManager";
 
export class GUI {
  public static readonly grandParentElementClassName: string = "scandit scandit-container";
  public static readonly parentElementClassName: string = "scandit scandit-barcode-picker";
  public static readonly hiddenClassName: string = "scandit-hidden";
  public static readonly hiddenOpacityClassName: string = "scandit-hidden-opacity";
  public static readonly videoElementClassName: string = "scandit-video";
  public static readonly scanditLogoImageElementClassName: string = "scandit-logo";
  public static readonly laserContainerElementClassName: string = "scandit-laser";
  public static readonly viewfinderElementClassName: string = "scandit-viewfinder";
  public static readonly cameraSwitcherElementClassName: string = "scandit-camera-switcher";
  public static readonly torchTogglerElementClassName: string = "scandit-torch-toggle";
  public static readonly cameraUploadElementClassName: string = "scandit-camera-upload";
  public static readonly flashColorClassName: string = "scandit-flash-color";
  public static readonly flashWhiteClassName: string = "scandit-flash-white";
  public static readonly flashInsetClassName: string = "scandit-flash-inset";
  public static readonly opacityPulseClassName: string = "scandit-opacity-pulse";
  public static readonly mirroredClassName: string = "mirrored";
  public static readonly pausedClassName: string = "paused";
 
  public readonly videoElement: HTMLVideoElement;
  public readonly cameraSwitcherElement: HTMLImageElement;
  public readonly torchTogglerElement: HTMLImageElement;
 
  private readonly scanner: Scanner;
  private readonly singleImageModeEnabled: boolean;
  private readonly singleImageModeSettings: SingleImageModePlatformSettings;
  private readonly grandParentElement: HTMLDivElement;
  private readonly parentElement: HTMLDivElement;
  private readonly laserContainerElement: HTMLDivElement;
  private readonly laserActiveImageElement: HTMLImageElement;
  private readonly laserPausedImageElement: HTMLImageElement;
  private readonly viewfinderElement: HTMLDivElement;
  private readonly cameraUploadElement: HTMLDivElement;
  private readonly cameraUploadLabelElement: HTMLLabelElement;
  private readonly cameraUploadInputElement: HTMLInputElement;
  private readonly cameraUploadProgressElement: HTMLDivElement;
  private readonly context2d?: CanvasRenderingContext2D;
  private readonly contextWebGL?: WebGLRenderingContext;
  private readonly visibilityListener: EventListenerOrEventListenerObject;
  private readonly videoResizeListener: EventListenerOrEventListenerObject;
  private readonly newScanSettingsListener: (scanSettings: ScanSettings) => void;
  private readonly licenseKeyFeaturesReadyListener: (licenseKeyFeatures: object) => void;
  private readonly resizeObserver: ResizeObserverPolyfill;
  private readonly cameraUploadCallback: () => Promise<void>;
  private readonly mirrorImageOverrides: Map<string, boolean>;
 
  private cameraManager?: CameraManager;
  private originElement: HTMLElement;
  private scanningPaused: boolean;
  private visible: boolean;
  private guiStyle: BarcodePicker.GuiStyle;
  private videoFit: BarcodePicker.ObjectFit;
  private customLaserArea?: SearchArea;
  private customViewfinderArea?: SearchArea;
  private cameraUploadInProgress: boolean;
  private cameraSwitchInProgress: boolean;
 
  public constructor(options: {
    scanner: Scanner;
    originElement: HTMLElement;
    singleImageModeEnabled: boolean;
    singleImageModeSettings: SingleImageModePlatformSettings;
    scanningPaused: boolean;
    visible: boolean;
    guiStyle: BarcodePicker.GuiStyle;
    videoFit: BarcodePicker.ObjectFit;
    hideLogo: boolean;
    cameraType: Camera.Type;
    laserArea?: SearchArea;
    viewfinderArea?: SearchArea;
    cameraUploadCallback(): Promise<void>;
  }) {
    this.scanner = options.scanner;
    this.originElement = options.originElement;
    this.singleImageModeEnabled = options.singleImageModeEnabled;
    this.singleImageModeSettings = options.singleImageModeSettings;
    this.scanningPaused = options.scanningPaused;
    this.cameraUploadCallback = options.cameraUploadCallback;
    this.mirrorImageOverrides = new Map<string, boolean>();
    this.cameraUploadInProgress = false;
    this.cameraSwitchInProgress = false;
 
    this.grandParentElement = document.createElement("div");
    this.grandParentElement.className = GUI.grandParentElementClassName;
    this.originElement.appendChild(this.grandParentElement);
    this.parentElement = document.createElement("div");
    this.parentElement.className = GUI.parentElementClassName;
    this.grandParentElement.appendChild(this.parentElement);
 
    this.videoElement = document.createElement("video");
    this.cameraSwitcherElement = document.createElement("img");
    this.torchTogglerElement = document.createElement("img");
    this.laserContainerElement = document.createElement("div");
    this.laserActiveImageElement = document.createElement("img");
    this.laserPausedImageElement = document.createElement("img");
    this.viewfinderElement = document.createElement("div");
 
    const canvas: HTMLCanvasElement = document.createElement("canvas");
 
    if (options.singleImageModeEnabled) {
      this.context2d = <CanvasRenderingContext2D>canvas.getContext("2d");
 
      this.cameraUploadElement = document.createElement("div");
      this.cameraUploadLabelElement = document.createElement("label");
      this.cameraUploadInputElement = document.createElement("input");
      this.cameraUploadProgressElement = document.createElement("div");
 
      this.setupCameraUploadGuiAssets(options.cameraType);
 
      this.guiStyle = BarcodePicker.GuiStyle.NONE;
    } else {
      let context: WebGLRenderingContext | null = canvas.getContext("webgl", { alpha: false, antialias: false });
      // istanbul ignore if
      if (context == null) {
        context = <WebGLRenderingContext>canvas.getContext("experimental-webgl", { alpha: false, antialias: false });
      }
      if (context != null) {
        this.contextWebGL = context;
        this.setupWebGL(this.contextWebGL);
      } else {
        this.context2d = <CanvasRenderingContext2D>canvas.getContext("2d");
      }
 
      this.setupVideoElement();
      this.setupCameraSwitcher();
      this.setupTorchToggler();
      this.setupFullGuiAssets();
      this.setGuiStyle(options.guiStyle);
      this.setVideoFit(options.videoFit);
      this.setLaserArea(options.laserArea);
      this.setViewfinderArea(options.viewfinderArea);
 
      this.visibilityListener = this.checkAndRecoverPlayback.bind(this);
      document.addEventListener("visibilitychange", this.visibilityListener);
 
      this.newScanSettingsListener = this.handleNewScanSettings.bind(this);
      this.scanner.on("newScanSettings", this.newScanSettingsListener);
      this.handleNewScanSettings();
 
      this.videoResizeListener = this.handleVideoResize.bind(this);
      this.videoElement.addEventListener("resize", this.videoResizeListener);
    }
 
    if (options.hideLogo) {
      this.licenseKeyFeaturesReadyListener = this.showScanditLogo.bind(this, options.hideLogo);
      this.scanner.on("licenseKeyFeaturesReady", this.licenseKeyFeaturesReadyListener);
    } else {
      this.showScanditLogo(false);
    }
 
    this.resize();
    this.resizeObserver = new ResizeObserver(
      /* istanbul ignore next */ () => {
        this.resize();
      }
    );
    this.resizeObserver.observe(this.originElement);
 
    this.setVisible(options.visible);
  }
 
  public destroy(): void {
    if (this.visibilityListener != null) {
      document.removeEventListener("visibilitychange", this.visibilityListener);
    }
    if (this.newScanSettingsListener != null) {
      this.scanner.removeListener("newScanSettings", this.newScanSettingsListener);
    }
    if (this.videoResizeListener != null) {
      document.removeEventListener("resize", this.videoResizeListener);
    }
    if (this.licenseKeyFeaturesReadyListener != null) {
      this.scanner.removeListener("licenseKeyFeaturesReady", this.licenseKeyFeaturesReadyListener);
    }
    this.resizeObserver.disconnect();
    this.grandParentElement.remove();
    this.originElement.classList.remove(GUI.hiddenClassName);
  }
 
  public setCameraManager(cameraManager: CameraManager): void {
    this.cameraManager = cameraManager;
  }
 
  public pauseScanning(): void {
    this.scanningPaused = true;
    this.laserActiveImageElement.classList.add(GUI.hiddenOpacityClassName);
    this.laserPausedImageElement.classList.remove(GUI.hiddenOpacityClassName);
    this.viewfinderElement.classList.add(GUI.pausedClassName);
  }
 
  public resumeScanning(): void {
    this.scanningPaused = false;
    this.laserPausedImageElement.classList.add(GUI.hiddenOpacityClassName);
    this.laserActiveImageElement.classList.remove(GUI.hiddenOpacityClassName);
    this.viewfinderElement.classList.remove(GUI.pausedClassName);
  }
 
  public isVisible(): boolean {
    return this.visible;
  }
 
  public setVisible(visible: boolean): void {
    const browserName: string | undefined = BrowserHelper.userAgentInfo.getBrowser().name;
    if (browserName != null && browserName.includes("Safari") && this.visible === false && visible) {
      // Safari behaves weirdly when displaying the video element again after being hidden:
      // it undetectably reuses video frames "buffered" from the video just before it was hidden.
      // We do this to avoid reusing old data
      this.videoElement.pause();
      this.videoElement.currentTime = 0;
      this.videoElement.load();
      this.playVideo();
    }
 
    this.visible = visible;
 
    if (visible) {
      this.originElement.classList.remove(GUI.hiddenClassName);
      if (this.guiStyle === BarcodePicker.GuiStyle.LASER) {
        this.laserActiveImageElement.classList.remove(GUI.flashColorClassName);
      } else if (this.guiStyle === BarcodePicker.GuiStyle.VIEWFINDER) {
        this.viewfinderElement.classList.remove(GUI.flashWhiteClassName);
      }
    } else {
      this.originElement.classList.add(GUI.hiddenClassName);
    }
  }
 
  public isMirrorImageEnabled(): boolean {
    if (this.cameraManager?.selectedCamera != null && this.cameraManager?.activeCamera != null) {
      const mirrorImageOverride: boolean | undefined = this.mirrorImageOverrides.get(
        this.cameraManager.activeCamera.deviceId + this.cameraManager.activeCamera.label
      );
 
      return mirrorImageOverride ?? this.cameraManager.activeCamera.cameraType === Camera.Type.FRONT;
    } else {
      return false;
    }
  }
 
  public setMirrorImageEnabled(enabled: boolean, override: boolean): void {
    if (this.cameraManager?.selectedCamera != null) {
      if (enabled) {
        this.videoElement.classList.add(GUI.mirroredClassName);
      } else {
        this.videoElement.classList.remove(GUI.mirroredClassName);
      }
 
      if (override) {
        this.mirrorImageOverrides.set(
          this.cameraManager.selectedCamera.deviceId + this.cameraManager.selectedCamera.label,
          enabled
        );
      }
    }
  }
 
  public setGuiStyle(guiStyle: BarcodePicker.GuiStyle): void {
    if (this.singleImageModeEnabled) {
      return;
    }
 
    switch (guiStyle) {
      case BarcodePicker.GuiStyle.LASER:
        this.guiStyle = guiStyle;
        this.laserContainerElement.classList.remove(GUI.hiddenClassName);
        this.viewfinderElement.classList.add(GUI.hiddenClassName);
        break;
      case BarcodePicker.GuiStyle.VIEWFINDER:
        this.guiStyle = guiStyle;
        this.laserContainerElement.classList.add(GUI.hiddenClassName);
        this.viewfinderElement.classList.remove(GUI.hiddenClassName);
        break;
      case BarcodePicker.GuiStyle.NONE:
      default:
        this.guiStyle = BarcodePicker.GuiStyle.NONE;
        this.laserContainerElement.classList.add(GUI.hiddenClassName);
        this.viewfinderElement.classList.add(GUI.hiddenClassName);
        break;
    }
  }
 
  public setLaserArea(area?: SearchArea): void {
    this.customLaserArea = area;
    if (area == null) {
      area = this.scanner.getScanSettings().getSearchArea();
    }
    const borderPercentage: number = 0.025;
    const usablePercentage: number = 1 - borderPercentage * 2;
    this.laserContainerElement.style.left = `${(borderPercentage + area.x * usablePercentage) * 100}%`;
    this.laserContainerElement.style.width = `${area.width * usablePercentage * 100}%`;
    this.laserContainerElement.style.top = `${(borderPercentage + area.y * usablePercentage) * 100}%`;
    this.laserContainerElement.style.height = `${area.height * usablePercentage * 100}%`;
  }
 
  public setViewfinderArea(area?: SearchArea): void {
    this.customViewfinderArea = area;
    if (area == null) {
      area = this.scanner.getScanSettings().getSearchArea();
    }
    const borderPercentage: number = 0.025;
    const usablePercentage: number = 1 - borderPercentage * 2;
    this.viewfinderElement.style.left = `${(borderPercentage + area.x * usablePercentage) * 100}%`;
    this.viewfinderElement.style.width = `${area.width * usablePercentage * 100}%`;
    this.viewfinderElement.style.top = `${(borderPercentage + area.y * usablePercentage) * 100}%`;
    this.viewfinderElement.style.height = `${area.height * usablePercentage * 100}%`;
  }
 
  public setVideoFit(objectFit: BarcodePicker.ObjectFit): void {
    if (this.singleImageModeEnabled) {
      return;
    }
 
    this.videoFit = objectFit;
 
    if (objectFit === BarcodePicker.ObjectFit.COVER) {
      this.videoElement.style.objectFit = "cover";
      this.videoElement.dataset.objectFit = "cover"; // used by "objectFitPolyfill" library
    } else {
      this.videoElement.style.objectFit = "contain";
      this.videoElement.dataset.objectFit = "contain"; // used by "objectFitPolyfill" library
 
      this.scanner.applyScanSettings(
        this.scanner.getScanSettings().setBaseSearchArea({ x: 0, y: 0, width: 1.0, height: 1.0 })
      );
    }
 
    this.resize();
  }
 
  public reassignOriginElement(originElement: HTMLElement): void {
    if (!this.visible) {
      this.originElement.classList.remove(GUI.hiddenClassName);
      originElement.classList.add(GUI.hiddenClassName);
    }
 
    originElement.appendChild(this.grandParentElement);
    this.checkAndRecoverPlayback();
    this.resize();
    this.resizeObserver.disconnect();
    this.resizeObserver.observe(originElement);
 
    this.originElement = originElement;
  }
 
  public flashGUI(): void {
    if (this.guiStyle === BarcodePicker.GuiStyle.LASER) {
      this.flashLaser();
    } else if (this.guiStyle === BarcodePicker.GuiStyle.VIEWFINDER) {
      this.flashViewfinder();
    }
  }
 
  public getImageData(imageData?: Uint8Array): Uint8Array | undefined {
    if (this.singleImageModeEnabled && this.context2d != null) {
      return new Uint8Array(
        this.context2d.getImageData(0, 0, this.context2d.canvas.width, this.context2d.canvas.height).data.buffer
      );
    }
    // istanbul ignore else
    if (!this.singleImageModeEnabled) {
      if (this.contextWebGL != null) {
        // This could happen in unexpected situations and should be temporary
        if (
          this.videoElement.readyState !== 4 ||
          this.contextWebGL.canvas.width <= 2 ||
          this.contextWebGL.canvas.height <= 2
        ) {
          return undefined;
        }
 
        const imageDataLength: number =
          this.contextWebGL.drawingBufferWidth * this.contextWebGL.drawingBufferHeight * 4;
        Eif (imageData == null || imageData.length !== imageDataLength) {
          imageData = new Uint8Array(imageDataLength);
        }
        this.contextWebGL.texImage2D(
          this.contextWebGL.TEXTURE_2D,
          0,
          this.contextWebGL.RGBA,
          this.contextWebGL.RGBA,
          this.contextWebGL.UNSIGNED_BYTE,
          this.videoElement
        );
        this.contextWebGL.readPixels(
          0,
          0,
          this.contextWebGL.drawingBufferWidth,
          this.contextWebGL.drawingBufferHeight,
          this.contextWebGL.RGBA,
          this.contextWebGL.UNSIGNED_BYTE,
          imageData
        );
 
        return imageData;
      }
      // istanbul ignore else
      if (this.context2d != null) {
        // This could happen in unexpected situations and should be temporary
        if (
          this.videoElement.readyState !== 4 ||
          this.context2d.canvas.width <= 2 ||
          this.context2d.canvas.height <= 2
        ) {
          return undefined;
        }
 
        this.context2d.drawImage(this.videoElement, 0, 0);
 
        return new Uint8Array(
          this.context2d.getImageData(0, 0, this.context2d.canvas.width, this.context2d.canvas.height).data.buffer
        );
      }
    }
 
    // istanbul ignore next
    return undefined;
  }
 
  public getVideoCurrentTime(): number {
    return this.videoElement.currentTime;
  }
 
  public setCameraSwitcherVisible(visible: boolean): void {
    if (visible) {
      this.cameraSwitcherElement.classList.remove(GUI.hiddenClassName);
    } else {
      this.cameraSwitcherElement.classList.add(GUI.hiddenClassName);
    }
  }
 
  public setTorchTogglerVisible(visible: boolean): void {
    if (visible) {
      this.torchTogglerElement.classList.remove(GUI.hiddenClassName);
    } else {
      this.torchTogglerElement.classList.add(GUI.hiddenClassName);
    }
  }
 
  public playVideo(): void {
    const playPromise: Promise<void> | undefined = this.videoElement.play();
    playPromise?.catch(
      /* istanbul ignore next */ () => {
        // Can sometimes cause an incorrect rejection (all is good, ignore).
      }
    );
  }
 
  private setCameraUploadGuiBusyScanning(busyScanning: boolean): void {
    if (busyScanning) {
      this.cameraUploadProgressElement.classList.remove(GUI.flashInsetClassName);
      this.cameraUploadElement.classList.add(GUI.opacityPulseClassName);
    } else {
      this.cameraUploadProgressElement.classList.add(GUI.flashInsetClassName);
      this.cameraUploadElement.classList.remove(GUI.opacityPulseClassName);
    }
  }
 
  private setupWebGL(contextWebGL: WebGLRenderingContext): void {
    const texture: WebGLTexture = <WebGLTexture>contextWebGL.createTexture();
    contextWebGL.bindTexture(contextWebGL.TEXTURE_2D, texture);
    const frameBuffer: WebGLFramebuffer = <WebGLFramebuffer>contextWebGL.createFramebuffer();
    contextWebGL.bindFramebuffer(contextWebGL.FRAMEBUFFER, frameBuffer);
    contextWebGL.framebufferTexture2D(
      contextWebGL.FRAMEBUFFER,
      contextWebGL.COLOR_ATTACHMENT0,
      contextWebGL.TEXTURE_2D,
      texture,
      0
    );
    contextWebGL.texParameteri(contextWebGL.TEXTURE_2D, contextWebGL.TEXTURE_WRAP_S, contextWebGL.CLAMP_TO_EDGE);
    contextWebGL.texParameteri(contextWebGL.TEXTURE_2D, contextWebGL.TEXTURE_WRAP_T, contextWebGL.CLAMP_TO_EDGE);
    contextWebGL.texParameteri(contextWebGL.TEXTURE_2D, contextWebGL.TEXTURE_MIN_FILTER, contextWebGL.NEAREST);
    contextWebGL.texParameteri(contextWebGL.TEXTURE_2D, contextWebGL.TEXTURE_MAG_FILTER, contextWebGL.NEAREST);
  }
 
  private setupVideoElement(): void {
    this.videoElement.setAttribute("autoplay", "autoplay");
    this.videoElement.setAttribute("playsinline", "true");
    this.videoElement.setAttribute("muted", "muted");
    this.videoElement.className = GUI.videoElementClassName;
    this.parentElement.appendChild(this.videoElement);
  }
 
  private setupCameraUploadGuiAssets(cameraType: Camera.Type): void {
    const deviceType: string | undefined = BrowserHelper.userAgentInfo.getDevice().type;
    const defaultSettings: SingleImageModePlatformSettings =
      deviceType === "mobile" || deviceType === "tablet"
        ? SingleImageModeSettings.defaultMobile
        : SingleImageModeSettings.defaultDesktop;
 
    this.cameraUploadElement.className = GUI.cameraUploadElementClassName;
    Object.assign(
      this.cameraUploadElement.style,
      defaultSettings.containerStyle,
      this.singleImageModeSettings.containerStyle
    );
    this.parentElement.appendChild(this.cameraUploadElement);
 
    const informationElement: HTMLElement =
      this.singleImageModeSettings.informationElement ?? <HTMLElement>defaultSettings.informationElement;
    Object.assign(
      informationElement.style,
      defaultSettings.informationStyle,
      this.singleImageModeSettings.informationStyle
    );
    this.cameraUploadElement.appendChild(informationElement);
 
    this.cameraUploadInputElement.type = "file";
    this.cameraUploadInputElement.accept = "image/*";
    this.cameraUploadInputElement.setAttribute("capture", cameraType === Camera.Type.FRONT ? "user" : "environment");
    this.cameraUploadInputElement.addEventListener("change", this.cameraUploadFile.bind(this));
    const cameraUploadInputCheckFunction: EventListenerOrEventListenerObject = (event: Event): void => {
      // istanbul ignore next
      if (this.scanningPaused || this.cameraUploadInProgress) {
        event.preventDefault();
      }
    };
    this.cameraUploadInputElement.addEventListener("click", cameraUploadInputCheckFunction);
    this.cameraUploadInputElement.addEventListener("keydown", cameraUploadInputCheckFunction);
 
    this.cameraUploadLabelElement.appendChild(this.cameraUploadInputElement);
 
    const cameraUploadButtonIconElement: HTMLElement | SVGElement =
      this.singleImageModeSettings.buttonElement ?? <SVGElement>defaultSettings.buttonElement;
    [this.cameraUploadProgressElement.style, cameraUploadButtonIconElement.style].forEach((style) => {
      Object.assign(style, defaultSettings.buttonStyle, this.singleImageModeSettings.buttonStyle);
    });
    cameraUploadButtonIconElement.style.maxWidth = "100px";
    cameraUploadButtonIconElement.style.maxHeight = "100px";
    this.cameraUploadLabelElement.appendChild(cameraUploadButtonIconElement);
 
    this.cameraUploadProgressElement.classList.add("radial-progress");
    this.cameraUploadLabelElement.appendChild(this.cameraUploadProgressElement);
 
    this.cameraUploadElement.appendChild(this.cameraUploadLabelElement);
  }
 
  private setupFullGuiAssets(): void {
    this.laserActiveImageElement.src = laserActiveImage;
    this.laserContainerElement.appendChild(this.laserActiveImageElement);
 
    this.laserPausedImageElement.src = laserPausedImage;
    this.laserContainerElement.appendChild(this.laserPausedImageElement);
 
    this.laserContainerElement.className = GUI.laserContainerElementClassName;
    this.parentElement.appendChild(this.laserContainerElement);
 
    this.viewfinderElement.className = GUI.viewfinderElementClassName;
    this.parentElement.appendChild(this.viewfinderElement);
 
    // Show inactive GUI, as for now the scanner isn't ready yet
    this.laserActiveImageElement.classList.add(GUI.hiddenOpacityClassName);
    this.laserPausedImageElement.classList.remove(GUI.hiddenOpacityClassName);
    this.viewfinderElement.classList.add(GUI.pausedClassName);
  }
 
  private flashLaser(): void {
    this.laserActiveImageElement.classList.remove(GUI.flashColorClassName);
    // tslint:disable-next-line:no-unused-expression
    this.laserActiveImageElement.offsetHeight; // NOSONAR // Trigger reflow to restart animation
    this.laserActiveImageElement.classList.add(GUI.flashColorClassName);
  }
 
  private flashViewfinder(): void {
    this.viewfinderElement.classList.remove(GUI.flashWhiteClassName);
    // tslint:disable-next-line:no-unused-expression
    this.viewfinderElement.offsetHeight; // NOSONAR // Trigger reflow to restart animation
    this.viewfinderElement.classList.add(GUI.flashWhiteClassName);
  }
 
  private resize(): void {
    this.parentElement.style.maxWidth = "";
    this.parentElement.style.maxHeight = "";
 
    const width: number = this.originElement.clientWidth;
    const height: number = this.originElement.clientHeight;
 
    if (width === 0 || height === 0) {
      return;
    }
 
    if (this.singleImageModeEnabled) {
      this.resizeCameraUpload(width, height);
    } else {
      this.resizeVideo(width, height);
    }
  }
 
  private resizeCameraUpload(width: number, height: number): void {
    this.cameraUploadLabelElement.style.transform = `scale(${Math.min(1, width / 300, height / 300)})`;
  }
 
  private resizeVideo(width: number, height: number): void {
    Iif (this.videoElement.videoWidth <= 2 || this.videoElement.videoHeight <= 2) {
      return;
    }
 
    const videoRatio: number = this.videoElement.videoWidth / this.videoElement.videoHeight;
 
    if (this.videoFit === BarcodePicker.ObjectFit.COVER) {
      let widthPercentage: number = 1;
      let heightPercentage: number = 1;
 
      if (videoRatio < width / height) {
        heightPercentage = Math.min(1, height / (width / videoRatio));
      } else {
        widthPercentage = Math.min(1, width / (height * videoRatio));
      }
 
      this.scanner.applyScanSettings(
        this.scanner.getScanSettings().setBaseSearchArea({
          x: (1 - widthPercentage) / 2,
          y: (1 - heightPercentage) / 2,
          width: widthPercentage,
          height: heightPercentage,
        })
      );
 
      return;
    }
 
    if (videoRatio > width / height) {
      height = width / videoRatio;
    } else {
      width = height * videoRatio;
    }
 
    this.parentElement.style.maxWidth = `${Math.ceil(width)}px`;
    this.parentElement.style.maxHeight = `${Math.ceil(height)}px`;
 
    window.objectFitPolyfill(this.videoElement);
  }
 
  private checkAndRecoverPlayback(): void {
    Iif (this.cameraManager?.activeCamera != null && this.videoElement?.srcObject != null) {
      if (!(<MediaStream>this.videoElement.srcObject).active) {
        this.cameraManager.reinitializeCamera().catch(
          /* istanbul ignore next */ () => {
            // Ignored
          }
        );
      } else {
        this.playVideo();
      }
    }
  }
 
  private updateCameraUploadProgress(progressPercentageValue: string): void {
    this.cameraUploadProgressElement.setAttribute("data-progress", progressPercentageValue);
  }
 
  private async cameraUploadImageLoad(image: HTMLImageElement): Promise<void> {
    this.updateCameraUploadProgress("100");
 
    let resizedImageWidth: number;
    let resizedImageHeight: number;
    const resizedImageSizeLimit: number = 1440;
    if (image.naturalWidth <= resizedImageSizeLimit && image.naturalHeight <= resizedImageSizeLimit) {
      resizedImageWidth = image.naturalWidth;
      resizedImageHeight = image.naturalHeight;
    } else {
      if (image.naturalWidth > image.naturalHeight) {
        resizedImageWidth = resizedImageSizeLimit;
        resizedImageHeight = Math.round((image.naturalHeight / image.naturalWidth) * resizedImageSizeLimit);
      } else {
        resizedImageWidth = Math.round((image.naturalWidth / image.naturalHeight) * resizedImageSizeLimit);
        resizedImageHeight = resizedImageSizeLimit;
      }
    }
 
    await this.cameraUploadFileProcess(image, resizedImageWidth, resizedImageHeight);
  }
 
  private async cameraUploadFileProcess(image: HTMLImageElement, width: number, height: number): Promise<void> {
    // istanbul ignore else
    if (this.context2d != null) {
      this.context2d.canvas.width = width;
      this.context2d.canvas.height = height;
 
      this.context2d.drawImage(image, 0, 0, width, height);
      this.scanner.applyImageSettings({
        width,
        height,
        format: ImageSettings.Format.RGBA_8U,
      });
    }
 
    this.setCameraUploadGuiBusyScanning(true);
    await this.cameraUploadCallback();
    this.setCameraUploadGuiBusyScanning(false);
    this.cameraUploadInProgress = false;
  }
 
  private cameraUploadFile(): void {
    const files: FileList | null = this.cameraUploadInputElement.files;
    if (files != null && files.length !== 0) {
      this.cameraUploadInProgress = true;
      const image: HTMLImageElement = new Image();
      const fileReader: FileReader = new FileReader();
      fileReader.onload = () => {
        this.cameraUploadInputElement.value = "";
        // istanbul ignore else
        if (fileReader.result != null) {
          image.onload = this.cameraUploadImageLoad.bind(this, image);
          image.onprogress = (event2) => {
            // istanbul ignore else
            Iif (event2.lengthComputable) {
              const progress: number = Math.round((event2.loaded / event2.total) * 20) * 5;
              // istanbul ignore else
              Iif (progress <= 100) {
                this.updateCameraUploadProgress(progress.toString());
              }
            }
          };
          image.onerror = () => {
            this.cameraUploadInProgress = false;
          };
          image.src = <string>fileReader.result;
        }
      };
      fileReader.onerror = () => {
        this.cameraUploadInProgress = false;
      };
      this.updateCameraUploadProgress("0");
      fileReader.readAsDataURL(files[0]);
    }
  }
 
  private async cameraSwitcherListener(event: Event): Promise<void> {
    if (I!this.cameraSwitchInProgress && this.cameraManager != null) {
      const cameraManager: CameraManager = this.cameraManager;
      event.preventDefault();
      try {
        const cameras: Camera[] = await CameraAccess.getCameras();
        if (cameras.length <= 1) {
          this.setCameraSwitcherVisible(false);
 
          return;
        }
        this.cameraSwitchInProgress = true;
        const currentCameraIndex: number = cameras.findIndex((camera) => {
          return camera.deviceId === cameraManager.activeCamera?.deviceId ?? camera.deviceId;
        });
        let newCameraIndex: number = (currentCameraIndex + 1) % cameras.length;
        while (newCameraIndex !== currentCameraIndex) {
          try {
            await cameraManager.initializeCameraWithSettings(
              cameras[newCameraIndex],
              cameraManager.activeCameraSettings
            );
          } catch (error) {
            console.warn("Couldn't access camera", cameras[newCameraIndex], error);
            newCameraIndex = (newCameraIndex + 1) % cameras.length;
            if (newCameraIndex === currentCameraIndex) {
              this.setCameraSwitcherVisible(false);
              await cameraManager.initializeCameraWithSettings(
                cameras[newCameraIndex],
                cameraManager.activeCameraSettings
              );
            }
            continue;
          }
          break;
        }
        this.cameraSwitchInProgress = false;
      } catch (error) {
        console.error(error);
        this.cameraSwitchInProgress = false;
      }
    }
  }
 
  private setupCameraSwitcher(): void {
    this.cameraSwitcherElement.src = switchCameraImage;
    this.cameraSwitcherElement.className = GUI.cameraSwitcherElementClassName;
    this.cameraSwitcherElement.classList.add(GUI.hiddenClassName);
    this.parentElement.appendChild(this.cameraSwitcherElement);
    ["touchstart", "mousedown"].forEach((eventName) => {
      this.cameraSwitcherElement.addEventListener(eventName, this.cameraSwitcherListener.bind(this));
    });
  }
 
  private setupTorchToggler(): void {
    this.torchTogglerElement.src = toggleTorchImage;
    this.torchTogglerElement.className = GUI.torchTogglerElementClassName;
    this.torchTogglerElement.classList.add(GUI.hiddenClassName);
    this.parentElement.appendChild(this.torchTogglerElement);
    ["touchstart", "mousedown"].forEach((eventName) => {
      this.torchTogglerElement.addEventListener(eventName, (event) => {
        if (this.cameraManager != null) {
          event.preventDefault();
          this.cameraManager.toggleTorch().catch(
            /* istanbul ignore next */ () => {
              // Ignored
            }
          );
        }
      });
    });
  }
 
  private showScanditLogo(hideLogo: boolean, licenseKeyFeatures?: { hiddenScanditLogoAllowed?: boolean }): void {
    Iif (hideLogo && licenseKeyFeatures?.hiddenScanditLogoAllowed === true) {
      return;
    }
 
    const scanditLogoImageElement: HTMLImageElement = document.createElement("img");
    scanditLogoImageElement.src = scanditLogoImage;
    scanditLogoImageElement.className = GUI.scanditLogoImageElementClassName;
    this.parentElement.appendChild(scanditLogoImageElement);
  }
 
  private handleNewScanSettings(): void {
    if (this.customLaserArea == null) {
      this.setLaserArea();
    }
    if (this.customViewfinderArea == null) {
      this.setViewfinderArea();
    }
  }
 
  private handleVideoResize(): void {
    this.resize();
 
    if (this.contextWebGL != null) {
      if (
        this.contextWebGL.canvas.width === this.videoElement.videoWidth &&
        this.contextWebGL.canvas.height === this.videoElement.videoHeight
      ) {
        return;
      }
 
      this.contextWebGL.canvas.width = this.videoElement.videoWidth;
      this.contextWebGL.canvas.height = this.videoElement.videoHeight;
      this.contextWebGL.viewport(0, 0, this.contextWebGL.drawingBufferWidth, this.contextWebGL.drawingBufferHeight);
 
      this.scanner.applyImageSettings({
        width: this.contextWebGL.drawingBufferWidth,
        height: this.contextWebGL.drawingBufferHeight,
        format: ImageSettings.Format.RGBA_8U,
      });
    } else if (this.context2d != null) {
      if (
        this.context2d.canvas.width === this.videoElement.videoWidth &&
        this.context2d.canvas.height === this.videoElement.videoHeight
      ) {
        return;
      }
 
      this.context2d.canvas.width = this.videoElement.videoWidth;
      this.context2d.canvas.height = this.videoElement.videoHeight;
 
      this.scanner.applyImageSettings({
        width: this.videoElement.videoWidth,
        height: this.videoElement.videoHeight,
        format: ImageSettings.Format.RGBA_8U,
      });
    }
  }
}