diff --git a/Api Reference.url b/Api Reference.url index d2e66f2..86d6db6 100644 --- a/Api Reference.url +++ b/Api Reference.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.6.10 \ No newline at end of file +URL=https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.6.11 \ No newline at end of file diff --git a/README.md b/README.md index d320433..6742c7c 100644 --- a/README.md +++ b/README.md @@ -17,46 +17,35 @@ In this guide, you will learn step by step on how to integrate the DBR-JS SDK in Table of Contents -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a public CDN](#use-a-public-cdn) - - [Host the SDK yourself](#host-the-sdk-yourself) - - [Configure the SDK](#configure-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files](#specify-the-location-of-the-engine-files) - - [Interact with the SDK](#interact-with-the-sdk) - - [Create a `BarcodeScanner` object](#create-a-barcodescanner-object) - - [Customize the `BarcodeScanner` Settings (optional)](#customize-the-barcodescanner-settings-optional) - - [Customize the UI (optional)](#customize-the-ui-optional) - - [Modify the file `dist/dbr.ui.html` directly](#modify-the-file-distdbruihtml-directly) - - [Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI](#copy-the-file-distdbruihtml-to-your-application-modify-it-and-use-the-the-api-defaultuielementurl-to-set-it-as-the-default-ui) - - [Append the default UI element to your page, customize it before showing it](#append-the-default-ui-element-to-your-page-customize-it-before-showing-it) - - [Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)`](#build-the-ui-element-from-scratch-and-connect-it-to-the-sdk-with-the-api-setuielementhtmlelement) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) +- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) + - [Understand the code](#understand-the-code) + - [Run the example](#run-the-example) +- [Building your own page](#building-your-own-page) + - [Include the SDK](#include-the-sdk) + - [Configure the SDK](#configure-the-sdk) + - [Interact with the SDK](#interact-with-the-sdk) + - [Customize the UI (optional)](#customize-the-ui-optional) +- [API Documentation](#api-documentation) +- [System Requirements](#system-requirements) +- [How to Upgrade](#how-to-upgrade) +- [Release Notes](#release-notes) +- [Next Steps](#next-steps) **Popular Examples** -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.10&utm_source=github) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.10&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.10&utm_source=github) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.10&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.10&utm_source=github) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.10&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.10&utm_source=github) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.10&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.10&utm_source=github) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.10&utm_source=github&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.10&utm_source=github) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.10&utm_source=github) +- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.11&utm_source=github) +- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.11&utm_source=github) +- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.11&utm_source=github) +- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.11&utm_source=github) +- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.11&utm_source=github) +- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.11&utm_source=github&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.11&utm_source=github) +- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.11&utm_source=github) +- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/5.others/debug) You can also: -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.10&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.10&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.10/) +- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) +- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.11&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.11/) ## Hello World - Simplest Implementation @@ -76,9 +65,9 @@ The complete code of the "Hello World" example is shown below - + + ``` - UNPKG ```html - + ``` #### Host the SDK yourself @@ -182,7 +171,7 @@ Options to download the SDK: - From the website - Download the JavaScript Package + Download the JavaScript Package - yarn @@ -199,7 +188,7 @@ Options to download the SDK: Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: ```html - + ``` or @@ -241,7 +230,7 @@ The SDK requires a license to work, use the API `license` to specify a license k Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; ``` -To test the SDK, you can request a 30-day trial license via the [customer portal](https://www.dynamsoft.com/customer/license/trialLicense?ver=9.6.10&utm_source=github&product=dbr&package=js). +To test the SDK, you can request a 30-day trial license via the [customer portal](https://www.dynamsoft.com/customer/license/trialLicense?ver=9.6.11&utm_source=github&product=dbr&package=js). > If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. @@ -253,7 +242,7 @@ The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*. ```javascript //The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.10/dist/"; +Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.11/dist/"; ``` ### Interact with the SDK @@ -348,9 +337,9 @@ As you can see from the above code snippets, there are three types of configurat Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.10&utm_source=github). + See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.11&utm_source=github). -> Find the full list of the runtime settings here. +> Find the full list of the runtime settings here. ### Customize the UI (optional) @@ -448,7 +437,7 @@ The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr. ## API Documentation You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.10](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.10). +[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.11](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.11). ## System Requirements @@ -469,7 +458,7 @@ DBR requires the following features to work: - `MediaDevices`/`getUserMedia` - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.10&utm_source=github#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. + This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.11&utm_source=github#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - `getSettings` @@ -494,7 +483,7 @@ Apart from the browsers, the operating systems may impose some limitations of th ## How to Upgrade -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.10&utm_source=github). +If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.11&utm_source=github). ## Release Notes diff --git a/dist/dbr-9.6.10.browser.worker.js b/dist/dbr-9.6.11.browser.worker.js similarity index 51% rename from dist/dbr-9.6.10.browser.worker.js rename to dist/dbr-9.6.11.browser.worker.js index 2c9b905..dfacea2 100644 --- a/dist/dbr-9.6.10.browser.worker.js +++ b/dist/dbr-9.6.11.browser.worker.js @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2023, Dynamsoft Corporation * @author Dynamsoft - * @version 9.6.10 (js 20230213) + * @version 9.6.11 (js 20230310) * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ */ -!function(){"use strict";const e="undefined"==typeof self,t=e?{}:self,r=e=>e&&"object"==typeof e&&"function"==typeof e.then;class n extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(r(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,r(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const r=await t;e===this._task&&this.resolve(r)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}let o,a,s,i,c;if("undefined"!=typeof navigator&&(o=navigator,a=o.userAgent,s=o.platform,i=o.mediaDevices),!e){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:o.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:s,search:"Win"},Mac:{str:s},Linux:{str:s}};let r="unknownBrowser",n=0,i="unknownOS";for(let t in e){const o=e[t]||{};let s=o.str||a,i=o.search||t,c=o.verStr||a,d=o.verSearch||t;if(d instanceof Array||(d=[d]),-1!=s.indexOf(i)){r=t;for(let e of d){let t=c.indexOf(e);if(-1!=t){n=parseFloat(c.substring(t+e.length+1));break}}break}}for(let e in t){const r=t[e]||{};let n=r.str||a,o=r.search||e;if(-1!=n.indexOf(o)){i=e;break}}"Linux"==i&&-1!=a.indexOf("Windows NT")&&(i="HarmonyOS"),c={browser:r,version:n,OS:i}}e&&(c={browser:"ssr",version:0,OS:"ssr"}),"undefined"!=typeof WebAssembly&&a&&(!/Safari/.test(a)||/Chrome/.test(a)||/\(.+\s11_2_([2-6]).*\)/.test(a)),i&&i.getUserMedia;const d="Chrome"===c.browser&&c.version>66||"Safari"===c.browser&&c.version>13||"OPR"===c.browser&&c.version>43||"Edge"===c.browser&&c.version>15;var u=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(e){return}}();function l(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(o){if("TypeError"!==o.name)throw o;for(var r=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),n=0;n=43)}})).catch((function(){return!1}))}(e).then((function(e){return p=e,p}))}function k(e){var t=b[e.name],r={};r.promise=new Promise((function(e,t){r.resolve=e,r.reject=t})),t.deferredOperations.push(r),t.dbReady?t.dbReady=t.dbReady.then((function(){return r.promise})):t.dbReady=r.promise}function I(e){var t=b[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function M(e,t){var r=b[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function x(e,t){return new Promise((function(r,n){if(b[e.name]=b[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);k(e),e.db.close()}var o=[e.name];t&&o.push(e.version);var a=u.open.apply(u,o);t&&(a.onupgradeneeded=function(t){var r=a.result;try{r.createObjectStore(e.storeName),t.oldVersion<=1&&r.createObjectStore(y)}catch(r){if("ConstraintError"!==r.name)throw r;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),a.onerror=function(e){e.preventDefault(),n(a.error)},a.onsuccess=function(){var t=a.result;t.onversionchange=function(e){e.target.close()},r(t),I(e)}}))}function C(e){return x(e,!1)}function P(e){return x(e,!0)}function D(e,t){if(!e.db)return!0;var r=!e.db.objectStoreNames.contains(e.storeName),n=e.versione.db.version;if(n&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),o||r){if(r){var a=e.db.version+1;a>e.version&&(e.version=a)}return!0}return!1}function N(e){var t=function(e){for(var t=e.length,r=new ArrayBuffer(t),n=new Uint8Array(r),o=0;o0&&(!e.db||"InvalidStateError"===o.name||"NotFoundError"===o.name))return Promise.resolve().then((()=>{if(!e.db||"NotFoundError"===o.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),P(e)})).then((()=>function(e){k(e);for(var t=b[e.name],r=t.forages,n=0;n(e.db=t,D(e)?P(e):t))).then((n=>{e.db=t.db=n;for(var o=0;o{throw M(e,t),t}))}(e).then((function(){T(e,t,r,n-1)})))).catch(r);r(o)}}var E={_driver:"asyncStorage",_initStorage:function(e){var t=this,r={db:null};if(e)for(var n in e)r[n]=e[n];var o=b[r.name];o||(o={forages:[],db:null,dbReady:null,deferredOperations:[]},b[r.name]=o),o.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=R);var a=[];function s(){return Promise.resolve()}for(var i=0;i{const r=b[e.name],n=r.forages;r.db=t;for(var o=0;o{if(!t.objectStoreNames.contains(e.storeName))return;const r=t.version+1;k(e);const n=b[e.name],o=n.forages;t.close();for(let e=0;e{const o=u.open(e.name,r);o.onerror=e=>{o.result.close(),n(e)},o.onupgradeneeded=()=>{o.result.deleteObjectStore(e.storeName)},o.onsuccess=()=>{const e=o.result;e.close(),t(e)}}));return a.then((e=>{n.db=e;for(let t=0;t{throw(M(e,t)||Promise.resolve()).catch((()=>{})),t}))})):t.then((t=>{k(e);const r=b[e.name],n=r.forages;t.close();for(var o=0;o{var n=u.deleteDatabase(e.name);n.onerror=()=>{const e=n.result;e&&e.close(),r(n.error)},n.onblocked=()=>{console.warn('dropInstance blocked for database "'+e.name+'" until all open connections are closed')},n.onsuccess=()=>{const e=n.result;e&&e.close(),t(e)}}));return a.then((e=>{r.db=e;for(var t=0;t{throw(M(e,t)||Promise.resolve()).catch((()=>{})),t}))}))}else n=Promise.reject("Invalid arguments");return f(n,t),n}};const O=new Map;function B(e,t){let r=e.name+"/";return e.storeName!==t.storeName&&(r+=e.storeName+"/"),r}var F={_driver:"tempStorageWrapper",_initStorage:async function(e){const t={};if(e)for(let r in e)t[r]=e[r];const r=t.keyPrefix=B(e,this._defaultConfig);this._dbInfo=t,O.has(r)||O.set(r,new Map)},getItem:function(e,t){e=h(e);const r=this.ready().then((()=>O.get(this._dbInfo.keyPrefix).get(e)));return f(r,t),r},setItem:function(e,t,r){e=h(e);const n=this.ready().then((()=>(void 0===t&&(t=null),O.get(this._dbInfo.keyPrefix).set(e,t),t)));return f(n,r),n},removeItem:function(e,t){e=h(e);const r=this.ready().then((()=>{O.get(this._dbInfo.keyPrefix).delete(e)}));return f(r,t),r},clear:function(e){const t=this.ready().then((()=>{const e=this._dbInfo.keyPrefix;O.has(e)&&O.delete(e)}));return f(t,e),t},length:function(e){const t=this.ready().then((()=>O.get(this._dbInfo.keyPrefix).size));return f(t,e),t},keys:function(e){const t=this.ready().then((()=>[...O.get(this._dbInfo.keyPrefix).keys()]));return f(t,e),t},dropInstance:function(e,t){if(t=g.apply(this,arguments),!(e="function"!=typeof e&&e||{}).name){const t=this.config();e.name=e.name||t.name,e.storeName=e.storeName||t.storeName}let r;return r=e.name?new Promise((t=>{e.storeName?t(B(e,this._defaultConfig)):t(`${e.name}/`)})).then((e=>{O.delete(e)})):Promise.reject("Invalid arguments"),f(r,t),r}};const A=(e,t)=>{const r=e.length;let n=0;for(;n{}))}config(e){if("object"==typeof e){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(let t in e){if("storeName"===t&&(e[t]=e[t].replace(/\W/g,"_")),"version"===t&&"number"!=typeof e[t])return new Error("Database version must be a number.");this._config[t]=e[t]}return!("driver"in e)||!e.driver||this.setDriver(this._config.driver)}return"string"==typeof e?this._config[e]:this._config}defineDriver(e,t,r){const n=new Promise((function(t,r){try{const n=e._driver,o=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!e._driver)return void r(o);const a=L.concat("_initStorage");for(let t=0,n=a.length;t(null===t._ready&&(t._ready=t._initDriver()),t._ready)));return m(r,e,e),r}setDriver(e,t,r){const n=this;j(e)||(e=[e]);const o=this._getSupportedDrivers(e);function a(){n._config.driver=n.driver()}function s(e){return n._extend(e),a(),n._ready=n._initStorage(n._config),n._ready}const i=null!==this._driverSet?this._driverSet.catch((()=>Promise.resolve())):Promise.resolve();return this._driverSet=i.then((()=>{const e=o[0];return n._dbInfo=null,n._ready=null,n.getDriver(e).then((e=>{n._driver=e._driver,a(),n._wrapLibraryMethodsWithReady(),n._initDriver=function(e){return function(){let t=0;return function r(){for(;t{a();const e=new Error("No available storage method found.");return n._driverSet=Promise.reject(e),n._driverSet})),m(this._driverSet,t,r),this._driverSet}supports(e){return!!J[e]}_extend(e){K(this,e)}_getSupportedDrivers(e){const t=[];for(let r=0,n=e.length;r{let r,o,a,s,i,c,u,l,f,m=t.btoa,h=t.atob,g=e.bd,y=e.dm;const p=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"];let b,v,w,S,_,k,I,M,x,C,P,D,N,R,T=p,E=!1,O=Promise.resolve(),B=e.log&&((...t)=>{try{e.log.apply(null,t)}catch(e){setTimeout((()=>{throw e}),0)}})||(()=>{}),F=g&&B||(()=>{}),A=e=>e.join(""),j={a:[80,88,27,82,145,164,199,211],b:[187,87,89,128,150,44,190,213],c:[89,51,74,53,99,72,82,118],d:[99,181,118,158,215,103,76,117],e:[99,51,86,105,100,71,120,108],f:[97,87,49,119,98,51,74,48,83,50,86,53],g:[81,85,86,84,76,85,100,68,84,81,32,32],h:[90,87,53,106,99,110,108,119,100,65,32,32],i:[90,71,86,106,99,110,108,119,100,65,32,32],j:[97,88,89,32],k:[29,83,122,137,5,180,157,114],l:[100,71,70,110,84,71,86,117,90,51,82,111]},U=()=>t[A(j.c)][A(j.e)][A(j.f)]("raw",new Uint8Array(j.a.concat(j.b,j.d,j.k)),A(j.g),!0,[A(j.h),A(j.i)]),J=e=>h(h(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),W=e=>m(String.fromCharCode(97+25*Math.random())+m(e)).replace(/\+/g,"\n").replace(/=/g," "),z=()=>{if(t.crypto){let e=new Uint8Array(36);t.crypto.getRandomValues(e);let r="";for(let t=0;t<36;++t){let n=e[t]%36;r+=n<10?n:String.fromCharCode(n+87)}return r}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))};const H="Failed to connect to the Dynamsoft License Server: ",L={dlsErrorAndCacheExpire:H+"The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",publicTrialNetworkTimeout:H+"network timed out. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",networkTimeout:H+"network timed out. Check your Internet connection or contact the site administrator for more information.",publicTrialFailConnect:H+"network connection error. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",failConnect:H+"network connection error. Check your Internet connection or contact the site administrator for more information.",checkLocalTime:"Your system date and time appear to have been changed, causing the license to fail. Please correct the system data and time and try again.",idbTimeout:"Failed to open indexedDB: Timeout."};let $,V,K,Z,X=async()=>{if($)return $;$=new n,await(async()=>{k||(k=G)})(),await Promise.race([(async()=>{let e=await k.createInstance({name:"dynamjssdkhello"});await e.setItem("dynamjssdkhello","available")})(),new Promise(((e,t)=>{setTimeout((()=>t(new Error(L.idbTimeout))),5e3)}))]),M=await k.createInstance({name:"dynamdlsinfo"}),x=m(m("v2")+String.fromCharCode(y.charCodeAt(y.length/2)+1)+m(y));try{let e=await M.getItem(x);e&&([u,S]=JSON.parse(await J(e)))}catch(e){}try{null==u&&(u=z(),M.setItem(x,await W(JSON.stringify([u,null]))))}catch(e){}$.resolve()},Y=async()=>{C=m(String.fromCharCode(s.charCodeAt(0)+10)+m(r)+m(s)+a+m(""+c)),I=await k.createInstance({name:"dynamdlsuns"+m(m("v2"))+m(String.fromCharCode(s.charCodeAt(0)+10)+m(r)+m(s)+a+m(""+c))});try{i=await M.getItem(C)}catch(e){}A=e=>h(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="))},q=async e=>{if(K=Date.now(),V)return V;V=new n;try{let t={pd:r,vm:a,v:o,dt:c||"browser",ed:"javascript",cu:u,ad:y,os:l,fn:f};w&&(t.rmk=w),s&&(t=-1!=s.indexOf("-")?{...t,hs:s}:{...t,og:s});let n={};if(S){let e=await M.getItem(x);e&&([u,S]=JSON.parse(await J(e))),n["lts-time"]=S}v&&(t.sp=v);let d=await Promise.race([(async()=>{let r,o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");S&&(M.setItem(x,await W(JSON.stringify([u,o]))),S=o);let a,s="auth/?ext="+encodeURIComponent(m(JSON.stringify(t))),c=!1,d=!1,l=async e=>{if(e&&!e.ok)try{let t=await e.text();if(t){let e=JSON.parse(t);e.errorCode&&(a=e,e.errorCode>100&&e.errorCode<200&&(i=null,c=!0,d=!0))}}catch(e){}};try{r=await Promise.race([fetch(T[0]+s,{headers:n,cache:e?"reload":"default",mode:"cors"}),new Promise(((e,t)=>setTimeout(t,1e4)))]),await l(r)}catch(e){}if(!(i||r&&r.ok||c))try{r=await Promise.race([fetch(T[1]+s,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await l(r)}catch(e){}if(!(i||r&&r.ok||c))try{r=await Promise.race([fetch(T[0]+s,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await l(r)}catch(e){}a&&151==a.errorCode&&(M.removeItem(x),M.removeItem(C),u=z(),t.cu=u,S=void 0,s="auth/?ext="+encodeURIComponent(m(JSON.stringify(t))),r=await Promise.race([fetch(T[0]+s,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await l(r));(()=>{if(!r||!r.ok){let e;d&&M.setItem(C,""),a?111==a.errorCode?e=a.message:(e=a.message.trim(),e.endsWith(".")||(e+="."),e=b?`An error occurred during authorization: ${e} [Contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.`:`An error occurred during authorization: ${e} Contact the site administrator for more information.`):e=b?L.publicTrialFailConnect:L.failConnect;let t=Error(e);throw a&&a.errorCode&&(t.ltsErrorCode=a.errorCode),t}})();let f=await r.text();try{S||(M.setItem(x,await W(JSON.stringify([u,o]))),S=o),M.setItem(C,f)}catch(e){}return f})(),new Promise(((e,t)=>{let r;r=b?L.publicTrialNetworkTimeout:L.networkTimeout,setTimeout((()=>t(new Error(r))),i?3e3:15e3)}))]);i=d}catch(e){g&&console.error(e),_=e}V.resolve(),V=null},Q=async()=>{Z||(Z=(async()=>{if(F(u),!i){if(!E)throw B(_.message),_;return}let e={dm:y};g&&(e.bd=!0),e.brtk=!0,e.ls=T[0],s&&(-1!=s.indexOf("-")?e.hs=s:e.og=s),e.cu=u,f&&(e.fn=f),r&&(e.pd=r),o&&(e.v=o),c&&(e.dt=c),l&&(e.os=l),w&&(e.rmk=w),F(i);try{let r=JSON.parse(await(async e=>{if(t[A(j.c)]&&t[A(j.c)][A(j.e)]&&t[A(j.c)][A(j.e)][A(j.f)]){let r=h(e),n=new Uint8Array(r.length);for(let e=0;e{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await N();if(F(t),t&&t(O=O.then((async()=>{try{let r=await I.keys();if(t||(te.isFulfilled?e&&(r=r.filter((t=>t{r=e.pd,o=e.v,a=o.split(".")[0],e.dt&&(c=e.dt),s=e.l||"",l="string"!=typeof e.os?JSON.stringify(e.os):e.os,f=e.fn,"string"==typeof f&&(f=f.substring(0,50)),e.ls&&e.ls.length&&(T=e.ls,1==T.length&&T.push(T[0])),b=p===T&&(!s||"200001"===s||s.startsWith("200001-")),v=e.sp,w=e.rmk,P=e.updl,D=e.mnet,N=e.mxet,await X(),await Y(),await q(),await Q(),(!_||_.ltsErrorCode>=102&&_.ltsErrorCode<=120)&&ne(null,!0)},c:async()=>{let e=new Date;if(e.getTime()Q()))}},s:async(e,r,n,o)=>{try{let e;e=r.startsWith("{")&&r.endsWith("}")?await(async e=>{if(t[A(j.c)]&&t[A(j.c)][A(j.e)]&&t[A(j.c)][A(j.e)][A(j.f)]){let r=new Uint8Array(e.length);for(let t=0;t{await ne()}),36e4)},p:te,u:async()=>(await X(),u)}},oe=t,ae="dbr",se=!1,ie="BarcodeReaderWasm",ce=0,de=0;let ue=new n,le=!1,fe=async e=>{await ue,ee=e.trial,te=e.msg,Module[ie].init(JSON.stringify(e))},me=()=>{let e=Module[ie].getMinExpireTime;return e?e():null},he=()=>{let e=Module[ie].getMaxExpireTime;return e?e():null},ge=new Map,ye=0,pe=!1,be=async function(e){const r=e.data?e.data:e,n=r.id,o=r.instanceID,a=r.body;switch(!Q||"decodeBuffer"!=r.type&&"decodeFileInMemory"!=r.type||await re.c(),r.type){case"loadWasm":try{X=r.bd,Y=r.engineResourcePath,se=r.bUseFullFeature,q=r.v;let e=r.dm,n=r.l;Q=r.brtk;let o,a=r.bptk;(async()=>{if(le)throw"can't load wasm twice";le=!0,ve("wasm loading...");let e=Date.now();await new Promise((async e=>{t.KModule=t.Module={locateFile:function(e){return["dbr.full.wasm.wasm","dbr.wasm.wasm"].includes(e)?"Safari"===c.browser&&[11,12].includes(Math.floor(c.version))?Y+ae+"-"+q+".standby"+(se?".full":"")+".wasm":Y+ae+"-"+q+(se?".full":"")+".wasm":Y+e},print:e=>{ve(e)},printErr:e=>{console.error(e),ve(e)},onRuntimeInitialized:e},"Safari"===c.browser&&[11,12].includes(Math.floor(c.version))?importScripts(Y+ae+"-"+q+".standby"+(se?".full":"")+".wasm.js"):importScripts(Y+ae+"-"+q+(se?".full":"")+".wasm.js")})),ve("wasm initialized, cost "+(Date.now()-e)+" ms"),Module=KModule,ue.resolve()})();let s=async()=>{try{re=ne({log:ve,bd:X,dm:e}),t.scsd=re.s,r.pd="dbr",r.updl=fe,r.mnet=me,r.mxet=he,await re.i(r)}catch(e){if(!a)throw e;Q=!1,await i(),o=e.ltsErrorCode,te=e.message||e}},i=async()=>{let t={pk:n,dm:e};X&&(t.bd=!0),await fe(t)};Q?await s():await i(),oe.postMessage({type:"load",success:!0,version:Module[ie].getVersion(),trial:ee,ltsErrorCode:o,message:te})}catch(e){let t=e&&e.message;oe.postMessage({type:"load",success:!1,ltsErrorCode:e&&e.ltsErrorCode,message:t,trial:ee,stack:X&&e?e.stack:null})}break;case"createInstance":{const e=ye++;try{let t=new Module[ie](r.bScanner,e);ge.set(e,t);let n=JSON.parse(t.getRuntimeSettings());r.bScanner?(n.localizationModes=[2,0,0,0,0,0,0,0],n.deblurLevel=0):(n.expectedBarcodesCount=512,n.scaleDownThreshold=1e5,n.timeout=1e5),se||(n.barcodeFormatIds=238028799),t.updateRuntimeSettings(JSON.stringify(n))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,instanceID:e}});break}case"destroyContext":try{if(!ge.get(o))break;ge.get(o).delete(),ge.delete(o)}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"decodeBuffer":{let e,t,r,s,i=Date.now();try{e=X?Date.now():0,d=a.buffer,(u=a.stride*a.height)>ce&&(de&&Module._free(de),de=Module._malloc(u),ce=u),Module.HEAPU8.set(d.subarray(0,u),de),t=X?Date.now():0,s=JSON.parse(ge.get(o).decodeBufferPtr(de,a.width,a.height,a.stride,a.format,void 0===a.orientation?0:a.orientation,!(!a.config||!a.config.bScanner))),r=Date.now()}catch(e){Se(e,n);break}!pe&&Q&&re.p.isPending&&(await Promise.race([re.p,new Promise((e=>setTimeout(e,500)))]),pe=!0),oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:s,buffer:a.buffer,duration:Date.now()-i}},[a.buffer.buffer]),we(["timeWorkerGetMsg: "+i,"timeBeforeSendBufferToWasm: "+e+" "+(e-i),"timeBeforeDecode: "+t+" "+(t-e),"timeFinishDecode: "+r+" "+(r-t)].join("\n"));break}case"decodeFileInMemory":{let e,t,r;try{t=X?Date.now():0,e=JSON.parse(ge.get(o).decodeFileInMemory(a.bytes)),r=X?Date.now():0}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:e,duration:r-t}});break}case"clearMapDecodeRecord":try{ge.get(o).clearMapDecodeRecord()}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getRuntimeSettings":{let e;try{e=ge.get(o).getRuntimeSettings()}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"updateRuntimeSettings":{let e;try{e=JSON.parse(ge.get(o).updateRuntimeSettings(a.settings))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,updateReturn:e}});break}case"resetRuntimeSettings":try{let e=ge.get(o);e.resetRuntimeSettings();let t=JSON.parse(e.getRuntimeSettings());e.bScanner?(t.expectedBarcodesCount=1,t.deblurLevel=0,t.localizationModes=[16,2,0,0,0,0,0,0]):(t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.timeout=1e5),se||(t.barcodeFormatIds=238028799),e.updateRuntimeSettings(JSON.stringify(t)),e.bScanner&&(e.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),e.setModeArgument("LocalizationModes",0,"ScanDirection","2"),e.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),e.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}catch(t){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"resetRuntimeSettingsToCppDefault":try{ge.get(o).resetRuntimeSettings()}catch(t){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"outputRuntimeSettingsToString":{let e;try{e=ge.get(o).outputSettingsToString()}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"initRuntimeSettingsWithString":{let e;try{e=JSON.parse(ge.get(o).initRuntimeSettingsWithString(a.settings))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,initReturn:e}});break}case"getIntermediateResults":{let e=[];try{var s=ge.get(o).getIntermediateResults(),i=JSON.parse(s,((t,r)=>{if("bytes"===t&&"ptr"in r&&"length"in r){var n=r,o=n.ptr,a=n.length;let t=Module[ie].getBytes(o,a);return t=t.slice(0),e.push(t.buffer),t}return r}))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:i}},e),ge.get(o).freeIntermediateResults();break}case"setModeArgument":{let e;try{e=JSON.parse(ge.get(o).setModeArgument(a.modeName,a.index,a.argumentName,a.argumentValue))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,setReturn:e}});break}case"getModeArgument":{let e;try{e=JSON.parse(ge.get(o).getModeArgument(a.modeName,a.index,a.argumentName))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,getReturn:e}});break}case"updateScanSettings":try{let e=ge.get(o),t=a.settings;e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getScanSettings":{let e={};try{let t=ge.get(o);e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}default:console.warn("Unmatched task: ",e)}var d,u};oe.onmessage=be;let ve=e=>{oe.postMessage({type:"log",message:e})},we=e=>{X&&ve(e)},Se=(e,t)=>{oe.postMessage({type:"task",id:t,body:{success:!1,message:e.message,stack:e.stack}}),setTimeout((()=>{throw e}),0)}}(); +!function(){"use strict";const e="undefined"==typeof self,t=e?{}:self,r=e=>e&&"object"==typeof e&&"function"==typeof e.then;class n extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(r(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,r(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const r=await t;e===this._task&&this.resolve(r)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}let o,a,s,i,c;if("undefined"!=typeof navigator&&(o=navigator,a=o.userAgent,s=o.platform,i=o.mediaDevices),!e){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:o.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:s,search:"Win"},Mac:{str:s},Linux:{str:s}};let r="unknownBrowser",n=0,i="unknownOS";for(let t in e){const o=e[t]||{};let s=o.str||a,i=o.search||t,c=o.verStr||a,d=o.verSearch||t;if(d instanceof Array||(d=[d]),-1!=s.indexOf(i)){r=t;for(let e of d){let t=c.indexOf(e);if(-1!=t){n=parseFloat(c.substring(t+e.length+1));break}}break}}for(let e in t){const r=t[e]||{};let n=r.str||a,o=r.search||e;if(-1!=n.indexOf(o)){i=e;break}}"Linux"==i&&-1!=a.indexOf("Windows NT")&&(i="HarmonyOS"),c={browser:r,version:n,OS:i}}e&&(c={browser:"ssr",version:0,OS:"ssr"}),"undefined"!=typeof WebAssembly&&a&&(!/Safari/.test(a)||/Chrome/.test(a)||/\(.+\s11_2_([2-6]).*\)/.test(a)),i&&i.getUserMedia;const d="Chrome"===c.browser&&c.version>66||"Safari"===c.browser&&c.version>13||"OPR"===c.browser&&c.version>43||"Edge"===c.browser&&c.version>15;var l=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(e){return}}();function u(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(o){if("TypeError"!==o.name)throw o;for(var r=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),n=0;n=43)}})).catch((function(){return!1}))}(e).then((function(e){return p=e,p}))}function k(e){var t=b[e.name],r={};r.promise=new Promise((function(e,t){r.resolve=e,r.reject=t})),t.deferredOperations.push(r),t.dbReady?t.dbReady=t.dbReady.then((function(){return r.promise})):t.dbReady=r.promise}function I(e){var t=b[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function M(e,t){var r=b[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function x(e,t){return new Promise((function(r,n){if(b[e.name]=b[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return r(e.db);k(e),e.db.close()}var o=[e.name];t&&o.push(e.version);var a=l.open.apply(l,o);t&&(a.onupgradeneeded=function(t){var r=a.result;try{r.createObjectStore(e.storeName),t.oldVersion<=1&&r.createObjectStore(y)}catch(r){if("ConstraintError"!==r.name)throw r;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),a.onerror=function(e){e.preventDefault(),n(a.error)},a.onsuccess=function(){var t=a.result;t.onversionchange=function(e){e.target.close()},r(t),I(e)}}))}function C(e){return x(e,!1)}function P(e){return x(e,!0)}function D(e,t){if(!e.db)return!0;var r=!e.db.objectStoreNames.contains(e.storeName),n=e.versione.db.version;if(n&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),o||r){if(r){var a=e.db.version+1;a>e.version&&(e.version=a)}return!0}return!1}function N(e){var t=function(e){for(var t=e.length,r=new ArrayBuffer(t),n=new Uint8Array(r),o=0;o0&&(!e.db||"InvalidStateError"===o.name||"NotFoundError"===o.name))return Promise.resolve().then((()=>{if(!e.db||"NotFoundError"===o.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),P(e)})).then((()=>function(e){k(e);for(var t=b[e.name],r=t.forages,n=0;n(e.db=t,D(e)?P(e):t))).then((n=>{e.db=t.db=n;for(var o=0;o{throw M(e,t),t}))}(e).then((function(){T(e,t,r,n-1)})))).catch(r);r(o)}}var E={_driver:"asyncStorage",_initStorage:function(e){var t=this,r={db:null};if(e)for(var n in e)r[n]=e[n];var o=b[r.name];o||(o={forages:[],db:null,dbReady:null,deferredOperations:[]},b[r.name]=o),o.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=R);var a=[];function s(){return Promise.resolve()}for(var i=0;i{const r=b[e.name],n=r.forages;r.db=t;for(var o=0;o{if(!t.objectStoreNames.contains(e.storeName))return;const r=t.version+1;k(e);const n=b[e.name],o=n.forages;t.close();for(let e=0;e{const o=l.open(e.name,r);o.onerror=e=>{o.result.close(),n(e)},o.onupgradeneeded=()=>{o.result.deleteObjectStore(e.storeName)},o.onsuccess=()=>{const e=o.result;e.close(),t(e)}}));return a.then((e=>{n.db=e;for(let t=0;t{throw(M(e,t)||Promise.resolve()).catch((()=>{})),t}))})):t.then((t=>{k(e);const r=b[e.name],n=r.forages;t.close();for(var o=0;o{var n=l.deleteDatabase(e.name);n.onerror=()=>{const e=n.result;e&&e.close(),r(n.error)},n.onblocked=()=>{console.warn('dropInstance blocked for database "'+e.name+'" until all open connections are closed')},n.onsuccess=()=>{const e=n.result;e&&e.close(),t(e)}}));return a.then((e=>{r.db=e;for(var t=0;t{throw(M(e,t)||Promise.resolve()).catch((()=>{})),t}))}))}else n=Promise.reject("Invalid arguments");return f(n,t),n}};const O=new Map;function B(e,t){let r=e.name+"/";return e.storeName!==t.storeName&&(r+=e.storeName+"/"),r}var F={_driver:"tempStorageWrapper",_initStorage:async function(e){const t={};if(e)for(let r in e)t[r]=e[r];const r=t.keyPrefix=B(e,this._defaultConfig);this._dbInfo=t,O.has(r)||O.set(r,new Map)},getItem:function(e,t){e=h(e);const r=this.ready().then((()=>O.get(this._dbInfo.keyPrefix).get(e)));return f(r,t),r},setItem:function(e,t,r){e=h(e);const n=this.ready().then((()=>(void 0===t&&(t=null),O.get(this._dbInfo.keyPrefix).set(e,t),t)));return f(n,r),n},removeItem:function(e,t){e=h(e);const r=this.ready().then((()=>{O.get(this._dbInfo.keyPrefix).delete(e)}));return f(r,t),r},clear:function(e){const t=this.ready().then((()=>{const e=this._dbInfo.keyPrefix;O.has(e)&&O.delete(e)}));return f(t,e),t},length:function(e){const t=this.ready().then((()=>O.get(this._dbInfo.keyPrefix).size));return f(t,e),t},keys:function(e){const t=this.ready().then((()=>[...O.get(this._dbInfo.keyPrefix).keys()]));return f(t,e),t},dropInstance:function(e,t){if(t=g.apply(this,arguments),!(e="function"!=typeof e&&e||{}).name){const t=this.config();e.name=e.name||t.name,e.storeName=e.storeName||t.storeName}let r;return r=e.name?new Promise((t=>{e.storeName?t(B(e,this._defaultConfig)):t(`${e.name}/`)})).then((e=>{O.delete(e)})):Promise.reject("Invalid arguments"),f(r,t),r}};const A=(e,t)=>{const r=e.length;let n=0;for(;n{}))}config(e){if("object"==typeof e){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(let t in e){if("storeName"===t&&(e[t]=e[t].replace(/\W/g,"_")),"version"===t&&"number"!=typeof e[t])return new Error("Database version must be a number.");this._config[t]=e[t]}return!("driver"in e)||!e.driver||this.setDriver(this._config.driver)}return"string"==typeof e?this._config[e]:this._config}defineDriver(e,t,r){const n=new Promise((function(t,r){try{const n=e._driver,o=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!e._driver)return void r(o);const a=L.concat("_initStorage");for(let t=0,n=a.length;t(null===t._ready&&(t._ready=t._initDriver()),t._ready)));return m(r,e,e),r}setDriver(e,t,r){const n=this;j(e)||(e=[e]);const o=this._getSupportedDrivers(e);function a(){n._config.driver=n.driver()}function s(e){return n._extend(e),a(),n._ready=n._initStorage(n._config),n._ready}const i=null!==this._driverSet?this._driverSet.catch((()=>Promise.resolve())):Promise.resolve();return this._driverSet=i.then((()=>{const e=o[0];return n._dbInfo=null,n._ready=null,n.getDriver(e).then((e=>{n._driver=e._driver,a(),n._wrapLibraryMethodsWithReady(),n._initDriver=function(e){return function(){let t=0;return function r(){for(;t{a();const e=new Error("No available storage method found.");return n._driverSet=Promise.reject(e),n._driverSet})),m(this._driverSet,t,r),this._driverSet}supports(e){return!!J[e]}_extend(e){K(this,e)}_getSupportedDrivers(e){const t=[];for(let r=0,n=e.length;r{let r,o,a,s,i,c,l,u,f,m=t.btoa,h=t.atob,g=e.bd,y=e.dm;const p=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"];let b,v,w,S,_,k,I,M,x,C,P,D,N,R,T,E=p,O=!1,B=Promise.resolve(),F=e.log&&((...t)=>{try{e.log.apply(null,t)}catch(e){setTimeout((()=>{throw e}),0)}})||(()=>{}),A=g&&F||(()=>{}),j=e=>e.join(""),U={a:[80,88,27,82,145,164,199,211],b:[187,87,89,128,150,44,190,213],c:[89,51,74,53,99,72,82,118],d:[99,181,118,158,215,103,76,117],e:[99,51,86,105,100,71,120,108],f:[97,87,49,119,98,51,74,48,83,50,86,53],g:[81,85,86,84,76,85,100,68,84,81,32,32],h:[90,87,53,106,99,110,108,119,100,65,32,32],i:[90,71,86,106,99,110,108,119,100,65,32,32],j:[97,88,89,32],k:[29,83,122,137,5,180,157,114],l:[100,71,70,110,84,71,86,117,90,51,82,111]},J=()=>t[j(U.c)][j(U.e)][j(U.f)]("raw",new Uint8Array(U.a.concat(U.b,U.d,U.k)),j(U.g),!0,[j(U.h),j(U.i)]),W=e=>h(h(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),z=e=>m(String.fromCharCode(97+25*Math.random())+m(e)).replace(/\+/g,"\n").replace(/=/g," "),H=()=>{if(t.crypto){let e=new Uint8Array(36);t.crypto.getRandomValues(e);let r="";for(let t=0;t<36;++t){let n=e[t]%36;r+=n<10?n:String.fromCharCode(n+87)}return r}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))};const L="Failed to connect to the Dynamsoft License Server: ",$={dlsErrorAndCacheExpire:L+"The cached license has expired. Please get connected to the network as soon as possible or contact the site administrator for more information.",publicTrialNetworkTimeout:L+"network timed out. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",networkTimeout:L+"network timed out. Check your Internet connection or contact the site administrator for more information.",publicTrialFailConnect:L+"network connection error. Check your Internet connection or [contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.",failConnect:L+"network connection error. Check your Internet connection or contact the site administrator for more information.",checkLocalTime:"Your system date and time appear to have been changed, causing the license to fail. Please correct the system data and time and try again.",idbTimeout:"Failed to open indexedDB: Timeout."};let V,K,Z,X,Y=async()=>{if(V)return V;V=new n,await(async()=>{I||(I=G)})(),await Promise.race([(async()=>{let e=await I.createInstance({name:"dynamjssdkhello"});await e.setItem("dynamjssdkhello","available")})(),new Promise(((e,t)=>{setTimeout((()=>t(new Error($.idbTimeout))),5e3)}))]),x=await I.createInstance({name:"dynamdlsinfo"}),C=m(m("v2")+String.fromCharCode(y.charCodeAt(y.length/2)+1)+m(y));try{let e=await x.getItem(C);if(!e){let t=await I.createInstance({name:"dynamltsinfo"});e=await t.getItem(C),e&&await x.setItem(C,e)}e&&([l,_]=JSON.parse(await W(e)))}catch(e){}try{null==l&&(l=H(),x.setItem(C,await z(JSON.stringify([l,null]))))}catch(e){}V.resolve()},q=async()=>{P=m(String.fromCharCode(s.charCodeAt(0)+10)+m(r)+m(s)+a+m(""+c)),M=await I.createInstance({name:"dynamdlsuns"+m(m("v2"))+m(String.fromCharCode(s.charCodeAt(0)+10)+m(r)+m(s)+a+m(""+c))});try{i=await x.getItem(P)}catch(e){}j=e=>h(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="))},Q=async e=>{if(Z=Date.now(),K)return K;K=new n;try{let t={pd:r,vm:a,v:o,dt:c||"browser",ed:"javascript",cu:l,ad:y,os:u,fn:f};w&&(t.rmk=w),s&&(t=-1!=s.indexOf("-")?{...t,hs:s}:{...t,og:s});let n={};if(_){let e=await x.getItem(C);e&&([l,_]=JSON.parse(await W(e))),n["lts-time"]=_}v&&(t.sp=v);let d=await Promise.race([(async()=>{let r,o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");_&&(x.setItem(C,await z(JSON.stringify([l,o]))),_=o);let a="auth/?ext="+encodeURIComponent(m(JSON.stringify(t)));S&&(a+="&v="+encodeURIComponent(S));let s,c=!1,d=!1,u=async e=>{if(e&&!e.ok)try{let t=await e.text();if(t){let e=JSON.parse(t);e.errorCode&&(s=e,e.errorCode>100&&e.errorCode<200&&(i=null,c=!0,d=!0))}}catch(e){}};try{r=await Promise.race([fetch(E[0]+a,{headers:n,cache:e?"reload":"default",mode:"cors"}),new Promise(((e,t)=>setTimeout(t,1e4)))]),await u(r)}catch(e){}if(!(i||r&&r.ok||c))try{r=await Promise.race([fetch(E[1]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r)}catch(e){}if(!(i||r&&r.ok||c))try{r=await Promise.race([fetch(E[0]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r)}catch(e){}s&&151==s.errorCode&&(x.removeItem(C),x.removeItem(P),l=H(),t.cu=l,_=void 0,a="auth/?ext="+encodeURIComponent(m(JSON.stringify(t))),r=await Promise.race([fetch(E[0]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r));(()=>{if(!r||!r.ok){let e;d&&x.setItem(P,""),s?111==s.errorCode?e=s.message:(e=s.message.trim(),e.endsWith(".")||(e+="."),e=b?`An error occurred during authorization: ${e} [Contact Dynamsoft](https://www.dynamsoft.com/company/contact/) for more information.`:`An error occurred during authorization: ${e} Contact the site administrator for more information.`):e=b?$.publicTrialFailConnect:$.failConnect;let t=Error(e);throw s&&s.errorCode&&(t.ltsErrorCode=s.errorCode),t}})();let f=await r.text();try{_||(x.setItem(C,await z(JSON.stringify([l,o]))),_=o),x.setItem(P,f)}catch(e){}return f})(),new Promise(((e,t)=>{let r;r=b?$.publicTrialNetworkTimeout:$.networkTimeout,setTimeout((()=>t(new Error(r))),i?3e3:15e3)}))]);i=d}catch(e){g&&console.error(e),k=e}K.resolve(),K=null},ee=async()=>{X||(X=(async()=>{if(A(l),!i){if(!O)throw F(k.message),k;return}let e={dm:y};g&&(e.bd=!0),e.brtk=!0,e.ls=E[0],s&&(-1!=s.indexOf("-")?e.hs=s:e.og=s),e.cu=l,f&&(e.fn=f),r&&(e.pd=r),o&&(e.v=o),c&&(e.dt=c),u&&(e.os=u),w&&(e.rmk=w),A(i);try{let r=JSON.parse(await(async e=>{if(t[j(U.c)]&&t[j(U.c)][j(U.e)]&&t[j(U.c)][j(U.e)][j(U.f)]){let r=h(e),n=new Uint8Array(r.length);for(let e=0;e{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await R();if(A(t),t&&t(B=B.then((async()=>{try{let r=await M.keys();if(t||(re.isFulfilled?e&&(r=r.filter((t=>t{r=e.pd,o=e.v,a=o.split(".")[0],e.dt&&(c=e.dt),s=e.l||"",u="string"!=typeof e.os?JSON.stringify(e.os):e.os,f=e.fn,"string"==typeof f&&(f=f.substring(0,50)),e.ls&&e.ls.length&&(E=e.ls,1==E.length&&E.push(E[0])),b=p===E&&(!s||"200001"===s||s.startsWith("200001-")),v=e.sp,w=e.rmk,e.cv&&(S=""+e.cv),D=e.updl,N=e.mnet,R=e.mxet,await Y(),await q(),await Q(),await ee(),(!k||k.ltsErrorCode>=102&&k.ltsErrorCode<=120)&&oe(null,!0)},c:async()=>{let e=new Date;if(e.getTime()ee()))}},s:async(e,r,n,o)=>{try{let e;e=r.startsWith("{")&&r.endsWith("}")?await(async e=>{if(t[j(U.c)]&&t[j(U.c)][j(U.e)]&&t[j(U.c)][j(U.e)][j(U.f)]){let r=new Uint8Array(e.length);for(let t=0;t{await oe()}),36e4)},p:re,u:async()=>(await Y(),l)}},oe=t,ae="dbr",se=!1,ie="BarcodeReaderWasm",ce=0,de=0;let le=new n,ue=!1,fe=async e=>{await le,ee=e.trial,te=e.msg,Module[ie].init(JSON.stringify(e))},me=()=>{let e=Module[ie].getMinExpireTime;return e?e():null},he=()=>{let e=Module[ie].getMaxExpireTime;return e?e():null},ge=new Map,ye=0,pe=!1,be=async function(e){const r=e.data?e.data:e,n=r.id,o=r.instanceID,a=r.body;switch(!Q||"decodeBuffer"!=r.type&&"decodeFileInMemory"!=r.type||await re.c(),r.type){case"loadWasm":try{X=r.bd,Y=r.engineResourcePath,se=r.bUseFullFeature,q=r.v;let e=r.dm,n=r.l;Q=r.brtk;let o,a=r.bptk;(async()=>{if(ue)throw"can't load wasm twice";ue=!0,ve("wasm loading...");let e=Date.now();await new Promise((async e=>{t.KModule=t.Module={locateFile:function(e){return["dbr.full.wasm.wasm","dbr.wasm.wasm"].includes(e)?"Safari"===c.browser&&[11,12].includes(Math.floor(c.version))?Y+ae+"-"+q+".standby"+(se?".full":"")+".wasm":Y+ae+"-"+q+(se?".full":"")+".wasm":Y+e},print:e=>{ve(e)},printErr:e=>{console.error(e),ve(e)},onRuntimeInitialized:e},"Safari"===c.browser&&[11,12].includes(Math.floor(c.version))?importScripts(Y+ae+"-"+q+".standby"+(se?".full":"")+".wasm.js"):importScripts(Y+ae+"-"+q+(se?".full":"")+".wasm.js")})),ve("wasm initialized, cost "+(Date.now()-e)+" ms"),Module=KModule,le.resolve()})();let s=async()=>{try{re=ne({log:ve,bd:X,dm:e}),t.scsd=re.s,r.pd="dbr",r.updl=fe,r.mnet=me,r.mxet=he,await re.i(r)}catch(e){if(!a)throw e;Q=!1,await i(),o=e.ltsErrorCode,te=e.message||e}},i=async()=>{let t={pk:n,dm:e};X&&(t.bd=!0),await fe(t)};Q?await s():await i(),oe.postMessage({type:"load",success:!0,version:Module[ie].getVersion(),trial:ee,ltsErrorCode:o,message:te})}catch(e){let t=e&&e.message;oe.postMessage({type:"load",success:!1,ltsErrorCode:e&&e.ltsErrorCode,message:t,trial:ee,stack:X&&e?e.stack:null})}break;case"createInstance":{const e=ye++;try{let t=new Module[ie](r.bScanner,e);ge.set(e,t);let n=JSON.parse(t.getRuntimeSettings());r.bScanner?(n.localizationModes=[2,0,0,0,0,0,0,0],n.deblurLevel=0):(n.expectedBarcodesCount=512,n.scaleDownThreshold=1e5,n.timeout=1e5),se||(n.barcodeFormatIds=238028799),t.updateRuntimeSettings(JSON.stringify(n))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,instanceID:e}});break}case"destroyContext":try{if(!ge.get(o))break;ge.get(o).delete(),ge.delete(o)}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"decodeBuffer":{let e,t,r,s,i=Date.now();try{e=X?Date.now():0,d=a.buffer,(l=a.stride*a.height)>ce&&(de&&Module._free(de),de=Module._malloc(l),ce=l),Module.HEAPU8.set(d.subarray(0,l),de),t=X?Date.now():0,s=JSON.parse(ge.get(o).decodeBufferPtr(de,a.width,a.height,a.stride,a.format,void 0===a.orientation?0:a.orientation,!(!a.config||!a.config.bScanner))),r=Date.now()}catch(e){Se(e,n);break}!pe&&Q&&re.p.isPending&&(await Promise.race([re.p,new Promise((e=>setTimeout(e,500)))]),pe=!0),oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:s,buffer:a.buffer,duration:Date.now()-i}},[a.buffer.buffer]),we(["timeWorkerGetMsg: "+i,"timeBeforeSendBufferToWasm: "+e+" "+(e-i),"timeBeforeDecode: "+t+" "+(t-e),"timeFinishDecode: "+r+" "+(r-t)].join("\n"));break}case"decodeFileInMemory":{let e,t,r;try{t=X?Date.now():0,e=JSON.parse(ge.get(o).decodeFileInMemory(a.bytes)),r=X?Date.now():0}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,decodeReturn:e,duration:r-t}});break}case"clearMapDecodeRecord":try{ge.get(o).clearMapDecodeRecord()}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getRuntimeSettings":{let e;try{e=ge.get(o).getRuntimeSettings()}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"updateRuntimeSettings":{let e;try{e=JSON.parse(ge.get(o).updateRuntimeSettings(a.settings))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,updateReturn:e}});break}case"resetRuntimeSettings":try{let e=ge.get(o);e.resetRuntimeSettings();let t=JSON.parse(e.getRuntimeSettings());e.bScanner?(t.expectedBarcodesCount=1,t.deblurLevel=0,t.localizationModes=[16,2,0,0,0,0,0,0]):(t.expectedBarcodesCount=512,t.scaleDownThreshold=1e5,t.timeout=1e5),se||(t.barcodeFormatIds=238028799),e.updateRuntimeSettings(JSON.stringify(t)),e.bScanner&&(e.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","0"),e.setModeArgument("LocalizationModes",0,"ScanDirection","2"),e.setModeArgument("BinarizationModes",0,"BlockSizeX","71"),e.setModeArgument("BinarizationModes",0,"BlockSizeY","71"))}catch(t){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"resetRuntimeSettingsToCppDefault":try{ge.get(o).resetRuntimeSettings()}catch(t){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"outputRuntimeSettingsToString":{let e;try{e=ge.get(o).outputSettingsToString()}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}case"initRuntimeSettingsWithString":{let e;try{e=JSON.parse(ge.get(o).initRuntimeSettingsWithString(a.settings))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,initReturn:e}});break}case"getIntermediateResults":{let e=[];try{var s=ge.get(o).getIntermediateResults(),i=JSON.parse(s,((t,r)=>{if("bytes"===t&&"ptr"in r&&"length"in r){var n=r,o=n.ptr,a=n.length;let t=Module[ie].getBytes(o,a);return t=t.slice(0),e.push(t.buffer),t}return r}))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:i}},e),ge.get(o).freeIntermediateResults();break}case"setModeArgument":{let e;try{e=JSON.parse(ge.get(o).setModeArgument(a.modeName,a.index,a.argumentName,a.argumentValue))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,setReturn:e}});break}case"getModeArgument":{let e;try{e=JSON.parse(ge.get(o).getModeArgument(a.modeName,a.index,a.argumentName))}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,getReturn:e}});break}case"updateScanSettings":try{let e=ge.get(o),t=a.settings;e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"getScanSettings":{let e={};try{let t=ge.get(o);e.duplicateForgetTime=t.duplicateForgetTime,e.oneDRememberFrameCount=t.oneDRememberFrameCount,e.oneDTrustFrameCount=t.oneDTrustFrameCount}catch(e){Se(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}default:console.warn("Unmatched task: ",e)}var d,l};oe.onmessage=be;let ve=e=>{oe.postMessage({type:"log",message:e})},we=e=>{X&&ve(e)},Se=(e,t)=>{oe.postMessage({type:"task",id:t,body:{success:!1,message:e.message,stack:e.stack}}),setTimeout((()=>{throw e}),0)}}(); diff --git a/dist/dbr-9.6.10.full.wasm b/dist/dbr-9.6.11.full.wasm similarity index 100% rename from dist/dbr-9.6.10.full.wasm rename to dist/dbr-9.6.11.full.wasm diff --git a/dist/dbr-9.6.10.full.wasm.js b/dist/dbr-9.6.11.full.wasm.js similarity index 100% rename from dist/dbr-9.6.10.full.wasm.js rename to dist/dbr-9.6.11.full.wasm.js diff --git a/dist/dbr-9.6.10.standby.full.wasm b/dist/dbr-9.6.11.standby.full.wasm similarity index 100% rename from dist/dbr-9.6.10.standby.full.wasm rename to dist/dbr-9.6.11.standby.full.wasm diff --git a/dist/dbr-9.6.10.standby.full.wasm.js b/dist/dbr-9.6.11.standby.full.wasm.js similarity index 100% rename from dist/dbr-9.6.10.standby.full.wasm.js rename to dist/dbr-9.6.11.standby.full.wasm.js diff --git a/dist/dbr-9.6.10.standby.wasm b/dist/dbr-9.6.11.standby.wasm similarity index 100% rename from dist/dbr-9.6.10.standby.wasm rename to dist/dbr-9.6.11.standby.wasm diff --git a/dist/dbr-9.6.10.standby.wasm.js b/dist/dbr-9.6.11.standby.wasm.js similarity index 100% rename from dist/dbr-9.6.10.standby.wasm.js rename to dist/dbr-9.6.11.standby.wasm.js diff --git a/dist/dbr-9.6.10.wasm b/dist/dbr-9.6.11.wasm similarity index 100% rename from dist/dbr-9.6.10.wasm rename to dist/dbr-9.6.11.wasm diff --git a/dist/dbr-9.6.10.wasm.js b/dist/dbr-9.6.11.wasm.js similarity index 100% rename from dist/dbr-9.6.10.wasm.js rename to dist/dbr-9.6.11.wasm.js diff --git a/dist/dbr.js b/dist/dbr.js index c47f1f7..668776b 100644 --- a/dist/dbr.js +++ b/dist/dbr.js @@ -4,11 +4,11 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2023, Dynamsoft Corporation * @author Dynamsoft - * @version 9.6.10 (js 20230213) + * @version 9.6.11 (js 20230310) * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.DBR={}))}(this,(function(e){"use strict";const t="undefined"==typeof self;let i,r,n,s,o;if("undefined"!=typeof navigator&&(i=navigator,r=i.userAgent,n=i.platform,s=i.mediaDevices),!t){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:i.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:n,search:"Win"},Mac:{str:n},Linux:{str:n}};let s="unknownBrowser",a=0,h="unknownOS";for(let t in e){const i=e[t]||{};let n=i.str||r,o=i.search||t,h=i.verStr||r,l=i.verSearch||t;if(l instanceof Array||(l=[l]),-1!=n.indexOf(o)){s=t;for(let e of l){let t=h.indexOf(e);if(-1!=t){a=parseFloat(h.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let n=i.str||r,s=i.search||e;if(-1!=n.indexOf(s)){h=e;break}}"Linux"==h&&-1!=r.indexOf("Windows NT")&&(h="HarmonyOS"),o={browser:s,version:a,OS:h}}t&&(o={browser:"ssr",version:0,OS:"ssr"});const a="undefined"!=typeof WebAssembly&&r&&!(/Safari/.test(r)&&!/Chrome/.test(r)&&/\(.+\s11_2_([2-6]).*\)/.test(r)),h=!("undefined"==typeof Worker),l=!(!s||!s.getUserMedia),c=async()=>{let e=!1;if(l)try{(await s.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===o.browser&&o.version>66||"Safari"===o.browser&&o.version>13||"OPR"===o.browser&&o.version>43||"Edge"===o.browser&&o.version;const u=(()=>{if(!t&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),d=" is not allowed to change after `createInstance` or `loadWasm` is called.",f=!t&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",g=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",_=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let i=0;ie&&"object"==typeof e&&"function"==typeof e.then;class b extends Promise{constructor(e){let t,i;super(((e,r)=>{t=e,i=r})),this._s="pending",this.resolve=e=>{this.isPending&&(C(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,C(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}var w=function(){this.init()};w.prototype={init:function(){var e=this||x;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||x;if(e=parseFloat(e),t.ctx||M(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,x.ctx.currentTime);for(var i=0;i=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,M()),e},codecs:function(e){return(this||x)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||x;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||x,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var i=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",n=r.match(/OPR\/([0-6].)/g),s=n&&parseInt(n[0].split("/")[1],10)<33,o=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),a=r.match(/Version\/(.*?) /),h=o&&a&&parseInt(a[1],10)<15;return e._codecs={mp3:!(s||!i&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!i,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(h||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(h||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||x;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(i){for(;e._html5AudioPool.length0?o._seek:i._sprite[e][0]/1e3),l=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-h),c=1e3*l/Math.abs(o._rate),u=i._sprite[e][0]/1e3,d=(i._sprite[e][0]+i._sprite[e][1])/1e3;o._sprite=e,o._ended=!1;var f=function(){o._paused=!1,o._seek=h,o._start=u,o._stop=d,o._loop=!(!o._loop&&!i._sprite[e][2])};if(!(h>=d)){var g=o._node;if(i._webAudio){var _=function(){i._playLock=!1,f(),i._refreshBuffer(o);var e=o._muted||i._muted?0:o._volume;g.gain.setValueAtTime(e,x.ctx.currentTime),o._playStart=x.ctx.currentTime,void 0===g.bufferSource.start?o._loop?g.bufferSource.noteGrainOn(0,h,86400):g.bufferSource.noteGrainOn(0,h,l):o._loop?g.bufferSource.start(0,h,86400):g.bufferSource.start(0,h,l),c!==1/0&&(i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c)),t||setTimeout((function(){i._emit("play",o._id),i._loadQueue()}),0)};"running"===x.state&&"interrupted"!==x.ctx.state?_():(i._playLock=!0,i.once("resume",_),i._clearTimer(o._id))}else{var p=function(){g.currentTime=h,g.muted=o._muted||i._muted||x._muted||g.muted,g.volume=o._volume*x.volume(),g.playbackRate=o._rate;try{var r=g.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(i._playLock=!0,f(),r.then((function(){i._playLock=!1,g._unlocked=!0,t?i._loadQueue():i._emit("play",o._id)})).catch((function(){i._playLock=!1,i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),o._ended=!0,o._paused=!0}))):t||(i._playLock=!1,f(),i._emit("play",o._id)),g.playbackRate=o._rate,g.paused)return void i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||o._loop?i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c):(i._endTimers[o._id]=function(){i._ended(o),g.removeEventListener("ended",i._endTimers[o._id],!1)},g.addEventListener("ended",i._endTimers[o._id],!1))}catch(e){i._emit("playerror",o._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=i._src,g.load());var m=window&&window.ejecta||!g.readyState&&x._navigator.isCocoonJS;if(g.readyState>=3||m)p();else{i._playLock=!0,i._state="loading";var v=function(){i._state="loaded",p(),g.removeEventListener(x._canPlayEvent,v,!1)};g.addEventListener(x._canPlayEvent,v,!1),i._clearTimer(o._id)}}return o._id}i._ended(o)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),r=0;r=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(i=t?r._soundById(t):r._sounds[0])?i._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,n)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var a=0;a0?r/l:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=h*n,a=Math.round(100*a)/100,a=h<0?Math.max(i,a):Math.min(i,a),o._webAudio?e._volume=a:o.volume(a,e._id,!0),s&&(o._volume=a),(it&&a>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,o.volume(i,e._id),o._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,i=t._soundById(e);return i&&i._interval&&(t._webAudio&&i._node.gain.cancelScheduledValues(x.ctx.currentTime),clearInterval(i._interval),i._interval=null,t.volume(i._fadeTo,e),i._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,i,r=this,n=arguments;if(0===n.length)return r._loop;if(1===n.length){if("boolean"!=typeof n[0])return!!(i=r._soundById(parseInt(n[0],10)))&&i._loop;e=n[0],r._loop=e}else 2===n.length&&(e=n[0],t=parseInt(n[1],10));for(var s=r._getSoundIds(t),o=0;o=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else 2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if("number"!=typeof e)return(i=r._soundById(t))?i._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,n)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var a=0;a=0?t=parseInt(r[0],10):i._sounds.length&&(t=i._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==i._state||i._playLock))return i._queue.push({event:"seek",action:function(){i.seek.apply(i,r)}}),i;var o=i._soundById(t);if(o){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var a=i.playing(t)?x.ctx.currentTime-o._playStart:0,h=o._rateSeek?o._rateSeek-o._seek:0;return o._seek+(h+a*Math.abs(o._rate))}return o._node.currentTime}var l=i.playing(t);l&&i.pause(t,!0),o._seek=e,o._ended=!1,i._clearTimer(t),i._webAudio||!o._node||isNaN(o._node.duration)||(o._node.currentTime=e);var c=function(){l&&i.play(t,!0),i._emit("seek",t)};if(l&&!i._webAudio){var u=function(){i._playLock?setTimeout(u,0):c()};setTimeout(u,0)}else c()}return i},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var r=0;r=0&&x._howls.splice(r,1);var n=!0;for(i=0;i=0){n=!1;break}return I&&n&&delete I[e._src],x.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,r){var n=this["_on"+e];return"function"==typeof t&&n.push(r?{id:i,fn:t,once:r}:{id:i,fn:t}),this},off:function(e,t,i){var r=this,n=r["_on"+e],s=0;if("number"==typeof t&&(i=t,t=null),t||i)for(s=0;s=0;s--)n[s].id&&n[s].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(r,n[s].fn),0),n[s].once&&r.off(e,n[s].fn,n[s].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var t=this,i=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(i<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i=0;if(!e.bufferSource)return this;if(x._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=x._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(x._navigator&&x._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var E=function(e){this._parent=e,this.init()};E.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++x._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=x._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===x.ctx.createGain?x.ctx.createGainNode():x.ctx.createGain(),e._node.gain.setValueAtTime(i,x.ctx.currentTime),e._node.paused=!0,e._node.connect(x.masterGain)):x.noAudio||(e._node=x._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(x._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*x.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++x._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(x._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var I={},A=function(e){var t=e._src;if(I[t])return e._duration=I[t].duration,void D(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(I[t._src]=e,D(t,e)):i()};"undefined"!=typeof Promise&&1===x.ctx.decodeAudioData.length?x.ctx.decodeAudioData(e).then(r).catch(i):x.ctx.decodeAudioData(e,r,i)},D=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},M=function(){if(x.usingWebAudio){try{"undefined"!=typeof AudioContext?x.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?x.ctx=new webkitAudioContext:x.usingWebAudio=!1}catch(e){x.usingWebAudio=!1}x.ctx||(x.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(x._navigator&&x._navigator.platform),t=x._navigator&&x._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var r=/safari/.test(x._navigator&&x._navigator.userAgent.toLowerCase());x._navigator&&!r&&(x.usingWebAudio=!1)}x.usingWebAudio&&(x.masterGain=void 0===x.ctx.createGain?x.ctx.createGainNode():x.ctx.createGain(),x.masterGain.gain.setValueAtTime(x._muted?0:x._volume,x.ctx.currentTime),x.masterGain.connect(x.ctx.destination)),x._setup()}};!function(e,t,i,r){var n;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},e.prototype.pos=function(e,i,r){var n=this;return n.ctx&&n.ctx.listener?(i="number"!=typeof i?n._pos[1]:i,r="number"!=typeof r?n._pos[2]:r,"number"!=typeof e?n._pos:(n._pos=[e,i,r],void 0!==n.ctx.listener.positionX?(n.ctx.listener.positionX.setTargetAtTime(n._pos[0],t.ctx.currentTime,.1),n.ctx.listener.positionY.setTargetAtTime(n._pos[1],t.ctx.currentTime,.1),n.ctx.listener.positionZ.setTargetAtTime(n._pos[2],t.ctx.currentTime,.1)):n.ctx.listener.setPosition(n._pos[0],n._pos[1],n._pos[2]),n)):n},e.prototype.orientation=function(e,i,r,n,s,o){var a=this;if(!a.ctx||!a.ctx.listener)return a;var h=a._orientation;return i="number"!=typeof i?h[1]:i,r="number"!=typeof r?h[2]:r,n="number"!=typeof n?h[3]:n,s="number"!=typeof s?h[4]:s,o="number"!=typeof o?h[5]:o,"number"!=typeof e?h:(a._orientation=[e,i,r,n,s,o],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(i,t.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(n,t.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(s,t.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(o,t.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,i,r,n,s,o),a)},i.prototype.init=(n=i.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],n.call(this,e)}),i.prototype.stereo=function(e,i){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,i)}}),r;var n=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var o=r._getSoundIds(i),a=0;a{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=F,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+d);i._license=t})(L,e)}static get productKeys(){return this._license}static set productKeys(e){L.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){L.license=e}static get organizationID(){return this._license}static set organizationID(e){L.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+d);i._sessionPassword=t})(L,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:a,worker:h,getUserMedia:l,camera:await c(),browser:o.browser,version:o.version,OS:o.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");L._engineResourcePath=(e=>{if(null==e&&(e="./"),!t){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+d);i._licenseServer=_(t)})(L,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+d);i._deviceFriendlyName=t||""})(L,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");L.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&(("colorMode"in e||"pixelFormat"in e)&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=L._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",L.engineResourcePath)}static set defaultUIElementURL(e){L._defaultUIElementURL=e}static _fireHTTPSWarnning(){L.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{L.onWarning&&L.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new T({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;L._onLog&&L._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const i=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else i||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let t=await this._decode_DCEFrame(e,{bCopyData:!1}),i=null;if(t&&t.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:h}=e;i=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(i,r,n,a,h,s,o)}if(this._drawResults(i,t),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(L._onLog&&L._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!L.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:i,sp:r,rmk:n}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,i,r=t._license||"",n=JSON.parse(JSON.stringify(t._licenseServer)),s=t._sessionPassword,o=0;if(r.startsWith("t")||r.startsWith("f"))o=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))o=1;else{o=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t;try{let e=r.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===n.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),n=_(e)}!s&&t.sessionPassword&&(s=t.sessionPassword),e=t.remark}("200001"===r||r.startsWith("200001-"))&&(n&&n.length||(r="")),r||(o=1)}if(o&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==o)throw new Error(i);o=0,console.warn(i),t._lastErrorCode=-1,t._lastErrorString=i}return 1===o&&(r="",console.warn("Applying for a public trial license ...")),{lt:o,l:r,ls:n,sp:s,rmk:e}}throw new Error("Can't preprocess license again"+d)})(L);this._pLoad.task=async(s,a)=>{let h=L.engineResourcePath+L._workerName;L.engineResourcePath.startsWith(location.origin)||(h=await fetch(h).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),L._dbrWorker=new Worker(h),L._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},L._dbrWorker.onmessage=async t=>{let i=t.data?t.data:t;switch(i.type){case"log":L._onLog&&L._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0,i.message||(i.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),i.success?(L._dbrWorker.onerror=null,L._version=i.version+"(JS "+L._jsVersion+"."+L._jsEditVersion+")",L._onLog&&L._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(t=new Error(i.message),t.stack=i.stack+"\n"+t.stack,t.ltsErrorCode=i.ltsErrorCode,r||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&L.showDialog(i.success?"warn":"error",i.message),i.success?s():a(t);break}case"task":{let e=i.id,t=i.body;try{L._taskCallbackMap.get(e)(t),L._taskCallbackMap.delete(e)}catch(t){throw L._taskCallbackMap.delete(e),t}break}default:L._onLog&&L._onLog(t)}},L._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:L.engineResourcePath,bUseFullFeature:L._bUseFullFeature,bd:L._bWasmDebug,v:L._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:o,fn:L.deviceFriendlyName,ls:i,sp:r,rmk:n})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,i)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let e=0;e{if(e==t.target){a.remove();for(let e of o)e.remove()}}));else if(!l&&e.classList.contains("dls-license-icon-close"))l=e,e.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!d&&e.classList.contains("dls-license-msg-content")){d=e;let t=i;for(;t;){let i=t.indexOf("["),r=t.indexOf("]",i),n=t.indexOf("(",r),s=t.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){e.appendChild(new Text(t));break}i>0&&e.appendChild(new Text(t.substring(0,i)));let o=document.createElement("a"),a=t.substring(i+1,r);o.innerText=a;let h=t.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),e.appendChild(o),t=t.substring(s+1)}}document.body.appendChild(a)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await L.loadWasm(),await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new L;return e._instanceID=await L.createInstanceInWorker(),L._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){L._onLog&&L._onLog("decode(source: any)"),L._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):L.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):L.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,i,r,n,s,o){return await new Promise(((a,h)=>{let l=L._nextTaskID++;L._taskCallbackMap.set(l,(e=>{if(e.success){let t,i=L._onLog?Date.now():0;L._onLog&&L._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return h(e)}if(L._onLog){let e=Date.now();L._onLog("DBR getting message from worker timestamp: "+i),L._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),L._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),L._onLog("Handling results from DBR worker costs: "+(e-i)),L._onLog("Total decoding image costs: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}})),this._timeEnterInnerDBR=Date.now(),L._onLog&&L._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),L._dbrWorker.postMessage({type:"decodeBuffer",id:l,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,orientation:s,config:o}},[e.buffer]),L._onLog&&o&&o.timeStamp&&L._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s,o){L._onLog&&L._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,i,r,n,s,o)}async decodeBuffer(e,t,i,r,n,s,o){let a;return L._onLog&&L._onLog("decodeBuffer(buffer,width,height,stride,format)"),L._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,i,r,n,s,o):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,r,n,s,o):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,i,r,n,s,o)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success){let t=JSON.parse(i.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let i;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=3,i.expectedBarcodesCount=0,i.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=5,i.expectedBarcodesCount=512,i.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=9,i.expectedBarcodesCount=0,i.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=3,i.expectedBarcodesCount=0,i.localizationModes=[2,8,0,0,0,0,0,0]}else i=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(i=JSON.parse(JSON.stringify(t)),i.region instanceof Array){let e=i.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(i.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!L._bUseFullFeature){if(0!=(i.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=i.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=i.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=i.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,i.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(i.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,t)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(i=>{if(i.success){try{this._handleRetJsonString(i.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(i)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=F,await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=F,await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!L._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!L._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){i(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){L._onLog&&L._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(r=await function(e){return new Promise(((t,i)=>{let r=URL.createObjectURL(e),n=new Image;n.dbrObjUrl=r,n.src=r,n.onload=()=>{t(n)},n.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let n=await this._decode_Image(i||r,t);return i&&i.close(),n}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){L._onLog&&L._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let i,r,n=e instanceof HTMLImageElement?e.naturalWidth:e.width,s=e instanceof HTMLImageElement?e.naturalHeight:e.height,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(a,t)}async _decode_Canvas(t,i){if(L._onLog&&L._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let r=(t.ctx2d||t.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(r,t.width,t.height,4*t.width,e.EnumImagePixelFormat.IPF_ABGR_8888,0,i)}async _decode_Video(e,t){if(L._onLog&&L._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let i,r,n=e.videoWidth,s=e.videoHeight,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),await this._decode_Canvas(a,t)}async _decode_DCEFrame(t,i){if(L._onLog&&L._onLog("_decode_DCEFrame(dceFrame)"),!L.isDCEFrame(t))return[];let r=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:n,height:s,colorMode:o,pixelFormat:a,stride:h,timeStamp:l}=t;let c;c=i&&i.bCopyData?new Uint8Array(t.data):t.data;let u=null;if(i?(u=JSON.parse(JSON.stringify(i)),u.timeStamp=l):u={timeStamp:l},a&&h)if("grey"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,h,e.EnumImagePixelFormat.IPF_GrayScaled,0,u);else if("rgba"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,h,e.EnumImagePixelFormat.IPF_ABGR_8888,0,u);else{if("bgra"!==a)throw new Error(`Pixel format '${a}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(c,n,s,h,e.EnumImagePixelFormat.IPF_ARGB_8888,0,u)}else if("grey"===o)r=await this._decodeBuffer_Uint8Array(c,n,s,n,e.EnumImagePixelFormat.IPF_GrayScaled,0,u);else if("rgba"===o)r=await this._decodeBuffer_Uint8Array(c,n,s,4*n,e.EnumImagePixelFormat.IPF_ABGR_8888,0,u);else{if("bgra"!==o)throw new Error(`Color mode '${o}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(c,n,s,4*n,e.EnumImagePixelFormat.IPF_ARGB_8888,0,u)}return r}async _decode_DSImage(t,i){if(L._onLog&&L._onLog("_decode_DSImage(dsImage)"),!L.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,t)}}async _decode_FilePath(e,t){throw L._onLog&&L._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,i,r,n,s,o){if(e.length>0)for(let a of e){let e=a.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*s,e.x2*=.01*s,e.x3*=.01*s,e.x4*=.01*s,e.y1*=.01*o,e.y2*=.01*o,e.y3*=.01*o,e.y4*=.01*o);let h=s/r,l=o/n;e.x1=e.x1/h+t,e.x2=e.x2/h+t,e.x3=e.x3/h+t,e.x4=e.x4/h+t,e.y1=e.y1/l+i,e.y2=e.y2/l+i,e.y3=e.y3/l+i,e.y4=e.y4/l+i,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/n,e.y2*=100/n,e.y3*=100/n,e.y4*=100/n)}}static BarcodeReaderException(t,i){let r,n=e.EnumErrorCode.DBR_UNKNOWN;return"number"==typeof t?(n=t,r=new Error(i)):r=new Error(t),r.code=n,r}_handleRetJsonString(t){let i=e.EnumErrorCode;if(t.textResults){for(let e=0;e{let i=t.indexOf(":");e[t.substring(0,i)]=t.substring(i+1)})),i.exception=e}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!L._setWarnnedEx.has(t.description)&&(L._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==i.DBR_SUCCESS)return t.data;throw L.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=L._nextTaskID++;L._taskCallbackMap.set(o,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return s(e)}return n()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),L._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:r}})}))}async getModeArgument(e,t,i){return await new Promise(((r,n)=>{let s=L._nextTaskID++;L._taskCallbackMap.set(s,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return n(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),L._dbrWorker.postMessage({type:"getModeArgument",id:s,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),i=[];for(let r of t)if(r.dataType==e.EnumIMResultDataType.IMRDT_IMAGE)for(let t of r.results){const r=t.bytes;let n;switch(L._onLog&&L._onLog(" "+r.length+" "+r.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case e.EnumImagePixelFormat.IPF_ABGR_8888:n=new Uint8ClampedArray(r);break;case e.EnumImagePixelFormat.IPF_RGB_888:{const e=r.length/3;n=new Uint8ClampedArray(4*e);for(let t=0;t=i)break;n[o]=n[o+1]=n[o+2]=(128&e)/128*255,n[o+3]=255,e<<=1}}break}default:console.warn("unknow intermediate image",t)}if(!n)continue;let s=new ImageData(n,t.width,t.height),o=document.createElement("canvas");o.width=t.width,o.height=t.height,o.getContext("2d").putImageData(s,0,0),i.push(o)}return i}async getScanSettings(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success){let t=i.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t.autoZoom=this.autoZoom,t.autoFocus=this.autoFocus,t.autoSuggestTip=this.autoSuggestTip,e(t)}{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),L._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(t){if(!t)return;const i=JSON.parse(JSON.stringify(t));if(i.autoZoom||i.autoFocus||i.autoSuggestTip){if(!L._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const t=await this.getRuntimeSettings();t.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(t)}return i.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(i.intervalTime,0),delete i.intervalTime),i.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=i.whenToPlaySoundforSuccessfulRead,delete i.whenToPlaySoundforSuccessfulRead),i.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=i.soundOnSuccessfullRead,delete i.soundOnSuccessfullRead),i.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=i.whenToVibrateforSuccessfulRead,delete i.whenToVibrateforSuccessfulRead),i.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=i.vibrateDuration,delete i.vibrateDuration),i.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=i.captureAndDecodeInParallel,delete i.captureAndDecodeInParallel),i.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=i.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=i.autoZoom,delete i.autoZoom),i.hasOwnProperty("autoFocus")&&(this.autoFocus=i.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete i.autoFocus),i.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=i.autoSuggestTip,delete i.autoFocus),await new Promise(((e,t)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),L._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:i}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let i of e)t.push(this._cloneDecodeResults(i));return t}{let t=e,i=JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return L._onLog&&L._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));L._onLog&&L._onLog("======= once read ======="),L._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!L.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return L._onLog&&L._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(e){i=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(i&&i.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:h}=e;t=i.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(t,r,n,a,h,s,o)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t,i),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else t&&(i=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return i})().then((e=>{if(L._onLog&&L._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const i=()=>{let i=0;if(t&&t.length){let r=Math.min(...e),n=Math.max(...t);r&&n&&(i=r-n)}else i=0;return i>0?i:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),L._onLog&&L._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(L._onLog&&L._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};t(e)}else L._onLog&&L._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e,t){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const i=this._dbrDrawingLayer;e||(e=[]);let r=this._arrPolygons;for(let n=0;n{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(t),t}stopScanning(e){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[e]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(e){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(L._onLog&&L._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let e=L._nextTaskID++;L._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),L._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}L._jsVersion="9.6.10",L._jsEditVersion="20230213",L._version=`loading...(JS ${L._jsVersion}.${L._jsEditVersion})`,L._license=f,L._sessionPassword=g,L.browserInfo=o,L._workerName=`dbr-${L._jsVersion}.browser.worker.js`,L._engineResourcePath=u,L._licenseServer=[],L._deviceFriendlyName="",L._isShowRelDecodeTimeInResults=!1,L._bWasmDebug=!1,L._bNeverShowDialog=!1,L.__bUseFullFeature=!0,L._nextTaskID=0,L._taskCallbackMap=new Map,L._pLoad=new b,L._lastErrorCode=0,L._lastErrorString="",L._setWarnnedEx=new Set,L._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var P={653:(e,t,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,_,p,m,v,y,S,C,b,w,x=x||{version:"5.2.1"};if(t.fabric=x,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?x.document=document:x.document=document.implementation.createHTMLDocument(""),x.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;x.document=T.document,x.jsdomImplForWrapper=i(898).implForWrapper,x.nodeCanvas=i(245).Canvas,x.window=T,DOMParser=x.window.DOMParser}function E(e,t){var i=e.canvas,r=t.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function I(e,t){var i=t.targetCanvas.getContext("2d"),r=t.destinationWidth,n=t.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}x.isTouchSupported="ontouchstart"in x.window||"ontouchstart"in x.document||x.window&&x.window.navigator&&x.window.navigator.maxTouchPoints>0,x.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,x.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],x.DPI=96,x.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",x.commaWsp="(?:\\s+,?\\s*|,\\s*)",x.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,x.reNonWord=/[ \n\.,;!\?\-]/,x.fontPaths={},x.iMatrix=[1,0,0,1,0,0],x.svgNS="http://www.w3.org/2000/svg",x.perfLimitSizeTotal=2097152,x.maxCacheSideLimit=4096,x.minCacheSideLimit=256,x.charWidthsCache={},x.textureSize=2048,x.disableStyleCopyPaste=!1,x.enableGLFiltering=!0,x.devicePixelRatio=x.window.devicePixelRatio||x.window.webkitDevicePixelRatio||x.window.mozDevicePixelRatio||1,x.browserShadowBlurConstant=1,x.arcToSegmentsCache={},x.boundsOfCurveCache={},x.cachesBoundsOfCurve=!0,x.forceGLPutImageData=!1,x.initFilterBackend=function(){return x.enableGLFiltering&&x.isWebglSupported&&x.isWebglSupported(x.textureSize)?(console.log("max texture size: "+x.maxTextureSize),new x.WebglFilterBackend({tileSize:x.textureSize})):x.Canvas2dFilterBackend?new x.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=x),function(){function e(e,t){if(this.__eventListeners[e]){var i=this.__eventListeners[e];t?i[i.indexOf(t)]=!1:x.util.array.fill(i,!1)}}function t(e,t){var i=function(){t.apply(this,arguments),this.off(e,i)}.bind(this);this.on(e,i)}x.Observable={fire:function(e,t){if(!this.__eventListeners)return this;var i=this.__eventListeners[e];if(!i)return this;for(var r=0,n=i.length;r-1||!!t&&this._objects.some((function(t){return"function"==typeof t.contains&&t.contains(e,!0)}))},complexity:function(){return this._objects.reduce((function(e,t){return e+(t.complexity?t.complexity():0)}),0)}},x.CommonMethods={_setOptions:function(e){for(var t in e)this.set(t,e[t])},_initGradient:function(e,t){!e||!e.colorStops||e instanceof x.Gradient||this.set(t,new x.Gradient(e))},_initPattern:function(e,t,i){!e||!e.source||e instanceof x.Pattern?i&&i():this.set(t,new x.Pattern(e,i))},_setObject:function(e){for(var t in e)this._set(t,e[t])},set:function(e,t){return"object"==typeof e?this._setObject(e):this._set(e,t),this},_set:function(e,t){this[e]=t},toggle:function(e){var t=this.get(e);return"boolean"==typeof t&&this.set(e,!t),this},get:function(e){return this[e]}},r=t,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,x.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},sin:function(e){if(0===e)return 0;var t=1;switch(e<0&&(t=-1),e/h){case 1:return t;case 2:return 0;case 3:return-t}return Math.sin(e)},removeFromArray:function(e,t){var i=e.indexOf(t);return-1!==i&&e.splice(i,1),e},getRandomInt:function(e,t){return Math.floor(Math.random()*(t-e+1))+e},degreesToRadians:function(e){return e*a},radiansToDegrees:function(e){return e/a},rotatePoint:function(e,t,i){var r=new x.Point(e.x-t.x,e.y-t.y),n=x.util.rotateVector(r,i);return new x.Point(n.x,n.y).addEquals(t)},rotateVector:function(e,t){var i=x.util.sin(t),r=x.util.cos(t);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}},createVector:function(e,t){return new x.Point(t.x-e.x,t.y-e.y)},calcAngleBetweenVectors:function(e,t){return Math.acos((e.x*t.x+e.y*t.y)/(Math.hypot(e.x,e.y)*Math.hypot(t.x,t.y)))},getHatVector:function(e){return new x.Point(e.x,e.y).multiply(1/Math.hypot(e.x,e.y))},getBisector:function(e,t,i){var r=x.util.createVector(e,t),n=x.util.createVector(e,i),s=x.util.calcAngleBetweenVectors(r,n),o=s*(0===x.util.calcAngleBetweenVectors(x.util.rotateVector(r,s),n)?1:-1)/2;return{vector:x.util.getHatVector(x.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(e,t,i){var r=[],n=t.strokeWidth/2,s=t.strokeUniform?new x.Point(1/t.scaleX,1/t.scaleY):new x.Point(1,1),o=function(e){var t=n/Math.hypot(e.x,e.y);return new x.Point(e.x*t*s.x,e.y*t*s.y)};return e.length<=1||e.forEach((function(a,h){var l,c,u=new x.Point(a.x,a.y);0===h?(c=e[h+1],l=i?o(x.util.createVector(c,u)).addEquals(u):e[e.length-1]):h===e.length-1?(l=e[h-1],c=i?o(x.util.createVector(l,u)).addEquals(u):e[0]):(l=e[h-1],c=e[h+1]);var d,f,g=x.util.getBisector(u,l,c),_=g.vector,p=g.angle;if("miter"===t.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new x.Point(_.x*d*s.x,_.y*d*s.y),Math.hypot(f.x,f.y)/n<=t.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new x.Point(_.x*d*s.x,_.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(e,t,i){return i?new x.Point(t[0]*e.x+t[2]*e.y,t[1]*e.x+t[3]*e.y):new x.Point(t[0]*e.x+t[2]*e.y+t[4],t[1]*e.x+t[3]*e.y+t[5])},makeBoundingBoxFromPoints:function(e,t){if(t)for(var i=0;i0&&(t>r?t-=r:t=0,i>r?i-=r:i=0);var n,s=!0,o=e.getImageData(t,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(e,t,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(e,t,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=x.util.sin(c),d=x.util.cos(c),f=0,g=0,_=-d*e*.5-u*t*.5,p=-d*t*.5+u*e*.5,m=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,S=_*_,C=m*v-m*y-v*S,b=0;if(C<0){var w=Math.sqrt(1-C/(m*v));i*=w,s*=w}else b=(o===a?-1:1)*Math.sqrt(C/(m*y+v*S));var T=b*i*p/s,E=-b*s*_/i,I=d*T-u*E+.5*e,A=u*T+d*E+.5*t,O=n(1,0,(_-T)/i,(p-E)/s),R=n((_-T)/i,(p-E)/s,(-_-T)/i,(-p-E)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var D=Math.ceil(Math.abs(R/l*2)),M=[],F=R/D,L=8/3*Math.sin(F/4)*Math.sin(F/4)/Math.sin(F/2),P=O+F,k=0;kb)for(var T=1,E=_.length;T2;for(t=t||0,l&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,h=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+h*t]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(t,i,r,n,s,o,a,h){var l;if(x.cachesBoundsOfCurve&&(l=e.call(arguments),x.boundsOfCurveCache[l]))return x.boundsOfCurveCache[l];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,C=Math.abs,b=[],w=[[],[]];u=6*t-12*r+6*s,c=-3*t+9*r-9*s+3*a,d=3*r-3*t;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&b.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&b.push(g),0<(_=(-u-m)/(2*c))&&_<1&&b.push(_));for(var E,I,A,O=b.length,R=O;O--;)E=(A=1-(f=b[O]))*A*A*t+3*A*A*f*r+3*A*f*f*s+f*f*f*a,w[0][O]=E,I=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,w[1][O]=I;w[0][R]=t,w[1][R]=i,w[0][R+1]=a,w[1][R+1]=h;var D=[{x:y.apply(null,w[0]),y:y.apply(null,w[1])},{x:S.apply(null,w[0]),y:S.apply(null,w[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=D),D},x.util.getPointOnPath=function(e,t,i){i||(i=d(e));for(var r=0;t-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>t?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,t)}},x.util.transformPath=function(e,t,i){return i&&(t=x.util.multiplyTransformMatrices(t,[1,0,0,1,-i.x,-i.y])),e.map((function(e){for(var i=e.slice(0),r={},n=1;n=t}))}}}(),function(){function e(t,i,r){if(r)if(!x.isLikelyNode&&i instanceof Element)t=i;else if(i instanceof Array){t=[];for(var n=0,s=i.length;n57343)return e.charAt(t);if(55296<=i&&i<=56319){if(e.length<=t+1)throw"High surrogate without following low surrogate";var r=e.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return e.charAt(t)+e.charAt(t+1)}if(0===t)throw"Low surrogate without preceding high surrogate";var n=e.charCodeAt(t-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}x.util.string={camelize:function(e){return e.replace(/-+(.)?/g,(function(e,t){return t?t.toUpperCase():""}))},capitalize:function(e,t){return e.charAt(0).toUpperCase()+(t?e.slice(1):e.slice(1).toLowerCase())},escapeXml:function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(t){var i,r=0,n=[];for(r=0;r-1?e.prototype[n]=function(e){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=t[e].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==e)return n}}(n):e.prototype[n]=t[n],i&&(t.toString!==Object.prototype.toString&&(e.prototype.toString=t.toString),t.valueOf!==Object.prototype.valueOf&&(e.prototype.valueOf=t.valueOf))};function n(){}function s(t){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[t];if(r[t]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,e.call(arguments,1)):i.call(this):console.log("tried to callSuper "+t+", method not found in prototype chain",this)}x.util.createClass=function(){var i=null,o=e.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===e.pointerType},d="string"==typeof(u=x.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(e){return e},d?_=function(e,t){return e.style.opacity=t,e}:f&&(_=function(e,t){var i=e.style;return e.currentStyle&&!e.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(t=t>=.9999?"":"alpha(opacity="+100*t+")",i.filter=i.filter.replace(g,t)):i.filter+=" alpha(opacity="+100*t+")",e}),x.util.setStyle=function(e,t){var i=e.style;if(!i)return e;if("string"==typeof t)return e.style.cssText+=";"+t,t.indexOf("opacity")>-1?_(e,t.match(/opacity:\s*(\d?\.?\d*)/)[1]):e;for(var r in t)"opacity"===r?_(e,t[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=t[r];return e},function(){var e,t,i,r,n=Array.prototype.slice,s=function(e){return n.call(e,0)};try{e=s(x.document.childNodes)instanceof Array}catch(e){}function o(e,t){var i=x.document.createElement(e);for(var r in t)"class"===r?i.className=t[r]:"for"===r?i.htmlFor=t[r]:i.setAttribute(r,t[r]);return i}function a(e){for(var t=0,i=0,r=x.document.documentElement,n=x.document.body||{scrollLeft:0,scrollTop:0};e&&(e.parentNode||e.host)&&((e=e.parentNode||e.host)===x.document?(t=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(t+=e.scrollLeft||0,i+=e.scrollTop||0),1!==e.nodeType||"fixed"!==e.style.position););return{left:t,top:i}}e||(s=function(e){for(var t=new Array(e.length),i=e.length;i--;)t[i]=e[i];return t}),t=x.document.defaultView&&x.document.defaultView.getComputedStyle?function(e,t){var i=x.document.defaultView.getComputedStyle(e,null);return i?i[t]:void 0}:function(e,t){var i=e.style[t];return!i&&e.currentStyle&&(i=e.currentStyle[t]),i},i=x.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",x.util.makeElementUnselectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=x.util.falseFunction),r?e.style[r]="none":"string"==typeof e.unselectable&&(e.unselectable="on"),e},x.util.makeElementSelectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=null),r?e.style[r]="":"string"==typeof e.unselectable&&(e.unselectable=""),e},x.util.setImageSmoothing=function(e,t){e.imageSmoothingEnabled=e.imageSmoothingEnabled||e.webkitImageSmoothingEnabled||e.mozImageSmoothingEnabled||e.msImageSmoothingEnabled||e.oImageSmoothingEnabled,e.imageSmoothingEnabled=t},x.util.getById=function(e){return"string"==typeof e?x.document.getElementById(e):e},x.util.toArray=s,x.util.addClass=function(e,t){e&&-1===(" "+e.className+" ").indexOf(" "+t+" ")&&(e.className+=(e.className?" ":"")+t)},x.util.makeElement=o,x.util.wrapElement=function(e,t,i){return"string"==typeof t&&(t=o(t,i)),e.parentNode&&e.parentNode.replaceChild(t,e),t.appendChild(e),t},x.util.getScrollLeftTop=a,x.util.getElementOffset=function(e){var i,r,n=e&&e.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(t(e,l),10)||0;return i=n.documentElement,void 0!==e.getBoundingClientRect&&(s=e.getBoundingClientRect()),r=a(e),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},x.util.getNodeCanvas=function(e){var t=x.jsdomImplForWrapper(e);return t._canvas||t._image},x.util.cleanUpJsdomNode=function(e){if(x.isLikelyNode){var t=x.jsdomImplForWrapper(e);t&&(t._image=null,t._canvas=null,t._currentSrc=null,t._attributes=null,t._classList=null)}}}(),function(){function e(){}x.util.request=function(t,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new x.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=e)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(t=function(e,t){return e+(/\?/.test(e)?"&":"?")+t}(t,i.parameters))),s.open(r,t,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),x.log=console.log,x.warn=console.warn,function(){var e=x.util.object.extend,t=x.util.object.clone,i=[];function r(){return!1}function n(e,t,i,r){return-i*Math.cos(e/r*(Math.PI/2))+i+t}x.util.object.extend(i,{cancelAll:function(){var e=this.splice(0);return e.forEach((function(e){e.cancel()})),e},cancelByCanvas:function(e){if(!e)return[];var t=this.filter((function(t){return"object"==typeof t.target&&t.target.canvas===e}));return t.forEach((function(e){e.cancel()})),t},cancelByTarget:function(e){var t=this.findAnimationsByTarget(e);return t.forEach((function(e){e.cancel()})),t},findAnimationIndex:function(e){return this.indexOf(this.findAnimation(e))},findAnimation:function(e){return this.find((function(t){return t.cancel===e}))},findAnimationsByTarget:function(e){return e?this.filter((function(t){return t.target===e})):[]}});var s=x.window.requestAnimationFrame||x.window.webkitRequestAnimationFrame||x.window.mozRequestAnimationFrame||x.window.oRequestAnimationFrame||x.window.msRequestAnimationFrame||function(e){return x.window.setTimeout(e,1e3/60)},o=x.window.cancelAnimationFrame||x.window.clearTimeout;function a(){return s.apply(x.window,arguments)}x.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var e=x.runningAnimations.indexOf(s);return e>-1&&x.runningAnimations.splice(e,1)[0]};return s=e(t(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(s),a((function(e){var t,l=e||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||n,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(e,t){return v[t]-m[t]})):v-m);i.onStart&&i.onStart(),function e(i){var r=(t=i||+new Date)>u?c:t-l,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),C=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=C,s.durationRate=n,!o){if(!f(S,C,n))return t>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(S,C,n),void a(e));h()}}(l)})),s.cancel},x.util.requestAnimFrame=a,x.util.cancelAnimFrame=function(){return o.apply(x.window,arguments)},x.runningAnimations=i}(),function(){function e(e,t,i){var r="rgba("+parseInt(e[0]+i*(t[0]-e[0]),10)+","+parseInt(e[1]+i*(t[1]-e[1]),10)+","+parseInt(e[2]+i*(t[2]-e[2]),10);return(r+=","+(e&&t?parseFloat(e[3]+i*(t[3]-e[3])):1))+")"}x.util.animateColor=function(t,i,r,n){var s=new x.Color(t).getSource(),o=new x.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},x.util.animate(x.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(t,i,r,s){return e(i,r,n.colorEasing?n.colorEasing(t,s):1-Math.cos(t/s*(Math.PI/2)))},onComplete:function(t,i,r){if(a)return a(e(o,o,0),i,r)},onChange:function(t,i,r){if(h){if(Array.isArray(t))return h(e(t,t,0),i,r);h(t,i,r)}}}))}}(),function(){function e(e,t,i,r){return e-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===e||"xlink:href"===e||"font"===e)return i;if("imageSmoothing"===e)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(e){return new RegExp("^("+e.join("|")+")\\b","i")}function g(e,t){var i,r,n,s,o=[];for(n=0,s=t.length;n1;)h.shift(),l=t.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*$");function y(e){if(!t.svgViewBoxElementsRegEx.test(e.nodeName))return{};var i,r,n,o,a,h,l=e.getAttribute("viewBox"),c=1,u=1,d=e.getAttribute("width"),f=e.getAttribute("height"),g=e.getAttribute("x")||0,_=e.getAttribute("y")||0,p=e.getAttribute("preserveAspectRatio")||"",m=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,C={},b="",w=0,x=0;if(C.width=0,C.height=0,C.toBeParsed=S,m&&(g||_)&&e.parentNode&&"#document"!==e.parentNode.nodeName&&(b=" translate("+s(g)+" "+s(_)+") ",a=(e.getAttribute("transform")||"")+b,e.setAttribute("transform",a),e.removeAttribute("x"),e.removeAttribute("y")),S)return C;if(m)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=r,C.viewBoxWidth=n,C.viewBoxHeight=o,y?(C.width=n,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/n,u=C.height/o),"none"!==(p=t.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),w=C.width-n*c,x=C.height-o*c,"Mid"===p.alignX&&(w/=2),"Mid"===p.alignY&&(x/=2),"Min"===p.alignX&&(w=0),"Min"===p.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return C;if((g||_)&&"#document"!==e.parentNode.nodeName&&(b=" translate("+s(g)+" "+s(_)+") "),a=b+" matrix("+c+" 0 0 "+u+" "+(i*c+w)+" "+(r*u+x)+") ","svg"===e.nodeName){for(h=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)h.appendChild(e.firstChild);e.appendChild(h)}else(h=e).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function S(e,t){var i="xlink:href",r=m(e,t.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(e,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(e){r&&!t.hasAttribute(e)&&r.hasAttribute(e)&&t.setAttribute(e,r.getAttribute(e))})),!t.children.length)for(var n=r.cloneNode(!0);n.firstChild;)t.appendChild(n.firstChild);t.removeAttribute(i)}t.parseSVGDocument=function(e,i,n,s){if(e){!function(e){for(var i=g(e,["use","svg:use"]),r=0;i.length&&re.x&&this.y>e.y},gte:function(e){return this.x>=e.x&&this.y>=e.y},lerp:function(e,t){return void 0===t&&(t=.5),t=Math.max(Math.min(1,t),0),new i(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)},distanceFrom:function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},midPointFrom:function(e){return this.lerp(e)},min:function(e){return new i(Math.min(this.x,e.x),Math.min(this.y,e.y))},max:function(e){return new i(Math.max(this.x,e.x),Math.max(this.y,e.y))},toString:function(){return this.x+","+this.y},setXY:function(e,t){return this.x=e,this.y=t,this},setX:function(e){return this.x=e,this},setY:function(e){return this.y=e,this},setFromPoint:function(e){return this.x=e.x,this.y=e.y,this},swap:function(e){var t=this.x,i=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=i},clone:function(){return new i(this.x,this.y)}})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){this.status=e,this.points=[]}t.Intersection?t.warn("fabric.Intersection is already defined"):(t.Intersection=i,t.Intersection.prototype={constructor:i,appendPoint:function(e){return this.points.push(e),this},appendPoints:function(e){return this.points=this.points.concat(e),this}},t.Intersection.intersectLineLine=function(e,r,n,s){var o,a=(s.x-n.x)*(e.y-n.y)-(s.y-n.y)*(e.x-n.x),h=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),l=(s.y-n.y)*(r.x-e.x)-(s.x-n.x)*(r.y-e.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new t.Point(e.x+c*(r.x-e.x),e.y+c*(r.y-e.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},t.Intersection.intersectLinePolygon=function(e,t,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},t.Intersection.intersectPolygonPolygon=function(e,t){var r,n=new i,s=e.length;for(r=0;r0&&(n.status="Intersection"),n},t.Intersection.intersectPolygonRectangle=function(e,r,n){var s=r.min(n),o=r.max(n),a=new t.Point(o.x,s.y),h=new t.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,e),c=i.intersectLinePolygon(a,o,e),u=i.intersectLinePolygon(o,h,e),d=i.intersectLinePolygon(h,s,e),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){e?this._tryParsingColor(e):this.setSource([0,0,0,1])}function r(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}t.Color?t.warn("fabric.Color is already defined."):(t.Color=i,t.Color.prototype={_tryParsingColor:function(e){var t;e in i.colorNameMap&&(e=i.colorNameMap[e]),"transparent"===e&&(t=[255,255,255,0]),t||(t=i.sourceFromHex(e)),t||(t=i.sourceFromRgb(e)),t||(t=i.sourceFromHsl(e)),t||(t=[0,0,0,1]),t&&this.setSource(t)},_rgbToHsl:function(e,i,r){e/=255,i/=255,r/=255;var n,s,o,a=t.util.array.max([e,i,r]),h=t.util.array.min([e,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case e:n=(i-r)/l+(i0)-(e<0)||+e};function f(e,t){var i=e.angle+u(Math.atan2(t.y,t.x))+360;return Math.round(i%360/45)}function g(e,i){var r=i.transform.target,n=r.canvas,s=t.util.object.clone(i);s.target=r,n&&n.fire("object:"+e,s),r.fire(e,i)}function _(e,t){var i=t.canvas,r=e[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(e){return e.originX===l&&e.originY===l}function m(e,t,i){var r=e.lockScalingX,n=e.lockScalingY;return!((!r||!n)&&(t||!r&&!n||!i)&&(!r||"x"!==t)&&(!n||"y"!==t))}function v(e,t,i,r){return{e,transform:t,pointer:{x:i,y:r}}}function y(e){return function(t,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=e(t,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function S(e,t){return function(i,r,n,s){var o=t(i,r,n,s);return o&&g(e,v(i,r,n,s)),o}}function C(e,i,r,n,s){var o=e.target,a=o.controls[e.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new t.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function b(e){return e.flipX!==e.flipY}function w(e,t,i,r,n){if(0!==e[t]){var s=n/e._getTransformedDimensions()[r]*e[i];e.set(i,s)}}function x(e,t,i,r){var n,l=t.target,c=l._getTransformedDimensions(0,l.skewY),d=C(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),t.originX===s&&t.originY===h&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),b(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().y;l.set("skewX",n),w(l,"skewY","scaleY","y",p)}return _}function T(e,t,i,r){var n,l=t.target,c=l._getTransformedDimensions(l.skewX,0),d=C(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),t.originX===s&&t.originY===h&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),b(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().x;l.set("skewY",n),w(l,"skewX","scaleX","x",p)}return _}function E(e,t,i,r,n){n=n||{};var s,o,a,h,l,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),b=m(f,y,S),w=t.gestureScale;if(b)return!1;if(w)o=t.scaleX*w,a=t.scaleY*w;else{if(s=C(t,t.originX,t.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,t.signX||(t.signX=l),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==l||t.signY!==u))return!1;if(h=f._getTransformedDimensions(),S&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=t.original,E=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*E,a=T.scaleY*E}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(t)&&(o*=2,a*=2),t.signX!==l&&"y"!==y&&(t.originX=c[t.originX],o*=-1,t.signX=l),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.signY=u)}var I=f.scaleX,A=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),I!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(e,t,r){var n=_(e,r),s="";if(0!==t.x&&0===t.y?s="x":0===t.x&&0!==t.y&&(s="y"),m(r,s,n))return"not-allowed";var o=f(r,t);return i[o]+"-resize"},n.skewCursorStyleHandler=function(e,t,i){var n="not-allowed";if(0!==t.x&&i.lockSkewingY)return n;if(0!==t.y&&i.lockSkewingX)return n;var s=f(i,t)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(e,t,i){return e[i.canvas.altActionKey]?n.skewCursorStyleHandler(e,t,i):n.scaleCursorStyleHandler(e,t,i)},n.rotationWithSnapping=S("rotating",y((function(e,t,i,r){var n=t,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),b(h)&&(n=n===s?a:s)),t.originX=n,S("skewing",y(x))(e,t,i,r))},n.skewHandlerY=function(e,t,i,r){var n,a=t.target,c=a.skewY,u=t.originX;return!a.lockSkewingY&&(0===c?n=C(t,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),b(a)&&(n=n===o?h:o)),t.originY=n,S("skewing",y(T))(e,t,i,r))},n.dragHandler=function(e,t,i,r){var n=t.target,s=i-t.offsetX,o=r-t.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(e,t,i,r)),a||h},n.scaleOrSkewActionName=function(e,t,i){var r=e[i.canvas.altActionKey];return 0===t.x?r?"skewX":"scaleY":0===t.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(e,t,i){return i.lockRotation?"not-allowed":t.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=S,n.getLocalPoint=C,t.controlsUtils=n}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians,r=t.controlsUtils;r.renderCircleControl=function(e,t,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=t,d=i;e.save(),e.fillStyle=r.cornerColor||n.cornerColor,e.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,e.scale(1,a/o),d=i*o/a):a>o?(s=a,e.scale(o/a,1),u=t*a/o):s=o,e.lineWidth=1,e.beginPath(),e.arc(u,d,s/2,0,2*Math.PI,!1),e[l](),c&&e.stroke(),e.restore()},r.renderSquareControl=function(e,t,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;e.save(),e.fillStyle=n.cornerColor||s.cornerColor,e.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,e.lineWidth=1,e.translate(t,r),e.rotate(i(s.angle)),e[l+"Rect"](-u,-d,o,a),c&&e.strokeRect(-u,-d,o,a),e.restore()}}(t),function(e){var t=e.fabric||(e.fabric={});t.Control=function(e){for(var t in e)this[t]=e[t]},t.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(e,t){return t.cursorStyle},getActionName:function(e,t){return t.actionName},getVisibility:function(e,t){var i=e._controlsVisibility;return i&&void 0!==i[t]?i[t]:this.visible},setVisibility:function(e){this.visible=e},positionHandler:function(e,i){return t.util.transformPoint({x:this.x*e.x+this.offsetX,y:this.y*e.y+this.offsetY},i)},calcCornerCoords:function(e,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-t.util.degreesToRadians(e),_=Math.PI/2-d-t.util.degreesToRadians(e);o=f*t.util.cos(g),a=f*t.util.sin(g),h=f*t.util.cos(_),l=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),o=h=f*t.util.cos(g),a=l=f*t.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(e,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?t.controlsUtils.renderCircleControl.call(this,e,i,r,n,s):t.controlsUtils.renderSquareControl.call(this,e,i,r,n,s)}}}(t),function(){function e(e,t){var i,r,n,s,o=e.getAttribute("style"),a=e.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=e.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=e.getAttribute("stop-opacity")),r=(i=new x.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*t,{offset:a,color:i.toRgb(),opacity:n}}var t=x.util.object.clone;x.Gradient=x.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(e){e||(e={}),e.coords||(e.coords={});var t,i=this;Object.keys(e).forEach((function(t){i[t]=e[t]})),this.id?this.id+="_"+x.Object.__uid++:this.id=x.Object.__uid++,t={x1:e.coords.x1||0,y1:e.coords.y1||0,x2:e.coords.x2||0,y2:e.coords.y2||0},"radial"===this.type&&(t.r1=e.coords.r1||0,t.r2=e.coords.r2||0),this.coords=t,this.colorStops=e.colorStops.slice()},addColorStop:function(e){for(var t in e){var i=new x.Color(e[t]);this.colorStops.push({offset:parseFloat(t),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(e){var t={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return x.util.populateWithProperties(this,t,e),t},toSVG:function(e,i){var r,n,s,o,a=t(this.coords,!0),h=(i=i||{},t(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():x.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(e,t){return e.offset-t.offset})),"objectBoundingBox"===g?(u/=e.width,d/=e.height):(u+=e.width/2,d+=e.height/2),"path"===e.type&&"percentage"!==this.gradientUnits&&(u-=e.pathOffset.x,d-=e.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+x.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(e){var t,i,r,n=x.util.object.clone(this.coords);if(this.type){for("linear"===this.type?t=e.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(t=e.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=t.getElementsByTagName("stop"),u="userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage",d=t.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?(o="linear",a=function(e){return{x1:e.getAttribute("x1")||0,y1:e.getAttribute("y1")||0,x2:e.getAttribute("x2")||"100%",y2:e.getAttribute("y2")||0}}(t)):(o="radial",a=function(e){return{x1:e.getAttribute("fx")||e.getAttribute("cx")||"50%",y1:e.getAttribute("fy")||e.getAttribute("cy")||"50%",r1:0,x2:e.getAttribute("cx")||"50%",y2:e.getAttribute("cy")||"50%",r2:e.getAttribute("r")||"50%"}}(t)),h=c.length;h--;)f.push(e(c[h],s));return l=x.parseTransformAttribute(d),function(e,t,i,r){var n,s;Object.keys(t).forEach((function(e){"Infinity"===(n=t[e])?s=1:"-Infinity"===n?s=0:(s=parseFloat(t[e],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==e&&"x2"!==e&&"r2"!==e||(s*=i.viewBoxWidth||i.width),"y1"!==e&&"y2"!==e||(s*=i.viewBoxHeight||i.height)))),t[e]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,_=-i.top),new x.Gradient({id:t.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:_})}})}(),m=x.util.toFixed,x.Pattern=x.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(e,t){if(e||(e={}),this.id=x.Object.__uid++,this.setOptions(e),!e.source||e.source&&"string"!=typeof e.source)t&&t(this);else{var i=this;this.source=x.util.createImage(),x.util.loadImage(e.source,(function(e,r){i.source=e,t&&t(i,r)}),null,this.crossOrigin)}},toObject:function(e){var t,i,r=x.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?t=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(t=this.source.toDataURL()),i={type:"pattern",source:t,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},x.util.populateWithProperties(this,i,e),i},toSVG:function(e){var t="function"==typeof this.source?this.source():this.source,i=t.width/e.width,r=t.height/e.height,n=this.offsetX/e.width,s=this.offsetY/e.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),t.src?o=t.src:t.toDataURL&&(o=t.toDataURL()),'\n\n\n'},setOptions:function(e){for(var t in e)this[t]=e[t]},toLive:function(e){var t=this.source;if(!t)return"";if(void 0!==t.src){if(!t.complete)return"";if(0===t.naturalWidth||0===t.naturalHeight)return""}return e.createPattern(t,this.repeat)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.toFixed;t.Shadow?t.warn("fabric.Shadow is already defined."):(t.Shadow=t.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(e){for(var i in"string"==typeof e&&(e=this._parseShadow(e)),e)this[i]=e[i];this.id=t.Object.__uid++},_parseShadow:function(e){var i=e.trim(),r=t.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(t.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(e){var r=40,n=40,s=t.Object.NUM_FRACTION_DIGITS,o=t.util.rotateVector({x:this.offsetX,y:this.offsetY},t.util.degreesToRadians(-e.angle)),a=new t.Color(this.color);return e.width&&e.height&&(r=100*i((Math.abs(o.x)+this.blur)/e.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/e.height,s)+20),e.flipX&&(o.x*=-1),e.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var e={},i=t.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(t){this[t]!==i[t]&&(e[t]=this[t])}),this),e}}),t.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(t),function(){if(x.StaticCanvas)x.warn("fabric.StaticCanvas is already defined.");else{var e=x.util.object.extend,t=x.util.getElementOffset,i=x.util.removeFromArray,r=x.util.toFixed,n=x.util.transformPoint,s=x.util.invertTransform,o=x.util.getNodeCanvas,a=x.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");x.StaticCanvas=x.util.createClass(x.CommonMethods,{initialize:function(e,t){t||(t={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(e,t)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:x.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(e,t){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(e),this._initOptions(t),this.interactive||this._initRetinaScaling(),t.overlayImage&&this.setOverlayImage(t.overlayImage,i),t.backgroundImage&&this.setBackgroundImage(t.backgroundImage,i),t.backgroundColor&&this.setBackgroundColor(t.backgroundColor,i),t.overlayColor&&this.setOverlayColor(t.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return x.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,x.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var e=x.devicePixelRatio;this.__initRetinaScaling(e,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(e,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(e,t,i){t.setAttribute("width",this.width*e),t.setAttribute("height",this.height*e),i.scale(e,e)},calcOffset:function(){return this._offset=t(this.lowerCanvasEl),this},setOverlayImage:function(e,t,i){return this.__setBgOverlayImage("overlayImage",e,t,i)},setBackgroundImage:function(e,t,i){return this.__setBgOverlayImage("backgroundImage",e,t,i)},setOverlayColor:function(e,t){return this.__setBgOverlayColor("overlayColor",e,t)},setBackgroundColor:function(e,t){return this.__setBgOverlayColor("backgroundColor",e,t)},__setBgOverlayImage:function(e,t,i,r){return"string"==typeof t?x.util.loadImage(t,(function(t,n){if(t){var s=new x.Image(t,r);this[e]=s,s.canvas=this}i&&i(t,n)}),this,r&&r.crossOrigin):(r&&t.setOptions(r),this[e]=t,t&&(t.canvas=this),i&&i(t,!1)),this},__setBgOverlayColor:function(e,t,i){return this[e]=t,this._initGradient(t,e),this._initPattern(t,e,i),this},_createCanvasElement:function(){var e=a();if(!e)throw h;if(e.style||(e.style={}),void 0===e.getContext)throw h;return e},_initOptions:function(e){var t=this.lowerCanvasEl;this._setOptions(e),this.width=this.width||parseInt(t.width,10)||0,this.height=this.height||parseInt(t.height,10)||0,this.lowerCanvasEl.style&&(t.width=this.width,t.height=this.height,t.style.width=this.width+"px",t.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(e){e&&e.getContext?this.lowerCanvasEl=e:this.lowerCanvasEl=x.util.getById(e)||this._createCanvasElement(),x.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(e,t){return this.setDimensions({width:e},t)},setHeight:function(e,t){return this.setDimensions({height:e},t)},setDimensions:function(e,t){var i;for(var r in t=t||{},e)i=e[r],t.cssOnly||(this._setBackstoreDimension(r,e[r]),i+="px",this.hasLostContext=!0),t.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),t.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(e,t){return this.lowerCanvasEl[e]=t,this.upperCanvasEl&&(this.upperCanvasEl[e]=t),this.cacheCanvasEl&&(this.cacheCanvasEl[e]=t),this[e]=t,this},_setCssDimension:function(e,t){return this.lowerCanvasEl.style[e]=t,this.upperCanvasEl&&(this.upperCanvasEl.style[e]=t),this.wrapperEl&&(this.wrapperEl.style[e]=t),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(e){var t,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=e,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",t),this._setSVGObjects(i,t),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",t),i.push(""),i.join("")},_setSVGPreamble:function(e,t){t.suppressPreamble||e.push('\n','\n')},_setSVGHeader:function(e,t){var i,n=t.width||this.width,s=t.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=x.Object.NUM_FRACTION_DIGITS;t.viewBox?o='viewBox="'+t.viewBox.x+" "+t.viewBox.y+" "+t.viewBox.width+" "+t.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),e.push("\n',"Created with Fabric.js ",x.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(t),"\n")},createSVGClipPathMarkup:function(e){var t=this.clipPath;return t?(t.clipPathId="CLIPPATH_"+x.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(e.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var e=this;return["background","overlay"].map((function(t){var i=e[t+"Color"];if(i&&i.toLive){var r=e[t+"Vpt"],n=e.viewportTransform,s={width:e.width/(r?n[0]:1),height:e.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?x.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var e,t,i,r,n,s,o,a,h="",l={},c=x.fontPaths,u=[];for(this._objects.forEach((function e(t){u.push(t),t._objects&&t._objects.forEach(e)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(e,t){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else e.push('\n")},sendToBack:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(t=(n=s._objects).length;t--;)r=n[t],i(this._objects,r),this._objects.unshift(r);else i(this._objects,e),this._objects.unshift(e);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(n=s._objects,t=0;t0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(e))&&(o=this._findNewLowerIndex(e,s,t),i(this._objects,e),this._objects.splice(o,0,e));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(e,t,i){var r,n;if(i){for(r=t,n=t-1;n>=0;--n)if(e.intersectsWithObject(this._objects[n])||e.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(e)){r=n;break}}else r=t-1;return r},bringForward:function(e,t){if(!e)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(e===h&&"activeSelection"===e.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),e(x.StaticCanvas.prototype,x.Observable),e(x.StaticCanvas.prototype,x.Collection),e(x.StaticCanvas.prototype,x.DataURLExporter),e(x.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(e){var t=a();if(!t||!t.getContext)return null;var i=t.getContext("2d");return i&&"setLineDash"===e?void 0!==i.setLineDash:null}}),x.StaticCanvas.prototype.toJSON=x.StaticCanvas.prototype.toObject,x.isLikelyNode&&(x.StaticCanvas.prototype.createPNGStream=function(){var e=o(this.lowerCanvasEl);return e&&e.createPNGStream()},x.StaticCanvas.prototype.createJPEGStream=function(e){var t=o(this.lowerCanvasEl);return t&&t.createJPEGStream(e)})}}(),x.BaseBrush=x.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(e){e.strokeStyle=this.color,e.lineWidth=this.width,e.lineCap=this.strokeLineCap,e.miterLimit=this.strokeMiterLimit,e.lineJoin=this.strokeLineJoin,e.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(e){var t=this.canvas.viewportTransform;e.save(),e.transform(t[0],t[1],t[2],t[3],t[4],t[5])},_setShadow:function(){if(this.shadow){var e=this.canvas,t=this.shadow,i=e.contextTop,r=e.getZoom();e&&e._isRetinaScaling()&&(r*=x.devicePixelRatio),i.shadowColor=t.color,i.shadowBlur=t.blur*r,i.shadowOffsetX=t.offsetX*r,i.shadowOffsetY=t.offsetY*r}},needsFullRender:function(){return new x.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var e=this.canvas.contextTop;e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0},_isOutSideCanvas:function(e){return e.x<0||e.x>this.canvas.getWidth()||e.y<0||e.y>this.canvas.getHeight()}}),x.PencilBrush=x.util.createClass(x.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(e){this.canvas=e,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(e,t,i){var r=t.midPointFrom(i);return e.quadraticCurveTo(t.x,t.y,r.x,r.y),r},onMouseDown:function(e,t){this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],this._prepareForDrawing(e),this._captureDrawingPath(e),this._render())},onMouseMove:function(e,t){if(this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(e))&&this._captureDrawingPath(e)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(e){return!this.canvas._isMainEvent(e.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(e){var t=new x.Point(e.x,e.y);this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)},_addPoint:function(e){return!(this._points.length>1&&e.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(e),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(e){var t=new x.Point(e.x,e.y);return this._addPoint(t)},_render:function(e){var t,i,r=this._points[0],n=this._points[1];if(e=e||this.canvas.contextTop,this._saveAndTransform(e),e.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new x.Point(r.x,r.y),n=new x.Point(n.x,n.y),r.x-=s,n.x+=s}for(e.moveTo(r.x,r.y),t=1,i=this._points.length;t=n&&(o=e[i],a.push(o));return a.push(e[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var e=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(e))this.canvas.requestRenderAll();else{var t=this.createPath(e);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:t}),this.canvas.add(t),this.canvas.requestRenderAll(),t.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:t})}}}),x.CircleBrush=x.util.createClass(x.BaseBrush,{width:10,initialize:function(e){this.canvas=e,this.points=[]},drawDot:function(e){var t=this.addPoint(e),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,t),i.restore()},dot:function(e,t){e.fillStyle=t.fill,e.beginPath(),e.arc(t.x,t.y,t.radius,0,2*Math.PI,!1),e.closePath(),e.fill()},onMouseDown:function(e){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(e)},_render:function(){var e,t,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),e=0,t=r.length;e0&&!this.preserveObjectStacking){t=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),t.push.apply(t,i)}else t=this._objects;return t},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var e=this.contextContainer;return this.renderCanvas(e,this._chooseObjectsToRender()),this},renderTopLayer:function(e){e.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(e),this.contextTopDirty=!0),e.restore()},renderTop:function(){var e=this.contextTop;return this.clearContext(e),this.renderTopLayer(e),this.fire("after:render"),this},_normalizePointer:function(e,t){var i=e.calcTransformMatrix(),r=x.util.invertTransform(i),n=this.restorePointerVpt(t);return x.util.transformPoint(n,r)},isTargetTransparent:function(e,t,i){if(e.shouldCache()&&e._cacheCanvas&&e!==this._activeObject){var r=this._normalizePointer(e,{x:t,y:i}),n=Math.max(e.cacheTranslationX+r.x*e.zoomX,0),s=Math.max(e.cacheTranslationY+r.y*e.zoomY,0);return x.util.isTransparent(e._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=e.selectionBackgroundColor,h=this.viewportTransform;return e.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),e.render(o),o.restore(),e.selectionBackgroundColor=a,x.util.isTransparent(o,t,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(e){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(t){return!0===e[t]})):e[this.selectionKey]},_shouldClearSelection:function(e,t){var i=this.getActiveObjects(),r=this._activeObject;return!t||t&&r&&i.length>1&&-1===i.indexOf(t)&&r!==t&&!this._isSelectionKeyPressed(e)||t&&!t.evented||t&&!t.selectable&&r&&r!==t},_shouldCenterTransform:function(e,t,i){var r;if(e)return"scale"===t||"scaleX"===t||"scaleY"===t||"resizing"===t?r=this.centeredScaling||e.centeredScaling:"rotate"===t&&(r=this.centeredRotation||e.centeredRotation),r?!i:i},_getOriginFromCorner:function(e,t){var i={x:e.originX,y:e.originY};return"ml"===t||"tl"===t||"bl"===t?i.x="right":"mr"!==t&&"tr"!==t&&"br"!==t||(i.x="left"),"tl"===t||"mt"===t||"tr"===t?i.y="bottom":"bl"!==t&&"mb"!==t&&"br"!==t||(i.y="top"),i},_getActionFromCorner:function(e,t,i,r){if(!t||!e)return"drag";var n=r.controls[t];return n.getActionName(i,n,r)},_setupCurrentTransform:function(e,i,r){if(i){var n=this.getPointer(e),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(e,i,o):x.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,e,i),l=this._getOriginFromCorner(i,s),c=e[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:t(i.angle),width:i.width*i.scaleX,shiftKey:e.shiftKey,altKey:c,original:x.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(e)}},setCursor:function(e){this.upperCanvasEl.style.cursor=e},_drawSelection:function(e){var t=this._groupSelector,i=new x.Point(t.ex,t.ey),r=x.util.transformPoint(i,this.viewportTransform),n=new x.Point(t.ex+t.left,t.ey+t.top),s=x.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,x.Object.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(o,a,h-o,l-a))},findTarget:function(e,t){if(!this.skipTargetFind){var r,n,s=this.getPointer(e,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(e),l=a.length>1&&!t||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!t&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return e[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(e,t,i){if(t&&t.visible&&t.evented&&t.containsPoint(e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;if(!this.isTargetTransparent(t,i.x,i.y))return!0}},_searchPossibleTargets:function(e,t){for(var i,r,n=e.length;n--;){var s=e[n],o=s.group?this._normalizePointer(s.group,t):t;if(this._checkTarget(o,s,t)){(i=e[n]).subTargetCheck&&i instanceof x.Group&&(r=this._searchPossibleTargets(i._objects,t))&&this.targets.push(r);break}}return i},restorePointerVpt:function(e){return x.util.transformPoint(e,x.util.invertTransform(this.viewportTransform))},getPointer:function(t,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=e(t),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var e=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),t=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),x.util.addClass(i,"upper-canvas "+e),this.wrapperEl.appendChild(i),this._copyCanvasStyle(t,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=x.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),x.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),x.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(e){var t=this.width||e.width,i=this.height||e.height;x.util.setStyle(e,{position:"absolute",width:t+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),e.width=t,e.height=i,x.util.makeElementUnselectable(e)},_copyCanvasStyle:function(e,t){t.style.cssText=e.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var e=this._activeObject;return e?"activeSelection"===e.type&&e._objects?e._objects.slice(0):[e]:[]},_onObjectRemoved:function(e){e===this._activeObject&&(this.fire("before:selection:cleared",{target:e}),this._discardActiveObject(),this.fire("selection:cleared",{target:e}),e.fire("deselected")),e===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",e)},_fireSelectionEvents:function(e,t){var i=!1,r=this.getActiveObjects(),n=[],s=[];e.forEach((function(e){-1===r.indexOf(e)&&(i=!0,e.fire("deselected",{e:t,target:e}),s.push(e))})),r.forEach((function(r){-1===e.indexOf(r)&&(i=!0,r.fire("selected",{e:t,target:r}),n.push(r))})),e.length>0&&r.length>0?i&&this.fire("selection:updated",{e:t,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:t,selected:n}):e.length>0&&this.fire("selection:cleared",{e:t,deselected:s})},setActiveObject:function(e,t){var i=this.getActiveObjects();return this._setActiveObject(e,t),this._fireSelectionEvents(i,t),this},_setActiveObject:function(e,t){return this._activeObject!==e&&!!this._discardActiveObject(t,e)&&!e.onSelect({e:t})&&(this._activeObject=e,!0)},_discardActiveObject:function(e,t){var i=this._activeObject;if(i){if(i.onDeselect({e,object:t}))return!1;this._activeObject=null}return!0},discardActiveObject:function(e){var t=this.getActiveObjects(),i=this.getActiveObject();return t.length&&this.fire("before:selection:cleared",{target:i,e}),this._discardActiveObject(e),this._fireSelectionEvents(t,e),this},dispose:function(){var e=this.wrapperEl;return this.removeListeners(),e.removeChild(this.upperCanvasEl),e.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(e){x.util.cleanUpJsdomNode(this[e]),this[e]=void 0}.bind(this)),e.parentNode&&e.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,x.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(e){var t=this._activeObject;t&&t._renderControls(e)},_toObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(e),n=this.callSuper("_toObject",e,t,i);return this._unwindGroupTransformOnObject(e,r),n},_realizeGroupTransformOnObject:function(e){if(e.group&&"activeSelection"===e.group.type&&this._activeObject===e.group){var t={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){t[i]=e[i]})),x.util.addTransformToObject(e,this._activeObject.calcOwnMatrix()),t}return null},_unwindGroupTransformOnObject:function(e,t){t&&e.set(t)},_setSVGObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(t);this.callSuper("_setSVGObject",e,t,i),this._unwindGroupTransformOnObject(t,r)},setViewportTransform:function(e){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),x.StaticCanvas.prototype.setViewportTransform.call(this,e)}}),x.StaticCanvas)"prototype"!==r&&(x.Canvas[r]=x.StaticCanvas[r])}(),function(){var e=x.util.addListener,t=x.util.removeListener,i={passive:!1};function r(e,t){return e.button&&e.button===t-1}x.util.object.extend(x.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(e,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(e,t){var r=this.upperCanvasEl,n=this._getEventPrefix();e(x.window,"resize",this._onResize),e(r,n+"down",this._onMouseDown),e(r,n+"move",this._onMouseMove,i),e(r,n+"out",this._onMouseOut),e(r,n+"enter",this._onMouseEnter),e(r,"wheel",this._onMouseWheel),e(r,"contextmenu",this._onContextMenu),e(r,"dblclick",this._onDoubleClick),e(r,"dragover",this._onDragOver),e(r,"dragenter",this._onDragEnter),e(r,"dragleave",this._onDragLeave),e(r,"drop",this._onDrop),this.enablePointerEvents||e(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&t in eventjs&&(eventjs[t](r,"gesture",this._onGesture),eventjs[t](r,"drag",this._onDrag),eventjs[t](r,"orientation",this._onOrientationChange),eventjs[t](r,"shake",this._onShake),eventjs[t](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(t,"remove");var e=this._getEventPrefix();t(x.document,e+"up",this._onMouseUp),t(x.document,"touchend",this._onTouchEnd,i),t(x.document,e+"move",this._onMouseMove,i),t(x.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(e,t){this.__onTransformGesture&&this.__onTransformGesture(e,t)},_onDrag:function(e,t){this.__onDrag&&this.__onDrag(e,t)},_onMouseWheel:function(e){this.__onMouseWheel(e)},_onMouseOut:function(e){var t=this._hoveredTarget;this.fire("mouse:out",{target:t,e}),this._hoveredTarget=null,t&&t.fire("mouseout",{e});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:t,e}),r&&t.fire("mouseout",{e})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(e){e.isEditing&&e.hiddenTextarea.focus()}))},_onMouseEnter:function(e){this._currentTransform||this.findTarget(e)||(this.fire("mouse:over",{target:null,e}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(e,t){this.__onOrientationChange&&this.__onOrientationChange(e,t)},_onShake:function(e,t){this.__onShake&&this.__onShake(e,t)},_onLongPress:function(e,t){this.__onLongPress&&this.__onLongPress(e,t)},_onDragOver:function(e){e.preventDefault();var t=this._simpleEventHandler("dragover",e);this._fireEnterLeaveEvents(t,e)},_onDrop:function(e){return this._simpleEventHandler("drop:before",e),this._simpleEventHandler("drop",e)},_onContextMenu:function(e){return this.stopContextMenu&&(e.stopPropagation(),e.preventDefault()),!1},_onDoubleClick:function(e){this._cacheTransformEventData(e),this._handleEvent(e,"dblclick"),this._resetTransformEventData(e)},getPointerId:function(e){var t=e.changedTouches;return t?t[0]&&t[0].identifier:this.enablePointerEvents?e.pointerId:-1},_isMainEvent:function(e){return!0===e.isPrimary||!1!==e.isPrimary&&("touchend"===e.type&&0===e.touches.length||!e.changedTouches||e.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(x.document,"touchend",this._onTouchEnd,i),e(x.document,"touchmove",this._onMouseMove,i),t(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(n,s+"move",this._onMouseMove,i),e(x.document,s+"up",this._onMouseUp),e(x.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();t(x.document,"touchend",this._onTouchEnd,i),t(x.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){e(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(t(x.document,s+"up",this._onMouseUp),t(x.document,s+"move",this._onMouseMove,i),e(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(e){!this.allowTouchScrolling&&e.preventDefault&&e.preventDefault(),this.__onMouseMove(e)},_onResize:function(){this.calcOffset()},_shouldRender:function(e){var t=this._activeObject;return!!(!!t!=!!e||t&&e&&t!==e)||(t&&t.isEditing,!1)},__onMouseUp:function(e){var t,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(e),t=this._target,this._handleEvent(e,"up:before"),r(e,3))this.fireRightClick&&this._handleEvent(e,"up",3,o);else{if(r(e,2))return this.fireMiddleClick&&this._handleEvent(e,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(e);else if(this._isMainEvent(e)){if(i&&(this._finalizeCurrentTransform(e),s=i.actionPerformed),!o){var a=t===this._activeObject;this._maybeGroupObjects(e),s||(s=this._shouldRender(t)||!a&&t===this._activeObject)}var h,l;if(t){if(h=t._findTargetCorner(this.getPointer(e,!0),x.util.isTouchEvent(e)),t.selectable&&t!==this._activeObject&&"up"===t.activeOn)this.setActiveObject(t,e),s=!0;else{var c=t.controls[h],u=c&&c.getMouseUpHandler(e,t,c);u&&u(e,i,(l=this.getPointer(e)).x,l.y)}t.isMoving=!1}if(i&&(i.target!==t||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(e,t,c);l=l||this.getPointer(e),f&&f(e,i,l.x,l.y)}this._setCursorFromEvent(e,t),this._handleEvent(e,"up",1,o),this._groupSelector=null,this._currentTransform=null,t&&(t.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(e,t){var i=this.findTarget(t),r=this.targets,n={e:t,target:i,subTargets:r};if(this.fire(e,n),i&&i.fire(e,n),!r)return i;for(var s=0;s1&&(t=new x.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(t,e))},_collectObjects:function(e){for(var t,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new x.Point(v(r,s),v(n,o)),h=new x.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((t=this._objects[u])&&t.selectable&&t.visible&&(l&&t.intersectsWithRect(a,h,!0)||t.isContainedWithinRect(a,h,!0)||l&&t.containsPoint(a,null,!0)||l&&t.containsPoint(h,null,!0))&&(i.push(t),c)););return i.length>1&&(i=i.filter((function(t){return!t.onSelect({e})}))),i},_maybeGroupObjects:function(e){this.selection&&this._groupSelector&&this._groupSelectedObjects(e),this.setCursor(this.defaultCursor),this._groupSelector=null}}),x.util.object.extend(x.StaticCanvas.prototype,{toDataURL:function(e){e||(e={});var t=e.format||"png",i=e.quality||1,r=(e.multiplier||1)*(e.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,e);return x.util.toDataURL(n,t,i)},toCanvasElement:function(e,t){e=e||1;var i=((t=t||{}).width||this.width)*e,r=(t.height||this.height)*e,n=this.getZoom(),s=this.width,o=this.height,a=n*e,h=this.viewportTransform,l=(h[4]-(t.left||0))*e,c=(h[5]-(t.top||0))*e,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=x.util.createCanvasElement(),_=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=_,g}}),x.util.object.extend(x.StaticCanvas.prototype,{loadFromJSON:function(e,t,i){if(e){var r="string"==typeof e?JSON.parse(e):x.util.object.clone(e),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(e){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,e,o,t)})):n.__setupCanvas.call(n,r,e,o,t)}))}),i),this}},__setupCanvas:function(e,t,i,r){var n=this;t.forEach((function(e,t){n.insertAt(e,t)})),this.renderOnAddRemove=i,delete e.objects,delete e.backgroundImage,delete e.overlayImage,delete e.background,delete e.overlay,this._setOptions(e),this.renderAll(),r&&r()},_setBgOverlay:function(e,t){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(e.backgroundImage||e.overlayImage||e.background||e.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&t&&t()};this.__setBgOverlay("backgroundImage",e.backgroundImage,i,r),this.__setBgOverlay("overlayImage",e.overlayImage,i,r),this.__setBgOverlay("backgroundColor",e.background,i,r),this.__setBgOverlay("overlayColor",e.overlay,i,r)}else t&&t()},__setBgOverlay:function(e,t,i,r){var n=this;if(!t)return i[e]=!0,void(r&&r());"backgroundImage"===e||"overlayImage"===e?x.util.enlivenObjects([t],(function(t){n[e]=t[0],i[e]=!0,r&&r()})):this["set"+x.util.string.capitalize(e,!0)](t,(function(){i[e]=!0,r&&r()}))},_enlivenObjects:function(e,t,i){e&&0!==e.length?x.util.enlivenObjects(e,(function(e){t&&t(e)}),null,i):t&&t([])},_toDataURL:function(e,t){this.clone((function(i){t(i.toDataURL(e))}))},_toDataURLWithMultiplier:function(e,t,i){this.clone((function(r){i(r.toDataURLWithMultiplier(e,t))}))},clone:function(e,t){var i=JSON.stringify(this.toJSON(t));this.cloneWithoutData((function(t){t.loadFromJSON(i,(function(){e&&e(t)}))}))},cloneWithoutData:function(e){var t=x.util.createCanvasElement();t.width=this.width,t.height=this.height;var i=new x.Canvas(t);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),e&&e(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):e&&e(i)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n=t.util.toFixed,s=t.util.string.capitalize,o=t.util.degreesToRadians,a=!t.isLikelyNode;t.Object||(t.Object=t.util.createClass(t.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(e){e&&this.setOptions(e)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=t.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(e){var i=t.perfLimitSizeTotal,r=e.width,n=e.height,s=t.maxCacheSideLimit,o=t.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(e.zoomX/=r/c,e.width=c,e.capped=!0),n>u&&(e.zoomY/=n/u,e.height=u,e.capped=!0),e},_getCacheCanvasDimensions:function(){var e=this.getTotalObjectScaling(),t=this._getTransformedDimensions(0,0),i=t.x*e.scaleX/this.scaleX,r=t.y*e.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:e.scaleX,zoomY:e.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var e=this.canvas;if(this.noScaleCache&&e&&e._currentTransform){var i=e._currentTransform.target,r=e._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=t.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,_=f||g,p=0,m=0,v=!1;if(f){var y=this._cacheCanvas.width,S=this._cacheCanvas.height,C=l>y||c>S;v=C||(l<.9*y||c<.9*S)&&y>h&&S>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,m=.1*c)}return this instanceof t.Text&&this.path&&(_=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!_&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+m)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(e){this._setOptions(e),this._initGradient(e.fill,"fill"),this._initGradient(e.stroke,"stroke"),this._initPattern(e.fill,"fill"),this._initPattern(e.stroke,"stroke")},transform:function(e){var t=this.group&&!this.group._transformDone||this.group&&this.canvas&&e===this.canvas.contextTop,i=this.calcTransformMatrix(!t);e.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(e){var i=t.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:t.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(e),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),t.util.populateWithProperties(this,r,e),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(e){return this.toObject(e)},_removeDefaultValues:function(e){var i=t.util.getKlass(e.type).prototype;return i.stateProperties.forEach((function(t){"left"!==t&&"top"!==t&&(e[t]===i[t]&&delete e[t],Array.isArray(e[t])&&Array.isArray(i[t])&&0===e[t].length&&0===i[t].length&&delete e[t])})),e},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var e=t.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(e.scaleX),scaleY:Math.abs(e.scaleY)}},getTotalObjectScaling:function(){var e=this.getObjectScaling(),t=e.scaleX,i=e.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();t*=r*n,i*=r*n}return{scaleX:t,scaleY:i}},getObjectOpacity:function(){var e=this.opacity;return this.group&&(e*=this.group.getObjectOpacity()),e},_set:function(e,i){var r="scaleX"===e||"scaleY"===e,n=this[e]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===e&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===e&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==e||!i||i instanceof t.Shadow?"dirty"===e&&this.group&&this.group.set("dirty",i):i=new t.Shadow(i),this[e]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(e)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(e)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:t.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(e){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(e.save(),this._setupCompositeOperation(e),this.drawSelectionBackground(e),this.transform(e),this._setOpacity(e),this._setShadow(e,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(e)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(e),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),e.restore())},renderCache:function(e){e=e||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,e.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(e,i){if(e.save(),i.inverted?e.globalCompositeOperation="destination-out":e.globalCompositeOperation="destination-in",i.absolutePositioned){var r=t.util.invertTransform(this.calcTransformMatrix());e.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(e),e.scale(1/i.zoomX,1/i.zoomY),e.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),e.restore()},drawObject:function(e,t){var i=this.fill,r=this.stroke;t?(this.fill="black",this.stroke="",this._setClippingProperties(e)):this._renderBackground(e),this._render(e),this._drawClipPath(e,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(e,t){t&&(t.canvas=this.canvas,t.shouldCache(),t._transformDone=!0,t.renderCache({forClipping:!0}),this.drawClipPathOnCache(e,t))},drawCacheOnCanvas:function(e){e.scale(1/this.zoomX,1/this.zoomY),e.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(e){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!e&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!e){var t=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-t/2,-i/2,t,i)}return!0}return!1},_renderBackground:function(e){if(this.backgroundColor){var t=this._getNonTransformedDimensions();e.fillStyle=this.backgroundColor,e.fillRect(-t.x/2,-t.y/2,t.x,t.y),this._removeShadow(e)}},_setOpacity:function(e){this.group&&!this.group._transformDone?e.globalAlpha=this.getObjectOpacity():e.globalAlpha*=this.opacity},_setStrokeStyles:function(e,t){var i=t.stroke;i&&(e.lineWidth=t.strokeWidth,e.lineCap=t.strokeLineCap,e.lineDashOffset=t.strokeDashOffset,e.lineJoin=t.strokeLineJoin,e.miterLimit=t.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(e,i):(e.strokeStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,i)):e.strokeStyle=t.stroke)},_setFillStyles:function(e,t){var i=t.fill;i&&(i.toLive?(e.fillStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,t.fill)):e.fillStyle=i)},_setClippingProperties:function(e){e.globalAlpha=1,e.strokeStyle="transparent",e.fillStyle="#000000"},_setLineDash:function(e,t){t&&0!==t.length&&(1&t.length&&t.push.apply(t,t),e.setLineDash(t))},_renderControls:function(e,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=t.util.multiplyTransformMatrices(a,h),r=t.util.qrDecompose(h),e.save(),e.translate(r.translateX,r.translateY),e.lineWidth=1*this.borderScaleFactor,this.group||(e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),e.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(e,r,i):n&&this.drawBorders(e,i),s&&this.drawControls(e,i),e.restore()},_setShadow:function(e){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=t.devicePixelRatio,o*=t.devicePixelRatio),e.shadowColor=r.color,e.shadowBlur=r.blur*t.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,e.shadowOffsetX=r.offsetX*s*i.scaleX,e.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(e){this.shadow&&(e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0)},_applyPatternGradientTransform:function(e,t){if(!t||!t.toLive)return{offsetX:0,offsetY:0};var i=t.gradientTransform||t.patternTransform,r=-this.width/2+t.offsetX||0,n=-this.height/2+t.offsetY||0;return"percentage"===t.gradientUnits?e.transform(this.width,0,0,this.height,r,n):e.transform(1,0,0,1,r,n),i&&e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(e){"stroke"===this.paintFirst?(this._renderStroke(e),this._renderFill(e)):(this._renderFill(e),this._renderStroke(e))},_render:function(){},_renderFill:function(e){this.fill&&(e.save(),this._setFillStyles(e,this),"evenodd"===this.fillRule?e.fill("evenodd"):e.fill(),e.restore())},_renderStroke:function(e){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this.strokeUniform&&this.group){var t=this.getObjectScaling();e.scale(1/t.scaleX,1/t.scaleY)}else this.strokeUniform&&e.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(e,this.strokeDashArray),this._setStrokeStyles(e,this),e.stroke(),e.restore()}},_applyPatternForTransformedGradient:function(e,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=t.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(e),r.fill(),e.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),e.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),e.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var e=t.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",e.scaleX),this.set("scaleY",e.scaleY),this.angle=e.angle,this.skewX=e.skewX,this.skewY=0}},_removeTransformMatrix:function(e){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=t.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,e&&(this.scaleX*=e.scaleX,this.scaleY*=e.scaleY,this.cropX=e.cropX,this.cropY=e.cropY,i.x+=e.offsetLeft,i.y+=e.offsetTop,this.width=e.width,this.height=e.height),this.setPositionByOrigin(i,"center","center")},clone:function(e,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,e):t.Object._fromObject("Object",r,e)},cloneAsImage:function(e,i){var r=this.toCanvasElement(i);return e&&e(new t.Image(r)),this},toCanvasElement:function(e){e||(e={});var i=t.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(e.multiplier||1)*(e.enableRetinaScaling?t.devicePixelRatio:1);delete this.group,e.withoutTransform&&i.resetObjectTransform(this),e.withoutShadow&&(this.shadow=null);var h,l,c,u,d=t.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),_.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+_.x,u=f.height+_.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new t.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===e.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new t.Point(p.width/2,p.height/2),"center","center");var m=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,e);return this.shadow=s,this.set("canvas",m),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(e){return e||(e={}),t.util.toDataURL(this.toCanvasElement(e),e.format||"png",e.quality||1)},isType:function(e){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===e},complexity:function(){return 1},toJSON:function(e){return this.toObject(e)},rotate:function(e){var t=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return t&&this._setOriginToCenter(),this.set("angle",e),t&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(e,i){i=i||this.canvas.getPointer(e);var r=new t.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=t.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(e){this.globalCompositeOperation&&(e.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){t.runningAnimations&&t.runningAnimations.cancelByTarget(this)}}),t.util.createAccessors&&t.util.createAccessors(t.Object),i(t.Object.prototype,t.Observable),t.Object.NUM_FRACTION_DIGITS=2,t.Object.ENLIVEN_PROPS=["clipPath"],t.Object._fromObject=function(e,i,n,s){var o=t[e];i=r(i,!0),t.util.enlivenPatterns([i.fill,i.stroke],(function(e){void 0!==e[0]&&(i.fill=e[0]),void 0!==e[1]&&(i.stroke=e[1]),t.util.enlivenObjectEnlivables(i,i,(function(){var e=s?new o(i[s],i):new o(i);n&&n(e)}))}))},t.Object.__uid=0)}(t),S=x.util.degreesToRadians,C={left:-.5,center:0,right:.5},b={top:-.5,center:0,bottom:.5},x.util.object.extend(x.Object.prototype,{translateToGivenOrigin:function(e,t,i,r,n){var s,o,a,h=e.x,l=e.y;return"string"==typeof t?t=C[t]:t-=.5,"string"==typeof r?r=C[r]:r-=.5,"string"==typeof i?i=b[i]:i-=.5,"string"==typeof n?n=b[n]:n-=.5,o=n-i,((s=r-t)||o)&&(a=this._getTransformedDimensions(),h=e.x+s*a.x,l=e.y+o*a.y),new x.Point(h,l)},translateToCenterPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,t,i,"center","center");return this.angle?x.util.rotatePoint(r,e,S(this.angle)):r},translateToOriginPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,"center","center",t,i);return this.angle?x.util.rotatePoint(r,e,S(this.angle)):r},getCenterPoint:function(){var e=new x.Point(this.left,this.top);return this.translateToCenterPoint(e,this.originX,this.originY)},getPointByOrigin:function(e,t){var i=this.getCenterPoint();return this.translateToOriginPoint(i,e,t)},toLocalPoint:function(e,t,i){var r,n,s=this.getCenterPoint();return r=void 0!==t&&void 0!==i?this.translateToGivenOrigin(s,"center","center",t,i):new x.Point(this.left,this.top),n=new x.Point(e.x,e.y),this.angle&&(n=x.util.rotatePoint(n,s,-S(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(e,t,i){var r=this.translateToCenterPoint(e,t,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(e){var t,i,r=S(this.angle),n=this.getScaledWidth(),s=x.util.cos(r)*n,o=x.util.sin(r)*n;t="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof e?C[e]:e-.5,this.left+=s*(i-t),this.top+=o*(i-t),this.setCoords(),this.originX=e},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var e=this.getCenterPoint();this.originX="center",this.originY="center",this.left=e.x,this.top=e.y},_resetOrigin:function(){var e=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=e.x,this.top=e.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var e=x.util,t=e.degreesToRadians,i=e.multiplyTransformMatrices,r=e.transformPoint;e.object.extend(x.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(e,t){return t?e?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),e?this.aCoords:this.lineCoords)},getCoords:function(e,t){return i=this._getCoords(e,t),[new x.Point(i.tl.x,i.tl.y),new x.Point(i.tr.x,i.tr.y),new x.Point(i.br.x,i.br.y),new x.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(e,t,i,r){var n=this.getCoords(i,r);return"Intersection"===x.Intersection.intersectPolygonRectangle(n,e,t).status},intersectsWithObject:function(e,t,i){return"Intersection"===x.Intersection.intersectPolygonPolygon(this.getCoords(t,i),e.getCoords(t,i)).status||e.isContainedWithinObject(this,t,i)||this.isContainedWithinObject(e,t,i)},isContainedWithinObject:function(e,t,i){for(var r=this.getCoords(t,i),n=t?e.aCoords:e.lineCoords,s=0,o=e._getImageLines(n);s<4;s++)if(!e.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(e,t,i,r){var n=this.getBoundingRect(i,r);return n.left>=e.x&&n.left+n.width<=t.x&&n.top>=e.y&&n.top+n.height<=t.y},containsPoint:function(e,t,i,r){var n=this._getCoords(i,r),s=(t=t||this._getImageLines(n),this._findCrossPoints(e,t));return 0!==s&&s%2==1},isOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,e).some((function(e){return e.x<=i.x&&e.x>=t.x&&e.y<=i.y&&e.y>=t.y}))||!!this.intersectsWithRect(t,i,!0,e)||this._containsCenterOfCanvas(t,i,e)},_containsCenterOfCanvas:function(e,t,i){var r={x:(e.x+t.x)/2,y:(e.y+t.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(t,i,!0,e)||this.getCoords(!0,e).every((function(e){return(e.x>=i.x||e.x<=t.x)&&(e.y>=i.y||e.y<=t.y)}))&&this._containsCenterOfCanvas(t,i,e)},_getImageLines:function(e){return{topline:{o:e.tl,d:e.tr},rightline:{o:e.tr,d:e.br},bottomline:{o:e.br,d:e.bl},leftline:{o:e.bl,d:e.tl}}},_findCrossPoints:function(e,t){var i,r,n,s=0;for(var o in t)if(!((n=t[o]).o.y=e.y&&n.d.y>=e.y||(n.o.x===n.d.x&&n.o.x>=e.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(e.y-0*e.x-(n.o.y-i*n.o.x))/(0-i)),r>=e.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(t,i){var r=this.getCoords(t,i);return e.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(e){return Math.abs(e)\n')}},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(e),{reviver:e})},toClipPathSVG:function(e){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(e),{reviver:e})},_createBaseClipPathSVGMarkup:function(e,t){var i=(t=t||{}).reviver,r=t.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=e.indexOf("COMMON_PARTS");return e[s]=n,i?i(e.join("")):e.join("")},_createBaseSVGMarkup:function(e,t){var i,r,n=(t=t||{}).noStyle,s=t.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=t.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=e.indexOf("COMMON_PARTS"),p=t.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+x.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),e[_]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(e.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var e=x.util.object.extend,t="stateProperties";function i(t,i,r){var n={};r.forEach((function(e){n[e]=t[e]})),e(t[i],n,!0)}function r(e,t,i){if(e===t)return!0;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(var n=0,s=e.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(t?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(e){for(var t in this.controls)e(this.controls[t],t,this)},_setCornerCoords:function(){var e=this.oCoords;for(var t in e){var i=this.controls[t];e[t].corner=i.calcCornerCoords(this.angle,this.cornerSize,e[t].x,e[t].y,!1),e[t].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,e[t].x,e[t].y,!0)}},drawSelectionBackground:function(t){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;t.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return t.translate(i.x,i.y),t.scale(1/n[0],1/n[3]),t.rotate(e(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-r.x/2,-r.y/2,r.x,r.y),t.restore(),this},drawBorders:function(e,t){t=t||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==t.hasControls?t.hasControls:this.hasControls,a=!1;return e.save(),e.strokeStyle=t.borderColor||this.borderColor,this._setLineDash(e,t.borderDashArray||this.borderDashArray),e.strokeRect(-n/2,-s/2,n,s),o&&(e.beginPath(),this.forEachControl((function(t,i,r){t.withConnection&&t.getVisibility(r,i)&&(a=!0,e.moveTo(t.x*n,t.y*s),e.lineTo(t.x*n+t.offsetX,t.y*s+t.offsetY))})),a&&e.stroke()),e.restore(),this},drawBordersInGroup:function(e,t,i){i=i||{};var r=x.util.sizeAfterTransform(this.width,this.height,t),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():t.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():t.scaleY)+o;return e.save(),this._setLineDash(e,i.borderDashArray||this.borderDashArray),e.strokeStyle=i.borderColor||this.borderColor,e.strokeRect(-a/2,-h/2,a,h),e.restore(),this},drawControls:function(e,t){t=t||{},e.save();var i,r,n=this.canvas.getRetinaScaling();return e.setTransform(n,0,0,n,0,0),e.strokeStyle=e.fillStyle=t.cornerColor||this.cornerColor,this.transparentCorners||(e.strokeStyle=t.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(e,t.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=x.util.transformPoint(r,i)),n.render(e,r.x,r.y,t,o))})),e.restore(),this},isControlVisible:function(e){return this.controls[e]&&this.controls[e].getVisibility(this,e)},setControlVisible:function(e,t){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[e]=t,this},setControlsVisibility:function(e){for(var t in e||(e={}),e)this.setControlVisible(t,e[t]);return this},onDeselect:function(){},onSelect:function(){}})}(),x.util.object.extend(x.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(t){e.set("left",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxCenterObjectV:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(t){e.set("top",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxRemove:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(t){e.set("opacity",t),s.requestRenderAll(),n()},onComplete:function(){s.remove(e),r()}})}}),x.util.object.extend(x.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var e,t,i=[],r=[];for(e in arguments[0])i.push(e);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(e);"from"in i||(i.from=a),o||(t=~t.indexOf("=")?a+parseFloat(t.replace("=","")):parseFloat(t));var h={target:this,startValue:i.from,endValue:t,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(e,t,r){return i.abort.call(s,e,t,r)},onChange:function(t,o,a){n?s[n[0]][n[1]]=t:s.set(e,t),r||i.onChange&&i.onChange(t,o,a)},onComplete:function(e,t,n){r||(s.setCoords(),i.onComplete&&i.onComplete(e,t,n))}};return o?x.util.animateColor(h.startValue,h.endValue,h.duration,h):x.util.animate(h)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(e,t){var i=e.origin,r=e.axis1,n=e.axis2,s=e.dimension,o=t.nearest,a=t.center,h=t.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}t.Line?t.warn("fabric.Line is already defined"):(t.Line=t.util.createClass(t.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:t.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(e,t){e||(e=[0,0,0,0]),this.callSuper("initialize",t),this.set("x1",e[0]),this.set("y1",e[1]),this.set("x2",e[2]),this.set("y2",e[3]),this._setWidthHeight(t)},_setWidthHeight:function(e){e||(e={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in e?e.left:this._getLeftToOriginX(),this.top="top"in e?e.top:this._getTopToOriginY()},_set:function(e,t){return this.callSuper("_set",e,t),void 0!==n[e]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(e){e.beginPath();var t=this.calcLinePoints();e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineWidth=this.strokeWidth;var i=e.strokeStyle;e.strokeStyle=this.stroke||e.fillStyle,this.stroke&&this._renderStroke(e),e.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(e){return i(this.callSuper("toObject",e),this.calcLinePoints())},_getNonTransformedDimensions:function(){var e=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(e.y-=this.strokeWidth),0===this.height&&(e.x-=this.strokeWidth)),e},calcLinePoints:function(){var e=this.x1<=this.x2?-1:1,t=this.y1<=this.y2?-1:1,i=e*this.width*.5,r=t*this.height*.5;return{x1:i,x2:e*this.width*-.5,y1:r,y2:t*this.height*-.5}},_toSVG:function(){var e=this.calcLinePoints();return["\n']}}),t.Line.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),t.Line.fromElement=function(e,r,n){n=n||{};var s=t.parseAttributes(e,t.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new t.Line(o,i(s,n)))},t.Line.fromObject=function(e,i){var n=r(e,!0);n.points=[e.x1,e.y1,e.x2,e.y2],t.Object._fromObject("Line",n,(function(e){delete e.points,i&&i(e)}),"points")})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians;t.Circle?t.warn("fabric.Circle is already defined."):(t.Circle=t.util.createClass(t.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:t.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(e,t){return this.callSuper("_set",e,t),"radius"===e&&this.setRadius(t),this},toObject:function(e){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(e))},_toSVG:function(){var e,r=(this.endAngle-this.startAngle)%360;if(0===r)e=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;e=['180?"1":"0")+" 1"," "+t.util.cos(s)*o+" "+t.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return e},_render:function(e){e.beginPath(),e.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(e)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(e){return this.radius=e,this.set("width",2*e).set("height",2*e)}}),t.Circle.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),t.Circle.fromElement=function(e,i){var r,n=t.parseAttributes(e,t.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new t.Circle(n))},t.Circle.fromObject=function(e,i){t.Object._fromObject("Circle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={});t.Triangle?t.warn("fabric.Triangle is already defined"):(t.Triangle=t.util.createClass(t.Object,{type:"triangle",width:100,height:100,_render:function(e){var t=this.width/2,i=this.height/2;e.beginPath(),e.moveTo(-t,i),e.lineTo(0,-i),e.lineTo(t,i),e.closePath(),this._renderPaintInOrder(e)},_toSVG:function(){var e=this.width/2,t=this.height/2;return["']}}),t.Triangle.fromObject=function(e,i){return t.Object._fromObject("Triangle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=2*Math.PI;t.Ellipse?t.warn("fabric.Ellipse is already defined."):(t.Ellipse=t.util.createClass(t.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this.set("rx",e&&e.rx||0),this.set("ry",e&&e.ry||0)},_set:function(e,t){switch(this.callSuper("_set",e,t),e){case"rx":this.rx=t,this.set("width",2*t);break;case"ry":this.ry=t,this.set("height",2*t)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']},_render:function(e){e.beginPath(),e.save(),e.transform(1,0,0,this.ry/this.rx,0,0),e.arc(0,0,this.rx,0,i,!1),e.restore(),this._renderPaintInOrder(e)}}),t.Ellipse.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),t.Ellipse.fromElement=function(e,i){var r=t.parseAttributes(e,t.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new t.Ellipse(r))},t.Ellipse.fromObject=function(e,i){t.Object._fromObject("Ellipse",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend;t.Rect?t.warn("fabric.Rect is already defined"):(t.Rect=t.util.createClass(t.Object,{stateProperties:t.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(e){var t=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==t||0!==i,h=.4477152502;e.beginPath(),e.moveTo(s+t,o),e.lineTo(s+r-t,o),a&&e.bezierCurveTo(s+r-h*t,o,s+r,o+h*i,s+r,o+i),e.lineTo(s+r,o+n-i),a&&e.bezierCurveTo(s+r,o+n-h*i,s+r-h*t,o+n,s+r-t,o+n),e.lineTo(s+t,o+n),a&&e.bezierCurveTo(s+h*t,o+n,s,o+n-h*i,s,o+n-i),e.lineTo(s,o+i),a&&e.bezierCurveTo(s,o+h*i,s+h*t,o,s+t,o),e.closePath(),this._renderPaintInOrder(e)},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']}}),t.Rect.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),t.Rect.fromElement=function(e,r,n){if(!e)return r(null);n=n||{};var s=t.parseAttributes(e,t.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new t.Rect(i(n?t.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},t.Rect.fromObject=function(e,i){return t.Object._fromObject("Rect",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.array.min,n=t.util.array.max,s=t.util.toFixed,o=t.util.projectStrokeOnPoints;t.Polyline?t.warn("fabric.Polyline is already defined"):(t.Polyline=t.util.createClass(t.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:t.Object.prototype.cacheProperties.concat("points"),initialize:function(e,t){t=t||{},this.points=e||[],this.callSuper("initialize",t),this._setPositionDimensions(t)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(e){var t,i=this._calcDimensions(e),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,e.fromSVG||(t=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===e.left&&(this.left=e.fromSVG?i.left:t.x),void 0===e.top&&(this.top=e.fromSVG?i.top:t.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var e=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,t=r(e,"x")||0,i=r(e,"y")||0;return{left:t,top:i,width:(n(e,"x")||0)-t,height:(n(e,"y")||0)-i}},toObject:function(e){return i(this.callSuper("toObject",e),{points:this.points.concat()})},_toSVG:function(){for(var e=[],i=this.pathOffset.x,r=this.pathOffset.y,n=t.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(e){var t,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;e.beginPath(),e.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(e){return n(this.callSuper("toObject",e),{path:this.path.map((function(e){return e.slice()}))})},toDatalessObject:function(e){var t=this.toObject(["sourcePath"].concat(e));return t.sourcePath&&delete t.path,t},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var e=t.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,e)+", "+o(-this.pathOffset.y,e)+")"},toClipPathSVG:function(e){var t=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},toSVG:function(e){var t=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var e,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(e){var i=!!this.group;return this._restoreObjectsState(),t.util.resetObjectTransform(this),e&&(i&&t.util.removeTransformFromObject(e,this.group.calcTransformMatrix()),this._objects.push(e),e.group=this,e._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(e){return this._restoreObjectsState(),t.util.resetObjectTransform(this),this.remove(e),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(e){this.dirty=!0,e.group=this,e._set("canvas",this.canvas)},_onObjectRemoved:function(e){this.dirty=!0,delete e.group},_set:function(e,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(e,i);if("canvas"===e)for(;r--;)this._objects[r]._set(e,i);t.Object.prototype._set.call(this,e,i)},toObject:function(e){var i=this.includeDefaultValues,r=this._objects.filter((function(e){return!e.excludeFromExport})).map((function(t){var r=t.includeDefaultValues;t.includeDefaultValues=i;var n=t.toObject(e);return t.includeDefaultValues=r,n})),n=t.Object.prototype.toObject.call(this,e);return n.objects=r,n},toDatalessObject:function(e){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(t){var i=t.includeDefaultValues;t.includeDefaultValues=n;var r=t.toDatalessObject(e);return t.includeDefaultValues=i,r}))}var s=t.Object.prototype.toDatalessObject.call(this,e);return s.objects=i,s},render:function(e){this._transformDone=!0,this.callSuper("render",e),this._transformDone=!1},shouldCache:function(){var e=t.Object.prototype.shouldCache.call(this);if(e)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),t},getSvgStyles:function(){var e=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",t=this.visible?"":" visibility: hidden;";return[e,this.getSvgFilter(),t].join("")},toClipPathSVG:function(e){for(var t=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(e,t,i){e.save(),e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",e,t),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,e=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?t.concat(e,i):t.concat(i,e)},getSrc:function(e){var t=e?this._element:this._originalElement;return t?t.toDataURL?t.toDataURL():this.srcFromAttribute?t.getAttribute("src"):t.src:this.src||""},setSrc:function(e,t,i){return x.util.loadImage(e,(function(e,r){this.setElement(e,i),this._setWidthHeight(),t&&t(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var e=this.resizeFilter,t=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!e||r>t&&n>t)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);x.filterBackend||(x.filterBackend=x.initFilterBackend());var o=x.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=n,x.filterBackend.applyFilters([e],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(e){if(e=(e=e||this.filters||[]).filter((function(e){return e&&!e.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===e.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var t=this._originalElement,i=t.naturalWidth||t.width,r=t.naturalHeight||t.height;if(this._element===this._originalElement){var n=x.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return x.filterBackend||(x.filterBackend=x.initFilterBackend()),x.filterBackend.applyFilters(e,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(e){x.util.setImageSmoothing(e,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(e),this._renderPaintInOrder(e)},drawCacheOnCanvas:function(e){x.util.setImageSmoothing(e,this.imageSmoothing),x.Object.prototype.drawCacheOnCanvas.call(this,e)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(e){var t=this._element;if(t){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=t.naturalWidth||t.width,u=t.naturalHeight||t.height,d=h*i,f=l*r,g=o(n*i,c-d),_=o(s*r,u-f),p=-n/2,m=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);t&&e.drawImage(t,d,f,g,_,p,m,v,y)}},_needsResize:function(){var e=this.getTotalObjectScaling();return e.scaleX!==this._lastScaleX||e.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(e,t){this.setElement(x.util.getById(e),t),x.util.addClass(this.getElement(),x.Image.CSS_CANVAS)},_initConfig:function(e){e||(e={}),this.setOptions(e),this._setWidthHeight(e)},_initFilters:function(e,t){e&&e.length?x.util.enlivenObjects(e,(function(e){t&&t(e)}),"fabric.Image.filters"):t&&t()},_setWidthHeight:function(e){e||(e={});var t=this.getElement();this.width=e.width||t.naturalWidth||t.width||0,this.height=e.height||t.naturalHeight||t.height||0},parsePreserveAspectRatioAttribute:function(){var e,t=x.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!t||"none"===t.alignX&&"none"===t.alignY?(n=c/i,s=u/r):("meet"===t.meetOrSlice&&(e=(c-i*(n=s=x.util.findScaleToFit(this._element,d)))/2,"Min"===t.alignX&&(o=-e),"Max"===t.alignX&&(o=e),e=(u-r*s)/2,"Min"===t.alignY&&(a=-e),"Max"===t.alignY&&(a=e)),"slice"===t.meetOrSlice&&(e=i-c/(n=s=x.util.findScaleToCover(this._element,d)),"Mid"===t.alignX&&(h=e/2),"Max"===t.alignX&&(h=e),e=r-u/s,"Mid"===t.alignY&&(l=e/2),"Max"===t.alignY&&(l=e),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),x.Image.CSS_CANVAS="canvas-img",x.Image.prototype.getSvgSrc=x.Image.prototype.getSrc,x.Image.fromObject=function(e,t){var i=x.util.object.clone(e);x.util.loadImage(i.src,(function(e,r){r?t&&t(null,!0):x.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],x.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],x.util.enlivenObjectEnlivables(i,i,(function(){var r=new x.Image(e,i);t(r,!1)}))}))}))}),null,i.crossOrigin)},x.Image.fromURL=function(e,t,i){x.util.loadImage(e,(function(e,r){t&&t(new x.Image(e,i),r)}),null,i&&i.crossOrigin)},x.Image.ATTRIBUTE_NAMES=x.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),x.Image.fromElement=function(e,i,r){var n=x.parseAttributes(e,x.Image.ATTRIBUTE_NAMES);x.Image.fromURL(n["xlink:href"],i,t(r?x.util.object.clone(r):{},n))})}(t),x.util.object.extend(x.Object.prototype,{_getAngleValueForStraighten:function(){var e=this.angle%360;return e>0?90*Math.round((e-1)/90):90*Math.round(e/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(e){var t=function(){},i=(e=e||{}).onComplete||t,r=e.onChange||t,n=this;return x.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(e){n.rotate(e),r()},onComplete:function(){n.setCoords(),i()}})}}),x.util.object.extend(x.StaticCanvas.prototype,{straightenObject:function(e){return e.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(e){return e.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function e(e,t){var i="precision "+t+" float;\nvoid main(){}",r=e.createShader(e.FRAGMENT_SHADER);return e.shaderSource(r,i),e.compileShader(r),!!e.getShaderParameter(r,e.COMPILE_STATUS)}function t(e){e&&e.tileSize&&(this.tileSize=e.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}x.isWebglSupported=function(t){if(x.isLikelyNode)return!1;t=t||x.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){x.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=x.maxTextureSize>=t;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(e(r,s[o])){x.webGlPrecision=s[o];break}}return this.isSupported=n,n},x.WebglFilterBackend=t,t.prototype={tileSize:2048,resources:{},setupGLContext:function(e,t){this.dispose(),this.createWebGLCanvas(e,t),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(e,t)},chooseFastestCopyGLTo2DMethod:function(e,t){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(e){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=x.util.createCanvasElement(),a=new ArrayBuffer(e*t*4);if(x.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=I);var h,l,c={imageBuffer:a,destinationWidth:e,destinationHeight:t,targetCanvas:o};o.width=e,o.height=t,h=window.performance.now(),E.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),I.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=I):this.copyGLTo2D=E}},createWebGLCanvas:function(e,t){var i=x.util.createCanvasElement();i.width=e,i.height=t;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(e,t,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,t));var h={originalWidth:t.width||t.originalWidth,originalHeight:t.height||t.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&t),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&t),passes:e.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),e.forEach((function(e){e&&e.applyTo(h)})),function(e){var t=e.targetCanvas,i=t.width,r=t.height,n=e.destinationWidth,s=e.destinationHeight;i===n&&r===s||(t.width=n,t.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(e,t,i,r){var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),r?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,i,0,e.RGBA,e.UNSIGNED_BYTE,null),n},getCachedTexture:function(e,t){if(this.textureCache[e])return this.textureCache[e];var i=this.createTexture(this.gl,t.width,t.height,t);return this.textureCache[e]=i,i},evictCachesForKey:function(e){this.textureCache[e]&&(this.gl.deleteTexture(this.textureCache[e]),delete this.textureCache[e])},copyGLTo2D:E,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var e=this.gl,t={renderer:"",vendor:""};if(!e)return t;var i=e.getExtension("WEBGL_debug_renderer_info");if(i){var r=e.getParameter(i.UNMASKED_RENDERER_WEBGL),n=e.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(t.renderer=r.toLowerCase()),n&&(t.vendor=n.toLowerCase())}return this.gpuInfo=t,t}}}(),function(){var e=function(){};function t(){}x.Canvas2dFilterBackend=t,t.prototype={evictCachesForKey:e,dispose:e,clearWebGLCaches:e,resources:{},applyFilters:function(e,t,i,r,n){var s=n.getContext("2d");s.drawImage(t,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:t,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return e.forEach((function(e){e.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),x.Image=x.Image||{},x.Image.filters=x.Image.filters||{},x.Image.filters.BaseFilter=x.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(e){e&&this.setOptions(e)},setOptions:function(e){for(var t in e)this[t]=e[t]},createProgram:function(e,t,i){t=t||this.fragmentSource,i=i||this.vertexSource,"highp"!==x.webGlPrecision&&(t=t.replace(/precision highp float/g,"precision "+x.webGlPrecision+" float"));var r=e.createShader(e.VERTEX_SHADER);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+e.getShaderInfoLog(r));var n=e.createShader(e.FRAGMENT_SHADER);if(e.shaderSource(n,t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+e.getShaderInfoLog(n));var s=e.createProgram();if(e.attachShader(s,r),e.attachShader(s,n),e.linkProgram(s),!e.getProgramParameter(s,e.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+e.getProgramInfoLog(s));var o=this.getAttributeLocations(e,s),a=this.getUniformLocations(e,s)||{};return a.uStepW=e.getUniformLocation(s,"uStepW"),a.uStepH=e.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(e,t){return{aPosition:e.getAttribLocation(t,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(e,t,i){var r=t.aPosition,n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW)},_setupFrameBuffer:function(e){var t,i,r=e.context;e.passes>1?(t=e.destinationWidth,i=e.destinationHeight,e.sourceWidth===t&&e.sourceHeight===i||(r.deleteTexture(e.targetTexture),e.targetTexture=e.filterBackend.createTexture(r,t,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(e){e.passes--,e.pass++;var t=e.targetTexture;e.targetTexture=e.sourceTexture,e.sourceTexture=t},isNeutralState:function(){var e=this.mainParameter,t=x.Image.filters[this.type].prototype;if(e){if(Array.isArray(t[e])){for(var i=t[e].length;i--;)if(this[e][i]!==t[e][i])return!1;return!0}return t[e]===this[e]}return!1},applyTo:function(e){e.webgl?(this._setupFrameBuffer(e),this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)},retrieveShader:function(e){return e.programCache.hasOwnProperty(this.type)||(e.programCache[this.type]=this.createProgram(e.context)),e.programCache[this.type]},applyToWebGL:function(e){var t=e.context,i=this.retrieveShader(e);0===e.pass&&e.originalTexture?t.bindTexture(t.TEXTURE_2D,e.originalTexture):t.bindTexture(t.TEXTURE_2D,e.sourceTexture),t.useProgram(i.program),this.sendAttributeData(t,i.attributeLocations,e.aPosition),t.uniform1f(i.uniformLocations.uStepW,1/e.sourceWidth),t.uniform1f(i.uniformLocations.uStepH,1/e.sourceHeight),this.sendUniformData(t,i.uniformLocations),t.viewport(0,0,e.destinationWidth,e.destinationHeight),t.drawArrays(t.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(e,t,i){e.activeTexture(i),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE0)},unbindAdditionalTexture:function(e,t){e.activeTexture(t),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(e){this[this.mainParameter]=e},sendUniformData:function(){},createHelpLayer:function(e){if(!e.helpLayer){var t=document.createElement("canvas");t.width=e.sourceWidth,t.height=e.sourceHeight,e.helpLayer=t}},toObject:function(){var e={type:this.type},t=this.mainParameter;return t&&(e[t]=this[t]),e},toJSON:function(){return this.toObject()}}),x.Image.filters.BaseFilter.fromObject=function(e,t){var i=new x.Image.filters[e.type](e);return t&&t(i),i},function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(e){this.callSuper("initialize",e),this.matrix=this.matrix.slice(0)},applyTo2d:function(e){var t,i,r,n,s,o=e.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=S||o<0||o>=y||(h=4*(a*y+o),l=p[f*m+d],t+=_[h]*l,i+=_[h+1]*l,r+=_[h+2]*l,w||(n+=_[h+3]*l));b[s]=t,b[s+1]=i,b[s+2]=r,b[s+3]=w?_[s+3]:n}e.imageData=C},getUniformLocations:function(e,t){return{uMatrix:e.getUniformLocation(t,"uMatrix"),uOpaque:e.getUniformLocation(t,"uOpaque"),uHalfSize:e.getUniformLocation(t,"uHalfSize"),uSize:e.getUniformLocation(t,"uSize")}},sendUniformData:function(e,t){e.uniform1fv(t.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),t.Image.filters.Convolute.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(e){var t,i,r=e.imageData.data,n=r.length,s=this.mode;for(t=0;tl[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[e]+"}\n}"},retrieveShader:function(e){var t,i=this.type+"_"+this.mode;return e.programCache.hasOwnProperty(i)||(t=this.buildSource(this.mode),e.programCache[i]=this.createProgram(e.context,t)),e.programCache[i]},applyTo2d:function(e){var i,r,n,s,o,a,h,l=e.imageData.data,c=l.length,u=1-this.alpha;i=(h=new t.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=e||t<=-e)return 0;if(t<1.1920929e-7&&t>-1.1920929e-7)return 1;var i=(t*=Math.PI)/e;return a(t)/t*a(i)/i}},applyTo2d:function(e){var t=e.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=t.width,a=t.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(e,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(e,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(e,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(e,s,a,h,l)),e.imageData=n},sliceByTwo:function(e,i,n,s,o){var a,h,l=e.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,_=t.filterBackend.resources,p=0,m=0,v=i,y=0;for(_.sliceByTwo||(_.sliceByTwo=document.createElement("canvas")),((a=_.sliceByTwo).width<1.5*i||a.height=t)){M=r(1e3*s(x-C.x)),S[M]||(S[M]={});for(var L=b.y-y;L<=b.y+y;L++)L<0||L>=o||(F=r(1e3*s(L-C.y)),S[M][F]||(S[M][F]=f(n(i(M*p,2)+i(F*m,2))/1e3)),(T=S[M][F])>0&&(I+=T,A+=T*c[E=4*(L*t+x)],O+=T*c[E+1],R+=T*c[E+2],D+=T*c[E+3]))}d[E=4*(w*a+h)]=A/I,d[E+1]=O/I,d[E+2]=R/I,d[E+3]=D/I}return++h1&&F<-1||(y=2*F*F*F-3*F*F+1)>0&&(T+=y*f[3+(M=4*(D+I*t))],C+=y,f[M+3]<255&&(y=y*f[M+3]/250),b+=y*f[M],w+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=b/S,_[v+1]=w/S,_[v+2]=x/S,_[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),t.Image.filters.Resize.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(e){if(0!==this.contrast){var t,i=e.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(t=0;t1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio),e=t*this.blur*.12,this.horizontal?i[0]=e:i[1]=e,i}}),i.Blur.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(e){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,e)},applyTo2d:function(e){var t,i=e.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),t=0,n=256;t'},_getCacheCanvasDimensions:function(){var e=this.callSuper("_getCacheCanvasDimensions"),t=this.fontSize;return e.width+=t*e.zoomX,e.height+=t*e.zoomY,e},_render:function(e){var t=this.path;t&&!t.isNotVisible()&&t._render(e),this._setTextStyles(e),this._renderTextLinesBackground(e),this._renderTextDecoration(e,"underline"),this._renderText(e),this._renderTextDecoration(e,"overline"),this._renderTextDecoration(e,"linethrough")},_renderText:function(e){"stroke"===this.paintFirst?(this._renderTextStroke(e),this._renderTextFill(e)):(this._renderTextFill(e),this._renderTextStroke(e))},_setTextStyles:function(e,t,i){if(e.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":e.textBaseline="middle";break;case"ascender":e.textBaseline="top";break;case"descender":e.textBaseline="bottom"}e.font=this._getFontDeclaration(t,i)},calcTextWidth:function(){for(var e=this.getLineWidth(0),t=1,i=this._textLines.length;te&&(e=r)}return e},_renderTextLine:function(e,t,i,r,n,s){this._renderChars(e,t,i,r,n,s)},_renderTextLinesBackground:function(e){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var t,i,r,n,s,o,a,h=e.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,_=this._textLines.length;g<_;g++)if(t=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){r=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,n=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,m=r.length;p=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(e,i,r){var n=e+i.kernedWidth/2,s=this.path,o=t.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(e,t,i,r,n){var s,o=this.getCompleteStyleDeclaration(t,i),a=r?this.getCompleteStyleDeclaration(t,i-1):{},h=this._measureChar(e,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[t][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(e){if(this.__lineHeights[e])return this.__lineHeights[e];for(var t=this._textLines[e],i=this.getHeightOfChar(e,0),r=1,n=t.length;r0){var I=v+s+u;"rtl"===this.direction&&(I=this.width-I-d),l&&m&&(e.fillStyle=m,e.fillRect(I,c+b*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,m=p,r=n,o=a}else d+=f.kernedWidth;I=v+s+u,"rtl"===this.direction&&(I=this.width-I-d),e.fillStyle=p,g&&p&&e.fillRect(I,c+b*r+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(e)}},_getFontDeclaration:function(e,i){var r=e||this,n=this.fontFamily,s=t.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[t.isLikelyNode?r.fontWeight:r.fontStyle,t.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(e){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",e)))},_splitTextIntoLines:function(e){for(var i=e.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(e.underline=!0),e.textDecoration.indexOf("line-through")>-1&&(e.linethrough=!0),e.textDecoration.indexOf("overline")>-1&&(e.overline=!0),delete e.textDecoration)}x.IText=x.util.createClass(x.Text,x.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(e,t){this.callSuper("initialize",e,t),this.initBehavior()},setSelectionStart:function(e){e=Math.max(e,0),this._updateAndFire("selectionStart",e)},setSelectionEnd:function(e){e=Math.min(e,this.text.length),this._updateAndFire("selectionEnd",e)},_updateAndFire:function(e,t){this[e]!==t&&(this._fireSelectionChanged(),this[e]=t),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(e){this.clearContextTop(),this.callSuper("render",e),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(e){this.callSuper("_render",e)},clearContextTop:function(e){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this.canvas.contextTop,i=this.canvas.viewportTransform;t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(t),this._clearTextArea(t),e||t.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this._getCursorBoundaries(),t=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(e,t):this.renderSelection(e,t),t.restore()}},_clearTextArea:function(e){var t=this.width+4,i=this.height+4;e.clearRect(-t/2,-i/2,t,i)},_getCursorBoundaries:function(e){void 0===e&&(e=this.selectionStart);var t=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(e);return{left:t,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(e){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var t,i,r,n,s=0,o=0,a=this.get2DCursorLocation(e);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(e,t){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=e.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(e,t),t.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),t.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,t.fillRect(e.left+e.leftOffset-a/2,h+e.top+l,a,s)},renderSelection:function(e,t){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=e.left+f+_,y=p-_,S=g,C=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,C=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+C,y,S),e.topOffset+=d}},getCurrentCharFontSize:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fontSize")},getCurrentCharColor:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fill")},_getCurrentCharIndex:function(){var e=this.get2DCursorLocation(this.selectionStart,!0),t=e.charIndex>0?e.charIndex-1:0;return{l:e.lineIndex,c:t}}}),x.IText.fromObject=function(t,i){if(e(t),t.styles)for(var r in t.styles)for(var n in t.styles[r])e(t.styles[r][n]);x.Object._fromObject("IText",t,i,"text")}}(),w=x.util.object.clone,x.util.object.extend(x.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var e=this;this.on("added",(function(){var t=e.canvas;t&&(t._hasITextHandlers||(t._hasITextHandlers=!0,e._initCanvasHandlers(t)),t._iTextInstances=t._iTextInstances||[],t._iTextInstances.push(e))}))},initRemovedHandler:function(){var e=this;this.on("removed",(function(){var t=e.canvas;t&&(t._iTextInstances=t._iTextInstances||[],x.util.removeFromArray(t._iTextInstances,e),0===t._iTextInstances.length&&(t._hasITextHandlers=!1,e._removeCanvasHandlers(t)))}))},_initCanvasHandlers:function(e){e._mouseUpITextHandler=function(){e._iTextInstances&&e._iTextInstances.forEach((function(e){e.__isMousedown=!1}))},e.on("mouse:up",e._mouseUpITextHandler)},_removeCanvasHandlers:function(e){e.off("mouse:up",e._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(e,t,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},e.animate("_currentCursorOpacity",t,{duration:i,onComplete:function(){n.isAborted||e[r]()},onChange:function(){e.canvas&&e.selectionStart===e.selectionEnd&&e.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var e=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){e._currentTickCompleteState=e._animateCursor(e,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(e){var t=this,i=e?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){t._tick()}),i)},abortCursorAnimation:function(){var e=this._currentTickState||this._currentTickCompleteState,t=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,e&&t&&t.clearContext(t.contextTop||t.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(e){var t=0,i=e-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i--;for(;/\S/.test(this._text[i])&&i>-1;)t++,i--;return e-t},findWordBoundaryRight:function(e){var t=0,i=e;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i++;for(;/\S/.test(this._text[i])&&i-1;)t++,i--;return e-t},findLineBoundaryRight:function(e){for(var t=0,i=e;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=t):(this.selectionStart=t,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(e,t,i){var r=i.slice(0,e),n=x.util.string.graphemeSplit(r).length;if(e===t)return{selectionStart:n,selectionEnd:n};var s=i.slice(e,t);return{selectionStart:n,selectionEnd:n+x.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(e,t,i){var r=i.slice(0,e).join("").length;return e===t?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(e,t).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var e=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=e.selectionStart,this.hiddenTextarea.selectionEnd=e.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var e=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var e=this._calcTextareaPosition();this.hiddenTextarea.style.left=e.left,this.hiddenTextarea.style.top=e.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var e=this.inCompositionMode?this.compositionStart:this.selectionStart,t=this._getCursorBoundaries(e),i=this.get2DCursorLocation(e),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=t.leftOffset,a=this.calcTransformMatrix(),h={x:t.left+o,y:t.top+t.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,_=c.clientWidth/u,p=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=_,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var e=this._textBeforeEdit!==this.text,t=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),e&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),e&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var e in this.styles)this._textLines[e]||delete this.styles[e]},removeStyleFromTo:function(e,t){var i,r,n=this.get2DCursorLocation(e,!0),s=this.get2DCursorLocation(t,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(e,t){var i=w(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>e&&(this.styles[n+t]=i[n],i[n-t]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(e,t,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[e].length===t;for(var h in i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&(n=this.styles[e][0===t?t:t-1]),this.styles[e]){var l=parseInt(h,10);l>=t&&(o=!0,s[l-t]=this.styles[e][h],a&&0===t||delete this.styles[e][h])}var c=!1;for(o&&!a&&(this.styles[e+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[e+i]={0:w(r[i-1])}:n?this.styles[e+i]={0:w(n)}:delete this.styles[e+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(e,t,i,r){this.styles||(this.styles={});var n=this.styles[e],s=n?w(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=t&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[e]||(this.styles[e]={}),this.styles[e][t+i]=w(r[i]));else if(n)for(var h=n[t?t-1:1];h&&i--;)this.styles[e][t+i]=w(h)},insertNewStyleBlock:function(e,t,i){for(var r=this.get2DCursorLocation(t,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(e,t,i){i<=e?(t===e?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=e),this.selectionStart=i):i>e&&ie?this.selectionStart=e:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>e?this.selectionEnd=e:this.selectionEnd<0&&(this.selectionEnd=0)}}),x.util.object.extend(x.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(e){if(this.canvas){this.__newClickTime=+new Date;var t=e.pointer;this.isTripleClick(t)&&(this.fire("tripleclick",e),this._stopEvent(e.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=t,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(e){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===e.x&&this.__lastPointer.y===e.y},_stopEvent:function(e){e.preventDefault&&e.preventDefault(),e.stopPropagation&&e.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(e){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(e.e))},tripleClickHandler:function(e){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(e.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(e.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(e){if(this.__isMousedown=!1,!(!this.editable||this.group||e.transform&&e.transform.actionPerformed||e.e.button&&1!==e.e.button)){if(this.canvas){var t=this.canvas._activeObject;if(t&&t!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(e.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(e){var t=this.getSelectionStartFromPointer(e),i=this.selectionStart,r=this.selectionEnd;e.shiftKey?this.setSelectionStartEndWithShift(i,r,t):(this.selectionStart=t,this.selectionEnd=t),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(e){for(var t,i=this.getLocalPointer(e),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,t=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=t.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),x.util.object.extend(x.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=x.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var e=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+e.top+"; left: "+e.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+e.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):x.document.body.appendChild(this.hiddenTextarea),x.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),x.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),x.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),x.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(x.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(e){if(this.isEditing){var t="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(e.keyCode in t)this[t[e.keyCode]](e);else{if(!(e.keyCode in this.ctrlKeysMapDown)||!e.ctrlKey&&!e.metaKey)return;this[this.ctrlKeysMapDown[e.keyCode]](e)}e.stopImmediatePropagation(),e.preventDefault(),e.keyCode>=33&&e.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(e){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:e.keyCode in this.ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)&&(this[this.ctrlKeysMapUp[e.keyCode]](e),e.stopImmediatePropagation(),e.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(e){var t=this.fromPaste;if(this.fromPaste=!1,e&&e.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[e][t-1]).left+i.width),r},getDownCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||e.metaKey||34===e.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(e,t){return e.shiftKey&&this.selectionStart!==this.selectionEnd&&t?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||e.metaKey||33===e.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(e,t){for(var i,r,n=this._textLines[e],s=this._getLineLeftOffset(e),o=0,a=0,h=n.length;at){r=!0;var l=s-i,c=s,u=Math.abs(l-t);o=Math.abs(c-t)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",e)},moveCursorUp:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",e)},_moveCursorUpOrDown:function(e,t){var i=this["get"+e+"CursorOffset"](t,"right"===this._selectionDirection);t.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(e){var t="left"===this._selectionDirection?this.selectionStart+e:this.selectionEnd+e;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,t),0!==e},moveCursorWithoutShift:function(e){return e<0?(this.selectionStart+=e,this.selectionEnd=this.selectionStart):(this.selectionEnd+=e,this.selectionStart=this.selectionEnd),0!==e},moveCursorLeft:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",e)},_move:function(e,t,i){var r;if(e.altKey)r=this["findWordBoundary"+i](this[t]);else{if(!e.metaKey&&35!==e.keyCode&&36!==e.keyCode)return this[t]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[t])}if(void 0!==typeof r&&this[t]!==r)return this[t]=r,!0},_moveLeft:function(e,t){return this._move(e,t,"Left")},_moveRight:function(e,t){return this._move(e,t,"Right")},moveCursorLeftWithoutShift:function(e){var t=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(t=this._moveLeft(e,"selectionStart")),this.selectionEnd=this.selectionStart,t},moveCursorLeftWithShift:function(e){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(e,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(e,"selectionStart")):void 0},moveCursorRight:function(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",e)},_moveCursorLeftOrRight:function(e,t){var i="moveCursor"+e+"With";this._currentCursorOpacity=1,t.shiftKey?i+="Shift":i+="outShift",this[i](t)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(e){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(e,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(e,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(e){var t=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(t=this._moveRight(e,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,t},removeChars:function(e,t){void 0===t&&(t=e+1),this.removeStyleFromTo(e,t),this._text.splice(e,t-e),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(e,t,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=x.util.string.graphemeSplit(e);this.insertNewStyleBlock(n,i,t),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var e=x.util.toFixed,t=/ +/g;x.util.object.extend(x.Text.prototype,{_toSVG:function(){var e=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(e.textTop,e.textLeft);return this._wrapSVGTextAndBg(t)},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(e){var t=this.getSvgTextDecoration(this);return[e.textBgRects.join(""),'\t\t",e.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(e,t){var i,r=[],n=[],s=e;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",x.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(e,t,i,r){var n,s,o,a,h,l=this.getHeightOfLine(t),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[t];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)h=g===_||this.charSpacing,u+=f[g],o=this.__charBounds[t][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(t,g),s=this.getCompleteStyleDeclaration(t,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(t,g)||{},e.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(t,i,r,n,s,o){var a=x.Object.NUM_FRACTION_DIGITS;t.push("\t\t\n')},_setSVGTextLineBg:function(e,t,i,r){for(var n,s,o=this._textLines[t],a=this.getHeightOfLine(t)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(e){for(var t=0,i=0,r=0,n={},s=0;s0?(i=0,r++,t++):!this.splitByGrapheme&&this._reSpaceAndTab.test(e.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:t,offset:i},r+=e.graphemeLines[s].length,i+=e.graphemeLines[s].length;return n},styleHas:function(e,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return t.Text.prototype.styleHas.call(this,e,i)},isEmptyStyles:function(e){if(!this.styles)return!0;var t,i,r=0,n=!1,s=this._styleMap[e],o=this._styleMap[e+1];for(var a in s&&(e=s.line,r=s.offset),o&&(n=o.line===e,t=o.offset),i=void 0===e?this.styles:{line:this.styles[e]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=m,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(h),_+n>this.dynamicMinWidth&&(this.dynamicMinWidth=_-m+n),a},isEndOfWrapping:function(e){return!this._styleMap[e+1]||this._styleMap[e+1].line!==this._styleMap[e].line},missingNewlineOffset:function(e){return this.splitByGrapheme?this.isEndOfWrapping(e)?1:0:1},_splitTextIntoLines:function(e){for(var i=t.Text.prototype._splitTextIntoLines.call(this,e),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},k={};function B(e){var t=k[e];if(void 0!==t)return t.exports;var i=k[e]={exports:{}};return P[e](i,i.exports,B),i.exports}B.d=(e,t)=>{for(var i in t)B.o(t,i)&&!B.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},B.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var N={};(()=>{let e;B.d(N,{R:()=>e}),e="undefined"!=typeof document&&"undefined"!=typeof window?B(653).fabric:{version:"5.2.1"}})();var j=N.R; +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.DBR={}))}(this,(function(e){"use strict";const t="undefined"==typeof self;let i,r,n,s,o;if("undefined"!=typeof navigator&&(i=navigator,r=i.userAgent,n=i.platform,s=i.mediaDevices),!t){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:i.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:n,search:"Win"},Mac:{str:n},Linux:{str:n}};let s="unknownBrowser",a=0,h="unknownOS";for(let t in e){const i=e[t]||{};let n=i.str||r,o=i.search||t,h=i.verStr||r,l=i.verSearch||t;if(l instanceof Array||(l=[l]),-1!=n.indexOf(o)){s=t;for(let e of l){let t=h.indexOf(e);if(-1!=t){a=parseFloat(h.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let n=i.str||r,s=i.search||e;if(-1!=n.indexOf(s)){h=e;break}}"Linux"==h&&-1!=r.indexOf("Windows NT")&&(h="HarmonyOS"),o={browser:s,version:a,OS:h}}t&&(o={browser:"ssr",version:0,OS:"ssr"});const a="undefined"!=typeof WebAssembly&&r&&!(/Safari/.test(r)&&!/Chrome/.test(r)&&/\(.+\s11_2_([2-6]).*\)/.test(r)),h=!("undefined"==typeof Worker),l=!(!s||!s.getUserMedia),c=async()=>{let e=!1;if(l)try{(await s.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===o.browser&&o.version>66||"Safari"===o.browser&&o.version>13||"OPR"===o.browser&&o.version>43||"Edge"===o.browser&&o.version;const u=(()=>{if(!t&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),d=" is not allowed to change after `createInstance` or `loadWasm` is called.",f=!t&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",g=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",_=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let i=0;ie&&"object"==typeof e&&"function"==typeof e.then;class w extends Promise{constructor(e){let t,i;super(((e,r)=>{t=e,i=r})),this._s="pending",this.resolve=e=>{this.isPending&&(C(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,C(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}var b=function(){this.init()};b.prototype={init:function(){var e=this||x;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||x;if(e=parseFloat(e),t.ctx||M(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,x.ctx.currentTime);for(var i=0;i=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,M()),e},codecs:function(e){return(this||x)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||x;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||x,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var i=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",n=r.match(/OPR\/([0-6].)/g),s=n&&parseInt(n[0].split("/")[1],10)<33,o=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),a=r.match(/Version\/(.*?) /),h=o&&a&&parseInt(a[1],10)<15;return e._codecs={mp3:!(s||!i&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!i,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(h||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(h||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||x;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(i){for(;e._html5AudioPool.length0?o._seek:i._sprite[e][0]/1e3),l=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-h),c=1e3*l/Math.abs(o._rate),u=i._sprite[e][0]/1e3,d=(i._sprite[e][0]+i._sprite[e][1])/1e3;o._sprite=e,o._ended=!1;var f=function(){o._paused=!1,o._seek=h,o._start=u,o._stop=d,o._loop=!(!o._loop&&!i._sprite[e][2])};if(!(h>=d)){var g=o._node;if(i._webAudio){var _=function(){i._playLock=!1,f(),i._refreshBuffer(o);var e=o._muted||i._muted?0:o._volume;g.gain.setValueAtTime(e,x.ctx.currentTime),o._playStart=x.ctx.currentTime,void 0===g.bufferSource.start?o._loop?g.bufferSource.noteGrainOn(0,h,86400):g.bufferSource.noteGrainOn(0,h,l):o._loop?g.bufferSource.start(0,h,86400):g.bufferSource.start(0,h,l),c!==1/0&&(i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c)),t||setTimeout((function(){i._emit("play",o._id),i._loadQueue()}),0)};"running"===x.state&&"interrupted"!==x.ctx.state?_():(i._playLock=!0,i.once("resume",_),i._clearTimer(o._id))}else{var p=function(){g.currentTime=h,g.muted=o._muted||i._muted||x._muted||g.muted,g.volume=o._volume*x.volume(),g.playbackRate=o._rate;try{var r=g.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(i._playLock=!0,f(),r.then((function(){i._playLock=!1,g._unlocked=!0,t?i._loadQueue():i._emit("play",o._id)})).catch((function(){i._playLock=!1,i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),o._ended=!0,o._paused=!0}))):t||(i._playLock=!1,f(),i._emit("play",o._id)),g.playbackRate=o._rate,g.paused)return void i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||o._loop?i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c):(i._endTimers[o._id]=function(){i._ended(o),g.removeEventListener("ended",i._endTimers[o._id],!1)},g.addEventListener("ended",i._endTimers[o._id],!1))}catch(e){i._emit("playerror",o._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=i._src,g.load());var m=window&&window.ejecta||!g.readyState&&x._navigator.isCocoonJS;if(g.readyState>=3||m)p();else{i._playLock=!0,i._state="loading";var v=function(){i._state="loaded",p(),g.removeEventListener(x._canPlayEvent,v,!1)};g.addEventListener(x._canPlayEvent,v,!1),i._clearTimer(o._id)}}return o._id}i._ended(o)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),r=0;r=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(i=t?r._soundById(t):r._sounds[0])?i._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,n)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var a=0;a0?r/l:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=h*n,a=Math.round(100*a)/100,a=h<0?Math.max(i,a):Math.min(i,a),o._webAudio?e._volume=a:o.volume(a,e._id,!0),s&&(o._volume=a),(it&&a>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,o.volume(i,e._id),o._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,i=t._soundById(e);return i&&i._interval&&(t._webAudio&&i._node.gain.cancelScheduledValues(x.ctx.currentTime),clearInterval(i._interval),i._interval=null,t.volume(i._fadeTo,e),i._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,i,r=this,n=arguments;if(0===n.length)return r._loop;if(1===n.length){if("boolean"!=typeof n[0])return!!(i=r._soundById(parseInt(n[0],10)))&&i._loop;e=n[0],r._loop=e}else 2===n.length&&(e=n[0],t=parseInt(n[1],10));for(var s=r._getSoundIds(t),o=0;o=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else 2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if("number"!=typeof e)return(i=r._soundById(t))?i._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,n)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var a=0;a=0?t=parseInt(r[0],10):i._sounds.length&&(t=i._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==i._state||i._playLock))return i._queue.push({event:"seek",action:function(){i.seek.apply(i,r)}}),i;var o=i._soundById(t);if(o){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var a=i.playing(t)?x.ctx.currentTime-o._playStart:0,h=o._rateSeek?o._rateSeek-o._seek:0;return o._seek+(h+a*Math.abs(o._rate))}return o._node.currentTime}var l=i.playing(t);l&&i.pause(t,!0),o._seek=e,o._ended=!1,i._clearTimer(t),i._webAudio||!o._node||isNaN(o._node.duration)||(o._node.currentTime=e);var c=function(){l&&i.play(t,!0),i._emit("seek",t)};if(l&&!i._webAudio){var u=function(){i._playLock?setTimeout(u,0):c()};setTimeout(u,0)}else c()}return i},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var r=0;r=0&&x._howls.splice(r,1);var n=!0;for(i=0;i=0){n=!1;break}return I&&n&&delete I[e._src],x.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,r){var n=this["_on"+e];return"function"==typeof t&&n.push(r?{id:i,fn:t,once:r}:{id:i,fn:t}),this},off:function(e,t,i){var r=this,n=r["_on"+e],s=0;if("number"==typeof t&&(i=t,t=null),t||i)for(s=0;s=0;s--)n[s].id&&n[s].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(r,n[s].fn),0),n[s].once&&r.off(e,n[s].fn,n[s].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var t=this,i=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(i<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i=0;if(!e.bufferSource)return this;if(x._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=x._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(x._navigator&&x._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var E=function(e){this._parent=e,this.init()};E.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++x._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=x._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===x.ctx.createGain?x.ctx.createGainNode():x.ctx.createGain(),e._node.gain.setValueAtTime(i,x.ctx.currentTime),e._node.paused=!0,e._node.connect(x.masterGain)):x.noAudio||(e._node=x._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(x._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*x.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++x._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(x._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var I={},A=function(e){var t=e._src;if(I[t])return e._duration=I[t].duration,void D(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(I[t._src]=e,D(t,e)):i()};"undefined"!=typeof Promise&&1===x.ctx.decodeAudioData.length?x.ctx.decodeAudioData(e).then(r).catch(i):x.ctx.decodeAudioData(e,r,i)},D=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},M=function(){if(x.usingWebAudio){try{"undefined"!=typeof AudioContext?x.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?x.ctx=new webkitAudioContext:x.usingWebAudio=!1}catch(e){x.usingWebAudio=!1}x.ctx||(x.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(x._navigator&&x._navigator.platform),t=x._navigator&&x._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var r=/safari/.test(x._navigator&&x._navigator.userAgent.toLowerCase());x._navigator&&!r&&(x.usingWebAudio=!1)}x.usingWebAudio&&(x.masterGain=void 0===x.ctx.createGain?x.ctx.createGainNode():x.ctx.createGain(),x.masterGain.gain.setValueAtTime(x._muted?0:x._volume,x.ctx.currentTime),x.masterGain.connect(x.ctx.destination)),x._setup()}};!function(e,t,i,r){var n;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},e.prototype.pos=function(e,i,r){var n=this;return n.ctx&&n.ctx.listener?(i="number"!=typeof i?n._pos[1]:i,r="number"!=typeof r?n._pos[2]:r,"number"!=typeof e?n._pos:(n._pos=[e,i,r],void 0!==n.ctx.listener.positionX?(n.ctx.listener.positionX.setTargetAtTime(n._pos[0],t.ctx.currentTime,.1),n.ctx.listener.positionY.setTargetAtTime(n._pos[1],t.ctx.currentTime,.1),n.ctx.listener.positionZ.setTargetAtTime(n._pos[2],t.ctx.currentTime,.1)):n.ctx.listener.setPosition(n._pos[0],n._pos[1],n._pos[2]),n)):n},e.prototype.orientation=function(e,i,r,n,s,o){var a=this;if(!a.ctx||!a.ctx.listener)return a;var h=a._orientation;return i="number"!=typeof i?h[1]:i,r="number"!=typeof r?h[2]:r,n="number"!=typeof n?h[3]:n,s="number"!=typeof s?h[4]:s,o="number"!=typeof o?h[5]:o,"number"!=typeof e?h:(a._orientation=[e,i,r,n,s,o],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(i,t.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(n,t.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(s,t.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(o,t.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,i,r,n,s,o),a)},i.prototype.init=(n=i.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],n.call(this,e)}),i.prototype.stereo=function(e,i){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,i)}}),r;var n=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var o=r._getSoundIds(i),a=0;a{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=F,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+d);i._license=t})(L,e)}static get productKeys(){return this._license}static set productKeys(e){L.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){L.license=e}static get organizationID(){return this._license}static set organizationID(e){L.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+d);i._sessionPassword=t})(L,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:a,worker:h,getUserMedia:l,camera:await c(),browser:o.browser,version:o.version,OS:o.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");L._engineResourcePath=(e=>{if(null==e&&(e="./"),!t){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+d);i._licenseServer=_(t)})(L,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+d);i._deviceFriendlyName=t||""})(L,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");L.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&(("colorMode"in e||"pixelFormat"in e)&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=L._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",L.engineResourcePath)}static set defaultUIElementURL(e){L._defaultUIElementURL=e}static _fireHTTPSWarnning(){L.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{L.onWarning&&L.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new T({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;L._onLog&&L._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const i=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else i||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let t=await this._decode_DCEFrame(e,{bCopyData:!1}),i=null;if(t&&t.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:h}=e;i=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(i,r,n,a,h,s,o)}if(this._drawResults(i,t),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(L._onLog&&L._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!L.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:i,sp:r,rmk:n}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,i,r=t._license||"",n=JSON.parse(JSON.stringify(t._licenseServer)),s=t._sessionPassword,o=0;if(r.startsWith("t")||r.startsWith("f"))o=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))o=1;else{o=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t;try{let e=r.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===n.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),n=_(e)}!s&&t.sessionPassword&&(s=t.sessionPassword),e=t.remark}("200001"===r||r.startsWith("200001-"))&&(n&&n.length||(r="")),r||(o=1)}if(o&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==o)throw new Error(i);o=0,console.warn(i),t._lastErrorCode=-1,t._lastErrorString=i}return 1===o&&(r="",console.warn("Applying for a public trial license ...")),{lt:o,l:r,ls:n,sp:s,rmk:e}}throw new Error("Can't preprocess license again"+d)})(L);this._pLoad.task=async(s,a)=>{let h=L.engineResourcePath+L._workerName;L.engineResourcePath.startsWith(location.origin)||(h=await fetch(h).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),L._dbrWorker=new Worker(h),L._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},L._dbrWorker.onmessage=async t=>{let i=t.data?t.data:t;switch(i.type){case"log":L._onLog&&L._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0,i.message||(i.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),i.success?(L._dbrWorker.onerror=null,L._version=i.version+"(JS "+L._jsVersion+"."+L._jsEditVersion+")",L._onLog&&L._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(t=new Error(i.message),t.stack=i.stack+"\n"+t.stack,t.ltsErrorCode=i.ltsErrorCode,r||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&L.showDialog(i.success?"warn":"error",i.message),i.success?s():a(t);break}case"task":{let e=i.id,t=i.body;try{L._taskCallbackMap.get(e)(t),L._taskCallbackMap.delete(e)}catch(t){throw L._taskCallbackMap.delete(e),t}break}default:L._onLog&&L._onLog(t)}},L._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:L.engineResourcePath,bUseFullFeature:L._bUseFullFeature,bd:L._bWasmDebug,v:L._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:o,cv:L.authCacheVersion,fn:L.deviceFriendlyName,ls:i,sp:r,rmk:n})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,i)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let e=0;e{if(e==t.target){a.remove();for(let e of o)e.remove()}}));else if(!l&&e.classList.contains("dls-license-icon-close"))l=e,e.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!d&&e.classList.contains("dls-license-msg-content")){d=e;let t=i;for(;t;){let i=t.indexOf("["),r=t.indexOf("]",i),n=t.indexOf("(",r),s=t.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){e.appendChild(new Text(t));break}i>0&&e.appendChild(new Text(t.substring(0,i)));let o=document.createElement("a"),a=t.substring(i+1,r);o.innerText=a;let h=t.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),e.appendChild(o),t=t.substring(s+1)}}document.body.appendChild(a)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await L.loadWasm(),await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new L;return e._instanceID=await L.createInstanceInWorker(),L._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){L._onLog&&L._onLog("decode(source: any)"),L._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):L.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):L.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,i,r,n,s,o){return await new Promise(((a,h)=>{let l=L._nextTaskID++;L._taskCallbackMap.set(l,(e=>{if(e.success){let t,i=L._onLog?Date.now():0;L._onLog&&L._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return h(e)}if(L._onLog){let e=Date.now();L._onLog("DBR getting message from worker timestamp: "+i),L._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),L._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),L._onLog("Handling results from DBR worker costs: "+(e-i)),L._onLog("Total decoding image costs: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}})),this._timeEnterInnerDBR=Date.now(),L._onLog&&L._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),L._dbrWorker.postMessage({type:"decodeBuffer",id:l,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,orientation:s,config:o}},[e.buffer]),L._onLog&&o&&o.timeStamp&&L._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s,o){L._onLog&&L._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,i,r,n,s,o)}async decodeBuffer(e,t,i,r,n,s,o){let a;return L._onLog&&L._onLog("decodeBuffer(buffer,width,height,stride,format)"),L._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,i,r,n,s,o):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,r,n,s,o):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,i,r,n,s,o)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success){let t=JSON.parse(i.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let i;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=3,i.expectedBarcodesCount=0,i.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=5,i.expectedBarcodesCount=512,i.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=9,i.expectedBarcodesCount=0,i.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,i.region=e.region,i.deblurLevel=3,i.expectedBarcodesCount=0,i.localizationModes=[2,8,0,0,0,0,0,0]}else i=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(i=JSON.parse(JSON.stringify(t)),i.region instanceof Array){let e=i.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(i.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!L._bUseFullFeature){if(0!=(i.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=i.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=i.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=i.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,i.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(i.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,t)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(i=>{if(i.success){try{this._handleRetJsonString(i.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(i)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=F,await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=F,await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!L._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!L._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){i(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){L._onLog&&L._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(r=await function(e){return new Promise(((t,i)=>{let r=URL.createObjectURL(e),n=new Image;n.dbrObjUrl=r,n.src=r,n.onload=()=>{t(n)},n.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let n=await this._decode_Image(i||r,t);return i&&i.close(),n}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){L._onLog&&L._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let i,r,n=e instanceof HTMLImageElement?e.naturalWidth:e.width,s=e instanceof HTMLImageElement?e.naturalHeight:e.height,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(a,t)}async _decode_Canvas(t,i){if(L._onLog&&L._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let r=(t.ctx2d||t.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(r,t.width,t.height,4*t.width,e.EnumImagePixelFormat.IPF_ABGR_8888,0,i)}async _decode_Video(e,t){if(L._onLog&&L._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let i,r,n=e.videoWidth,s=e.videoHeight,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),await this._decode_Canvas(a,t)}async _decode_DCEFrame(t,i){if(L._onLog&&L._onLog("_decode_DCEFrame(dceFrame)"),!L.isDCEFrame(t))return[];let r=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:n,height:s,colorMode:o,pixelFormat:a,stride:h,timeStamp:l}=t;let c;c=i&&i.bCopyData?new Uint8Array(t.data):t.data;let u=null;if(i?(u=JSON.parse(JSON.stringify(i)),u.timeStamp=l):u={timeStamp:l},a&&h)if("grey"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,h,e.EnumImagePixelFormat.IPF_GrayScaled,0,u);else if("rgba"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,h,e.EnumImagePixelFormat.IPF_ABGR_8888,0,u);else{if("bgra"!==a)throw new Error(`Pixel format '${a}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(c,n,s,h,e.EnumImagePixelFormat.IPF_ARGB_8888,0,u)}else if("grey"===o)r=await this._decodeBuffer_Uint8Array(c,n,s,n,e.EnumImagePixelFormat.IPF_GrayScaled,0,u);else if("rgba"===o)r=await this._decodeBuffer_Uint8Array(c,n,s,4*n,e.EnumImagePixelFormat.IPF_ABGR_8888,0,u);else{if("bgra"!==o)throw new Error(`Color mode '${o}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(c,n,s,4*n,e.EnumImagePixelFormat.IPF_ARGB_8888,0,u)}return r}async _decode_DSImage(t,i){if(L._onLog&&L._onLog("_decode_DSImage(dsImage)"),!L.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,t)}}async _decode_FilePath(e,t){throw L._onLog&&L._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,i,r,n,s,o){if(e.length>0)for(let a of e){let e=a.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*s,e.x2*=.01*s,e.x3*=.01*s,e.x4*=.01*s,e.y1*=.01*o,e.y2*=.01*o,e.y3*=.01*o,e.y4*=.01*o);let h=s/r,l=o/n;e.x1=e.x1/h+t,e.x2=e.x2/h+t,e.x3=e.x3/h+t,e.x4=e.x4/h+t,e.y1=e.y1/l+i,e.y2=e.y2/l+i,e.y3=e.y3/l+i,e.y4=e.y4/l+i,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/n,e.y2*=100/n,e.y3*=100/n,e.y4*=100/n)}}static BarcodeReaderException(t,i){let r,n=e.EnumErrorCode.DBR_UNKNOWN;return"number"==typeof t?(n=t,r=new Error(i)):r=new Error(t),r.code=n,r}_handleRetJsonString(t){let i=e.EnumErrorCode;if(t.textResults){for(let e=0;e{let i=t.indexOf(":");e[t.substring(0,i)]=t.substring(i+1)})),i.exception=e}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!L._setWarnnedEx.has(t.description)&&(L._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==i.DBR_SUCCESS)return t.data;throw L.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=L._nextTaskID++;L._taskCallbackMap.set(o,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return s(e)}return n()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),L._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:r}})}))}async getModeArgument(e,t,i){return await new Promise(((r,n)=>{let s=L._nextTaskID++;L._taskCallbackMap.set(s,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return n(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),L._dbrWorker.postMessage({type:"getModeArgument",id:s,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),i=[];for(let r of t)if(r.dataType==e.EnumIMResultDataType.IMRDT_IMAGE)for(let t of r.results){const r=t.bytes;let n;switch(L._onLog&&L._onLog(" "+r.length+" "+r.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case e.EnumImagePixelFormat.IPF_ABGR_8888:n=new Uint8ClampedArray(r);break;case e.EnumImagePixelFormat.IPF_RGB_888:{const e=r.length/3;n=new Uint8ClampedArray(4*e);for(let t=0;t=i)break;n[o]=n[o+1]=n[o+2]=(128&e)/128*255,n[o+3]=255,e<<=1}}break}default:console.warn("unknow intermediate image",t)}if(!n)continue;let s=new ImageData(n,t.width,t.height),o=document.createElement("canvas");o.width=t.width,o.height=t.height,o.getContext("2d").putImageData(s,0,0),i.push(o)}return i}async getScanSettings(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success){let t=i.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t.autoZoom=this.autoZoom,t.autoFocus=this.autoFocus,t.autoSuggestTip=this.autoSuggestTip,e(t)}{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),L._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(t){if(!t)return;const i=JSON.parse(JSON.stringify(t));if(i.autoZoom||i.autoFocus||i.autoSuggestTip){if(!L._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const t=await this.getRuntimeSettings();t.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(t)}return i.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(i.intervalTime,0),delete i.intervalTime),i.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=i.whenToPlaySoundforSuccessfulRead,delete i.whenToPlaySoundforSuccessfulRead),i.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=i.soundOnSuccessfullRead,delete i.soundOnSuccessfullRead),i.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=i.whenToVibrateforSuccessfulRead,delete i.whenToVibrateforSuccessfulRead),i.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=i.vibrateDuration,delete i.vibrateDuration),i.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=i.captureAndDecodeInParallel,delete i.captureAndDecodeInParallel),i.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=i.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=i.autoZoom,delete i.autoZoom),i.hasOwnProperty("autoFocus")&&(this.autoFocus=i.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete i.autoFocus),i.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=i.autoSuggestTip,delete i.autoFocus),await new Promise(((e,t)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),L._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:i}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let i of e)t.push(this._cloneDecodeResults(i));return t}{let t=e,i=JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return L._onLog&&L._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));L._onLog&&L._onLog("======= once read ======="),L._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!L.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return L._onLog&&L._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(e){i=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(i&&i.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:h}=e;t=i.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(t,r,n,a,h,s,o)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t,i),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else t&&(i=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return i})().then((e=>{if(L._onLog&&L._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const i=()=>{let i=0;if(t&&t.length){let r=Math.min(...e),n=Math.max(...t);r&&n&&(i=r-n)}else i=0;return i>0?i:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),L._onLog&&L._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(L._onLog&&L._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};t(e)}else L._onLog&&L._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e,t){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const i=this._dbrDrawingLayer;e||(e=[]);let r=this._arrPolygons;for(let n=0;n{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(t),t}stopScanning(e){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[e]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(e){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(L._onLog&&L._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let e=L._nextTaskID++;L._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),L._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}L._jsVersion="9.6.11",L._jsEditVersion="20230310",L._version=`loading...(JS ${L._jsVersion}.${L._jsEditVersion})`,L._license=f,L._sessionPassword=g,L.browserInfo=o,L._workerName=`dbr-${L._jsVersion}.browser.worker.js`,L._engineResourcePath=u,L._licenseServer=[],L._deviceFriendlyName="",L._isShowRelDecodeTimeInResults=!1,L._bWasmDebug=!1,L._bNeverShowDialog=!1,L.__bUseFullFeature=!0,L._nextTaskID=0,L._taskCallbackMap=new Map,L._pLoad=new w,L._lastErrorCode=0,L._lastErrorString="",L._setWarnnedEx=new Set,L._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var P={653:(e,t,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,_,p,m,v,y,S,C,w,b,x=x||{version:"5.2.1"};if(t.fabric=x,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?x.document=document:x.document=document.implementation.createHTMLDocument(""),x.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;x.document=T.document,x.jsdomImplForWrapper=i(898).implForWrapper,x.nodeCanvas=i(245).Canvas,x.window=T,DOMParser=x.window.DOMParser}function E(e,t){var i=e.canvas,r=t.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function I(e,t){var i=t.targetCanvas.getContext("2d"),r=t.destinationWidth,n=t.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}x.isTouchSupported="ontouchstart"in x.window||"ontouchstart"in x.document||x.window&&x.window.navigator&&x.window.navigator.maxTouchPoints>0,x.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,x.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],x.DPI=96,x.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",x.commaWsp="(?:\\s+,?\\s*|,\\s*)",x.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,x.reNonWord=/[ \n\.,;!\?\-]/,x.fontPaths={},x.iMatrix=[1,0,0,1,0,0],x.svgNS="http://www.w3.org/2000/svg",x.perfLimitSizeTotal=2097152,x.maxCacheSideLimit=4096,x.minCacheSideLimit=256,x.charWidthsCache={},x.textureSize=2048,x.disableStyleCopyPaste=!1,x.enableGLFiltering=!0,x.devicePixelRatio=x.window.devicePixelRatio||x.window.webkitDevicePixelRatio||x.window.mozDevicePixelRatio||1,x.browserShadowBlurConstant=1,x.arcToSegmentsCache={},x.boundsOfCurveCache={},x.cachesBoundsOfCurve=!0,x.forceGLPutImageData=!1,x.initFilterBackend=function(){return x.enableGLFiltering&&x.isWebglSupported&&x.isWebglSupported(x.textureSize)?(console.log("max texture size: "+x.maxTextureSize),new x.WebglFilterBackend({tileSize:x.textureSize})):x.Canvas2dFilterBackend?new x.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=x),function(){function e(e,t){if(this.__eventListeners[e]){var i=this.__eventListeners[e];t?i[i.indexOf(t)]=!1:x.util.array.fill(i,!1)}}function t(e,t){var i=function(){t.apply(this,arguments),this.off(e,i)}.bind(this);this.on(e,i)}x.Observable={fire:function(e,t){if(!this.__eventListeners)return this;var i=this.__eventListeners[e];if(!i)return this;for(var r=0,n=i.length;r-1||!!t&&this._objects.some((function(t){return"function"==typeof t.contains&&t.contains(e,!0)}))},complexity:function(){return this._objects.reduce((function(e,t){return e+(t.complexity?t.complexity():0)}),0)}},x.CommonMethods={_setOptions:function(e){for(var t in e)this.set(t,e[t])},_initGradient:function(e,t){!e||!e.colorStops||e instanceof x.Gradient||this.set(t,new x.Gradient(e))},_initPattern:function(e,t,i){!e||!e.source||e instanceof x.Pattern?i&&i():this.set(t,new x.Pattern(e,i))},_setObject:function(e){for(var t in e)this._set(t,e[t])},set:function(e,t){return"object"==typeof e?this._setObject(e):this._set(e,t),this},_set:function(e,t){this[e]=t},toggle:function(e){var t=this.get(e);return"boolean"==typeof t&&this.set(e,!t),this},get:function(e){return this[e]}},r=t,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,x.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},sin:function(e){if(0===e)return 0;var t=1;switch(e<0&&(t=-1),e/h){case 1:return t;case 2:return 0;case 3:return-t}return Math.sin(e)},removeFromArray:function(e,t){var i=e.indexOf(t);return-1!==i&&e.splice(i,1),e},getRandomInt:function(e,t){return Math.floor(Math.random()*(t-e+1))+e},degreesToRadians:function(e){return e*a},radiansToDegrees:function(e){return e/a},rotatePoint:function(e,t,i){var r=new x.Point(e.x-t.x,e.y-t.y),n=x.util.rotateVector(r,i);return new x.Point(n.x,n.y).addEquals(t)},rotateVector:function(e,t){var i=x.util.sin(t),r=x.util.cos(t);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}},createVector:function(e,t){return new x.Point(t.x-e.x,t.y-e.y)},calcAngleBetweenVectors:function(e,t){return Math.acos((e.x*t.x+e.y*t.y)/(Math.hypot(e.x,e.y)*Math.hypot(t.x,t.y)))},getHatVector:function(e){return new x.Point(e.x,e.y).multiply(1/Math.hypot(e.x,e.y))},getBisector:function(e,t,i){var r=x.util.createVector(e,t),n=x.util.createVector(e,i),s=x.util.calcAngleBetweenVectors(r,n),o=s*(0===x.util.calcAngleBetweenVectors(x.util.rotateVector(r,s),n)?1:-1)/2;return{vector:x.util.getHatVector(x.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(e,t,i){var r=[],n=t.strokeWidth/2,s=t.strokeUniform?new x.Point(1/t.scaleX,1/t.scaleY):new x.Point(1,1),o=function(e){var t=n/Math.hypot(e.x,e.y);return new x.Point(e.x*t*s.x,e.y*t*s.y)};return e.length<=1||e.forEach((function(a,h){var l,c,u=new x.Point(a.x,a.y);0===h?(c=e[h+1],l=i?o(x.util.createVector(c,u)).addEquals(u):e[e.length-1]):h===e.length-1?(l=e[h-1],c=i?o(x.util.createVector(l,u)).addEquals(u):e[0]):(l=e[h-1],c=e[h+1]);var d,f,g=x.util.getBisector(u,l,c),_=g.vector,p=g.angle;if("miter"===t.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new x.Point(_.x*d*s.x,_.y*d*s.y),Math.hypot(f.x,f.y)/n<=t.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new x.Point(_.x*d*s.x,_.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(e,t,i){return i?new x.Point(t[0]*e.x+t[2]*e.y,t[1]*e.x+t[3]*e.y):new x.Point(t[0]*e.x+t[2]*e.y+t[4],t[1]*e.x+t[3]*e.y+t[5])},makeBoundingBoxFromPoints:function(e,t){if(t)for(var i=0;i0&&(t>r?t-=r:t=0,i>r?i-=r:i=0);var n,s=!0,o=e.getImageData(t,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(e,t,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(e,t,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=x.util.sin(c),d=x.util.cos(c),f=0,g=0,_=-d*e*.5-u*t*.5,p=-d*t*.5+u*e*.5,m=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,S=_*_,C=m*v-m*y-v*S,w=0;if(C<0){var b=Math.sqrt(1-C/(m*v));i*=b,s*=b}else w=(o===a?-1:1)*Math.sqrt(C/(m*y+v*S));var T=w*i*p/s,E=-w*s*_/i,I=d*T-u*E+.5*e,A=u*T+d*E+.5*t,O=n(1,0,(_-T)/i,(p-E)/s),R=n((_-T)/i,(p-E)/s,(-_-T)/i,(-p-E)/s);0===a&&R>0?R-=2*l:1===a&&R<0&&(R+=2*l);for(var D=Math.ceil(Math.abs(R/l*2)),M=[],F=R/D,L=8/3*Math.sin(F/4)*Math.sin(F/4)/Math.sin(F/2),P=O+F,k=0;kw)for(var T=1,E=_.length;T2;for(t=t||0,l&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,h=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+h*t]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(t,i,r,n,s,o,a,h){var l;if(x.cachesBoundsOfCurve&&(l=e.call(arguments),x.boundsOfCurveCache[l]))return x.boundsOfCurveCache[l];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,C=Math.abs,w=[],b=[[],[]];u=6*t-12*r+6*s,c=-3*t+9*r-9*s+3*a,d=3*r-3*t;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&w.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&w.push(g),0<(_=(-u-m)/(2*c))&&_<1&&w.push(_));for(var E,I,A,O=w.length,R=O;O--;)E=(A=1-(f=w[O]))*A*A*t+3*A*A*f*r+3*A*f*f*s+f*f*f*a,b[0][O]=E,I=A*A*A*i+3*A*A*f*n+3*A*f*f*o+f*f*f*h,b[1][O]=I;b[0][R]=t,b[1][R]=i,b[0][R+1]=a,b[1][R+1]=h;var D=[{x:y.apply(null,b[0]),y:y.apply(null,b[1])},{x:S.apply(null,b[0]),y:S.apply(null,b[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=D),D},x.util.getPointOnPath=function(e,t,i){i||(i=d(e));for(var r=0;t-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>t?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,t)}},x.util.transformPath=function(e,t,i){return i&&(t=x.util.multiplyTransformMatrices(t,[1,0,0,1,-i.x,-i.y])),e.map((function(e){for(var i=e.slice(0),r={},n=1;n=t}))}}}(),function(){function e(t,i,r){if(r)if(!x.isLikelyNode&&i instanceof Element)t=i;else if(i instanceof Array){t=[];for(var n=0,s=i.length;n57343)return e.charAt(t);if(55296<=i&&i<=56319){if(e.length<=t+1)throw"High surrogate without following low surrogate";var r=e.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return e.charAt(t)+e.charAt(t+1)}if(0===t)throw"Low surrogate without preceding high surrogate";var n=e.charCodeAt(t-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}x.util.string={camelize:function(e){return e.replace(/-+(.)?/g,(function(e,t){return t?t.toUpperCase():""}))},capitalize:function(e,t){return e.charAt(0).toUpperCase()+(t?e.slice(1):e.slice(1).toLowerCase())},escapeXml:function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(t){var i,r=0,n=[];for(r=0;r-1?e.prototype[n]=function(e){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=t[e].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==e)return n}}(n):e.prototype[n]=t[n],i&&(t.toString!==Object.prototype.toString&&(e.prototype.toString=t.toString),t.valueOf!==Object.prototype.valueOf&&(e.prototype.valueOf=t.valueOf))};function n(){}function s(t){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[t];if(r[t]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,e.call(arguments,1)):i.call(this):console.log("tried to callSuper "+t+", method not found in prototype chain",this)}x.util.createClass=function(){var i=null,o=e.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===e.pointerType},d="string"==typeof(u=x.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(e){return e},d?_=function(e,t){return e.style.opacity=t,e}:f&&(_=function(e,t){var i=e.style;return e.currentStyle&&!e.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(t=t>=.9999?"":"alpha(opacity="+100*t+")",i.filter=i.filter.replace(g,t)):i.filter+=" alpha(opacity="+100*t+")",e}),x.util.setStyle=function(e,t){var i=e.style;if(!i)return e;if("string"==typeof t)return e.style.cssText+=";"+t,t.indexOf("opacity")>-1?_(e,t.match(/opacity:\s*(\d?\.?\d*)/)[1]):e;for(var r in t)"opacity"===r?_(e,t[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=t[r];return e},function(){var e,t,i,r,n=Array.prototype.slice,s=function(e){return n.call(e,0)};try{e=s(x.document.childNodes)instanceof Array}catch(e){}function o(e,t){var i=x.document.createElement(e);for(var r in t)"class"===r?i.className=t[r]:"for"===r?i.htmlFor=t[r]:i.setAttribute(r,t[r]);return i}function a(e){for(var t=0,i=0,r=x.document.documentElement,n=x.document.body||{scrollLeft:0,scrollTop:0};e&&(e.parentNode||e.host)&&((e=e.parentNode||e.host)===x.document?(t=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(t+=e.scrollLeft||0,i+=e.scrollTop||0),1!==e.nodeType||"fixed"!==e.style.position););return{left:t,top:i}}e||(s=function(e){for(var t=new Array(e.length),i=e.length;i--;)t[i]=e[i];return t}),t=x.document.defaultView&&x.document.defaultView.getComputedStyle?function(e,t){var i=x.document.defaultView.getComputedStyle(e,null);return i?i[t]:void 0}:function(e,t){var i=e.style[t];return!i&&e.currentStyle&&(i=e.currentStyle[t]),i},i=x.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",x.util.makeElementUnselectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=x.util.falseFunction),r?e.style[r]="none":"string"==typeof e.unselectable&&(e.unselectable="on"),e},x.util.makeElementSelectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=null),r?e.style[r]="":"string"==typeof e.unselectable&&(e.unselectable=""),e},x.util.setImageSmoothing=function(e,t){e.imageSmoothingEnabled=e.imageSmoothingEnabled||e.webkitImageSmoothingEnabled||e.mozImageSmoothingEnabled||e.msImageSmoothingEnabled||e.oImageSmoothingEnabled,e.imageSmoothingEnabled=t},x.util.getById=function(e){return"string"==typeof e?x.document.getElementById(e):e},x.util.toArray=s,x.util.addClass=function(e,t){e&&-1===(" "+e.className+" ").indexOf(" "+t+" ")&&(e.className+=(e.className?" ":"")+t)},x.util.makeElement=o,x.util.wrapElement=function(e,t,i){return"string"==typeof t&&(t=o(t,i)),e.parentNode&&e.parentNode.replaceChild(t,e),t.appendChild(e),t},x.util.getScrollLeftTop=a,x.util.getElementOffset=function(e){var i,r,n=e&&e.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(t(e,l),10)||0;return i=n.documentElement,void 0!==e.getBoundingClientRect&&(s=e.getBoundingClientRect()),r=a(e),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},x.util.getNodeCanvas=function(e){var t=x.jsdomImplForWrapper(e);return t._canvas||t._image},x.util.cleanUpJsdomNode=function(e){if(x.isLikelyNode){var t=x.jsdomImplForWrapper(e);t&&(t._image=null,t._canvas=null,t._currentSrc=null,t._attributes=null,t._classList=null)}}}(),function(){function e(){}x.util.request=function(t,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new x.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=e)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(t=function(e,t){return e+(/\?/.test(e)?"&":"?")+t}(t,i.parameters))),s.open(r,t,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),x.log=console.log,x.warn=console.warn,function(){var e=x.util.object.extend,t=x.util.object.clone,i=[];function r(){return!1}function n(e,t,i,r){return-i*Math.cos(e/r*(Math.PI/2))+i+t}x.util.object.extend(i,{cancelAll:function(){var e=this.splice(0);return e.forEach((function(e){e.cancel()})),e},cancelByCanvas:function(e){if(!e)return[];var t=this.filter((function(t){return"object"==typeof t.target&&t.target.canvas===e}));return t.forEach((function(e){e.cancel()})),t},cancelByTarget:function(e){var t=this.findAnimationsByTarget(e);return t.forEach((function(e){e.cancel()})),t},findAnimationIndex:function(e){return this.indexOf(this.findAnimation(e))},findAnimation:function(e){return this.find((function(t){return t.cancel===e}))},findAnimationsByTarget:function(e){return e?this.filter((function(t){return t.target===e})):[]}});var s=x.window.requestAnimationFrame||x.window.webkitRequestAnimationFrame||x.window.mozRequestAnimationFrame||x.window.oRequestAnimationFrame||x.window.msRequestAnimationFrame||function(e){return x.window.setTimeout(e,1e3/60)},o=x.window.cancelAnimationFrame||x.window.clearTimeout;function a(){return s.apply(x.window,arguments)}x.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var e=x.runningAnimations.indexOf(s);return e>-1&&x.runningAnimations.splice(e,1)[0]};return s=e(t(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(s),a((function(e){var t,l=e||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||n,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(e,t){return v[t]-m[t]})):v-m);i.onStart&&i.onStart(),function e(i){var r=(t=i||+new Date)>u?c:t-l,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),C=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=C,s.durationRate=n,!o){if(!f(S,C,n))return t>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(S,C,n),void a(e));h()}}(l)})),s.cancel},x.util.requestAnimFrame=a,x.util.cancelAnimFrame=function(){return o.apply(x.window,arguments)},x.runningAnimations=i}(),function(){function e(e,t,i){var r="rgba("+parseInt(e[0]+i*(t[0]-e[0]),10)+","+parseInt(e[1]+i*(t[1]-e[1]),10)+","+parseInt(e[2]+i*(t[2]-e[2]),10);return(r+=","+(e&&t?parseFloat(e[3]+i*(t[3]-e[3])):1))+")"}x.util.animateColor=function(t,i,r,n){var s=new x.Color(t).getSource(),o=new x.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},x.util.animate(x.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(t,i,r,s){return e(i,r,n.colorEasing?n.colorEasing(t,s):1-Math.cos(t/s*(Math.PI/2)))},onComplete:function(t,i,r){if(a)return a(e(o,o,0),i,r)},onChange:function(t,i,r){if(h){if(Array.isArray(t))return h(e(t,t,0),i,r);h(t,i,r)}}}))}}(),function(){function e(e,t,i,r){return e-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===e||"xlink:href"===e||"font"===e)return i;if("imageSmoothing"===e)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(e){return new RegExp("^("+e.join("|")+")\\b","i")}function g(e,t){var i,r,n,s,o=[];for(n=0,s=t.length;n1;)h.shift(),l=t.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*$");function y(e){if(!t.svgViewBoxElementsRegEx.test(e.nodeName))return{};var i,r,n,o,a,h,l=e.getAttribute("viewBox"),c=1,u=1,d=e.getAttribute("width"),f=e.getAttribute("height"),g=e.getAttribute("x")||0,_=e.getAttribute("y")||0,p=e.getAttribute("preserveAspectRatio")||"",m=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,C={},w="",b=0,x=0;if(C.width=0,C.height=0,C.toBeParsed=S,m&&(g||_)&&e.parentNode&&"#document"!==e.parentNode.nodeName&&(w=" translate("+s(g)+" "+s(_)+") ",a=(e.getAttribute("transform")||"")+w,e.setAttribute("transform",a),e.removeAttribute("x"),e.removeAttribute("y")),S)return C;if(m)return C.width=s(d),C.height=s(f),C;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=r,C.viewBoxWidth=n,C.viewBoxHeight=o,y?(C.width=n,C.height=o):(C.width=s(d),C.height=s(f),c=C.width/n,u=C.height/o),"none"!==(p=t.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),b=C.width-n*c,x=C.height-o*c,"Mid"===p.alignX&&(b/=2),"Mid"===p.alignY&&(x/=2),"Min"===p.alignX&&(b=0),"Min"===p.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return C;if((g||_)&&"#document"!==e.parentNode.nodeName&&(w=" translate("+s(g)+" "+s(_)+") "),a=w+" matrix("+c+" 0 0 "+u+" "+(i*c+b)+" "+(r*u+x)+") ","svg"===e.nodeName){for(h=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)h.appendChild(e.firstChild);e.appendChild(h)}else(h=e).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function S(e,t){var i="xlink:href",r=m(e,t.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(e,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(e){r&&!t.hasAttribute(e)&&r.hasAttribute(e)&&t.setAttribute(e,r.getAttribute(e))})),!t.children.length)for(var n=r.cloneNode(!0);n.firstChild;)t.appendChild(n.firstChild);t.removeAttribute(i)}t.parseSVGDocument=function(e,i,n,s){if(e){!function(e){for(var i=g(e,["use","svg:use"]),r=0;i.length&&re.x&&this.y>e.y},gte:function(e){return this.x>=e.x&&this.y>=e.y},lerp:function(e,t){return void 0===t&&(t=.5),t=Math.max(Math.min(1,t),0),new i(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)},distanceFrom:function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},midPointFrom:function(e){return this.lerp(e)},min:function(e){return new i(Math.min(this.x,e.x),Math.min(this.y,e.y))},max:function(e){return new i(Math.max(this.x,e.x),Math.max(this.y,e.y))},toString:function(){return this.x+","+this.y},setXY:function(e,t){return this.x=e,this.y=t,this},setX:function(e){return this.x=e,this},setY:function(e){return this.y=e,this},setFromPoint:function(e){return this.x=e.x,this.y=e.y,this},swap:function(e){var t=this.x,i=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=i},clone:function(){return new i(this.x,this.y)}})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){this.status=e,this.points=[]}t.Intersection?t.warn("fabric.Intersection is already defined"):(t.Intersection=i,t.Intersection.prototype={constructor:i,appendPoint:function(e){return this.points.push(e),this},appendPoints:function(e){return this.points=this.points.concat(e),this}},t.Intersection.intersectLineLine=function(e,r,n,s){var o,a=(s.x-n.x)*(e.y-n.y)-(s.y-n.y)*(e.x-n.x),h=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),l=(s.y-n.y)*(r.x-e.x)-(s.x-n.x)*(r.y-e.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new t.Point(e.x+c*(r.x-e.x),e.y+c*(r.y-e.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},t.Intersection.intersectLinePolygon=function(e,t,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},t.Intersection.intersectPolygonPolygon=function(e,t){var r,n=new i,s=e.length;for(r=0;r0&&(n.status="Intersection"),n},t.Intersection.intersectPolygonRectangle=function(e,r,n){var s=r.min(n),o=r.max(n),a=new t.Point(o.x,s.y),h=new t.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,e),c=i.intersectLinePolygon(a,o,e),u=i.intersectLinePolygon(o,h,e),d=i.intersectLinePolygon(h,s,e),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){e?this._tryParsingColor(e):this.setSource([0,0,0,1])}function r(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}t.Color?t.warn("fabric.Color is already defined."):(t.Color=i,t.Color.prototype={_tryParsingColor:function(e){var t;e in i.colorNameMap&&(e=i.colorNameMap[e]),"transparent"===e&&(t=[255,255,255,0]),t||(t=i.sourceFromHex(e)),t||(t=i.sourceFromRgb(e)),t||(t=i.sourceFromHsl(e)),t||(t=[0,0,0,1]),t&&this.setSource(t)},_rgbToHsl:function(e,i,r){e/=255,i/=255,r/=255;var n,s,o,a=t.util.array.max([e,i,r]),h=t.util.array.min([e,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case e:n=(i-r)/l+(i0)-(e<0)||+e};function f(e,t){var i=e.angle+u(Math.atan2(t.y,t.x))+360;return Math.round(i%360/45)}function g(e,i){var r=i.transform.target,n=r.canvas,s=t.util.object.clone(i);s.target=r,n&&n.fire("object:"+e,s),r.fire(e,i)}function _(e,t){var i=t.canvas,r=e[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(e){return e.originX===l&&e.originY===l}function m(e,t,i){var r=e.lockScalingX,n=e.lockScalingY;return!((!r||!n)&&(t||!r&&!n||!i)&&(!r||"x"!==t)&&(!n||"y"!==t))}function v(e,t,i,r){return{e,transform:t,pointer:{x:i,y:r}}}function y(e){return function(t,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=e(t,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function S(e,t){return function(i,r,n,s){var o=t(i,r,n,s);return o&&g(e,v(i,r,n,s)),o}}function C(e,i,r,n,s){var o=e.target,a=o.controls[e.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new t.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function w(e){return e.flipX!==e.flipY}function b(e,t,i,r,n){if(0!==e[t]){var s=n/e._getTransformedDimensions()[r]*e[i];e.set(i,s)}}function x(e,t,i,r){var n,l=t.target,c=l._getTransformedDimensions(0,l.skewY),d=C(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),t.originX===s&&t.originY===h&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().y;l.set("skewX",n),b(l,"skewY","scaleY","y",p)}return _}function T(e,t,i,r){var n,l=t.target,c=l._getTransformedDimensions(l.skewX,0),d=C(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),t.originX===s&&t.originY===h&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().x;l.set("skewY",n),b(l,"skewX","scaleX","x",p)}return _}function E(e,t,i,r,n){n=n||{};var s,o,a,h,l,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),w=m(f,y,S),b=t.gestureScale;if(w)return!1;if(b)o=t.scaleX*b,a=t.scaleY*b;else{if(s=C(t,t.originX,t.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,t.signX||(t.signX=l),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==l||t.signY!==u))return!1;if(h=f._getTransformedDimensions(),S&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=t.original,E=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*E,a=T.scaleY*E}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(t)&&(o*=2,a*=2),t.signX!==l&&"y"!==y&&(t.originX=c[t.originX],o*=-1,t.signX=l),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.signY=u)}var I=f.scaleX,A=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),I!==f.scaleX||A!==f.scaleY}n.scaleCursorStyleHandler=function(e,t,r){var n=_(e,r),s="";if(0!==t.x&&0===t.y?s="x":0===t.x&&0!==t.y&&(s="y"),m(r,s,n))return"not-allowed";var o=f(r,t);return i[o]+"-resize"},n.skewCursorStyleHandler=function(e,t,i){var n="not-allowed";if(0!==t.x&&i.lockSkewingY)return n;if(0!==t.y&&i.lockSkewingX)return n;var s=f(i,t)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(e,t,i){return e[i.canvas.altActionKey]?n.skewCursorStyleHandler(e,t,i):n.scaleCursorStyleHandler(e,t,i)},n.rotationWithSnapping=S("rotating",y((function(e,t,i,r){var n=t,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),w(h)&&(n=n===s?a:s)),t.originX=n,S("skewing",y(x))(e,t,i,r))},n.skewHandlerY=function(e,t,i,r){var n,a=t.target,c=a.skewY,u=t.originX;return!a.lockSkewingY&&(0===c?n=C(t,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),w(a)&&(n=n===o?h:o)),t.originY=n,S("skewing",y(T))(e,t,i,r))},n.dragHandler=function(e,t,i,r){var n=t.target,s=i-t.offsetX,o=r-t.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(e,t,i,r)),a||h},n.scaleOrSkewActionName=function(e,t,i){var r=e[i.canvas.altActionKey];return 0===t.x?r?"skewX":"scaleY":0===t.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(e,t,i){return i.lockRotation?"not-allowed":t.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=S,n.getLocalPoint=C,t.controlsUtils=n}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians,r=t.controlsUtils;r.renderCircleControl=function(e,t,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=t,d=i;e.save(),e.fillStyle=r.cornerColor||n.cornerColor,e.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,e.scale(1,a/o),d=i*o/a):a>o?(s=a,e.scale(o/a,1),u=t*a/o):s=o,e.lineWidth=1,e.beginPath(),e.arc(u,d,s/2,0,2*Math.PI,!1),e[l](),c&&e.stroke(),e.restore()},r.renderSquareControl=function(e,t,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;e.save(),e.fillStyle=n.cornerColor||s.cornerColor,e.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,e.lineWidth=1,e.translate(t,r),e.rotate(i(s.angle)),e[l+"Rect"](-u,-d,o,a),c&&e.strokeRect(-u,-d,o,a),e.restore()}}(t),function(e){var t=e.fabric||(e.fabric={});t.Control=function(e){for(var t in e)this[t]=e[t]},t.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(e,t){return t.cursorStyle},getActionName:function(e,t){return t.actionName},getVisibility:function(e,t){var i=e._controlsVisibility;return i&&void 0!==i[t]?i[t]:this.visible},setVisibility:function(e){this.visible=e},positionHandler:function(e,i){return t.util.transformPoint({x:this.x*e.x+this.offsetX,y:this.y*e.y+this.offsetY},i)},calcCornerCoords:function(e,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-t.util.degreesToRadians(e),_=Math.PI/2-d-t.util.degreesToRadians(e);o=f*t.util.cos(g),a=f*t.util.sin(g),h=f*t.util.cos(_),l=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),o=h=f*t.util.cos(g),a=l=f*t.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(e,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?t.controlsUtils.renderCircleControl.call(this,e,i,r,n,s):t.controlsUtils.renderSquareControl.call(this,e,i,r,n,s)}}}(t),function(){function e(e,t){var i,r,n,s,o=e.getAttribute("style"),a=e.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=e.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=e.getAttribute("stop-opacity")),r=(i=new x.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*t,{offset:a,color:i.toRgb(),opacity:n}}var t=x.util.object.clone;x.Gradient=x.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(e){e||(e={}),e.coords||(e.coords={});var t,i=this;Object.keys(e).forEach((function(t){i[t]=e[t]})),this.id?this.id+="_"+x.Object.__uid++:this.id=x.Object.__uid++,t={x1:e.coords.x1||0,y1:e.coords.y1||0,x2:e.coords.x2||0,y2:e.coords.y2||0},"radial"===this.type&&(t.r1=e.coords.r1||0,t.r2=e.coords.r2||0),this.coords=t,this.colorStops=e.colorStops.slice()},addColorStop:function(e){for(var t in e){var i=new x.Color(e[t]);this.colorStops.push({offset:parseFloat(t),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(e){var t={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return x.util.populateWithProperties(this,t,e),t},toSVG:function(e,i){var r,n,s,o,a=t(this.coords,!0),h=(i=i||{},t(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():x.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(e,t){return e.offset-t.offset})),"objectBoundingBox"===g?(u/=e.width,d/=e.height):(u+=e.width/2,d+=e.height/2),"path"===e.type&&"percentage"!==this.gradientUnits&&(u-=e.pathOffset.x,d-=e.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+x.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(e){var t,i,r,n=x.util.object.clone(this.coords);if(this.type){for("linear"===this.type?t=e.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(t=e.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=t.getElementsByTagName("stop"),u="userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage",d=t.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?(o="linear",a=function(e){return{x1:e.getAttribute("x1")||0,y1:e.getAttribute("y1")||0,x2:e.getAttribute("x2")||"100%",y2:e.getAttribute("y2")||0}}(t)):(o="radial",a=function(e){return{x1:e.getAttribute("fx")||e.getAttribute("cx")||"50%",y1:e.getAttribute("fy")||e.getAttribute("cy")||"50%",r1:0,x2:e.getAttribute("cx")||"50%",y2:e.getAttribute("cy")||"50%",r2:e.getAttribute("r")||"50%"}}(t)),h=c.length;h--;)f.push(e(c[h],s));return l=x.parseTransformAttribute(d),function(e,t,i,r){var n,s;Object.keys(t).forEach((function(e){"Infinity"===(n=t[e])?s=1:"-Infinity"===n?s=0:(s=parseFloat(t[e],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==e&&"x2"!==e&&"r2"!==e||(s*=i.viewBoxWidth||i.width),"y1"!==e&&"y2"!==e||(s*=i.viewBoxHeight||i.height)))),t[e]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,_=-i.top),new x.Gradient({id:t.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:_})}})}(),m=x.util.toFixed,x.Pattern=x.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(e,t){if(e||(e={}),this.id=x.Object.__uid++,this.setOptions(e),!e.source||e.source&&"string"!=typeof e.source)t&&t(this);else{var i=this;this.source=x.util.createImage(),x.util.loadImage(e.source,(function(e,r){i.source=e,t&&t(i,r)}),null,this.crossOrigin)}},toObject:function(e){var t,i,r=x.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?t=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(t=this.source.toDataURL()),i={type:"pattern",source:t,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},x.util.populateWithProperties(this,i,e),i},toSVG:function(e){var t="function"==typeof this.source?this.source():this.source,i=t.width/e.width,r=t.height/e.height,n=this.offsetX/e.width,s=this.offsetY/e.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),t.src?o=t.src:t.toDataURL&&(o=t.toDataURL()),'\n\n\n'},setOptions:function(e){for(var t in e)this[t]=e[t]},toLive:function(e){var t=this.source;if(!t)return"";if(void 0!==t.src){if(!t.complete)return"";if(0===t.naturalWidth||0===t.naturalHeight)return""}return e.createPattern(t,this.repeat)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.toFixed;t.Shadow?t.warn("fabric.Shadow is already defined."):(t.Shadow=t.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(e){for(var i in"string"==typeof e&&(e=this._parseShadow(e)),e)this[i]=e[i];this.id=t.Object.__uid++},_parseShadow:function(e){var i=e.trim(),r=t.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(t.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(e){var r=40,n=40,s=t.Object.NUM_FRACTION_DIGITS,o=t.util.rotateVector({x:this.offsetX,y:this.offsetY},t.util.degreesToRadians(-e.angle)),a=new t.Color(this.color);return e.width&&e.height&&(r=100*i((Math.abs(o.x)+this.blur)/e.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/e.height,s)+20),e.flipX&&(o.x*=-1),e.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var e={},i=t.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(t){this[t]!==i[t]&&(e[t]=this[t])}),this),e}}),t.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(t),function(){if(x.StaticCanvas)x.warn("fabric.StaticCanvas is already defined.");else{var e=x.util.object.extend,t=x.util.getElementOffset,i=x.util.removeFromArray,r=x.util.toFixed,n=x.util.transformPoint,s=x.util.invertTransform,o=x.util.getNodeCanvas,a=x.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");x.StaticCanvas=x.util.createClass(x.CommonMethods,{initialize:function(e,t){t||(t={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(e,t)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:x.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(e,t){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(e),this._initOptions(t),this.interactive||this._initRetinaScaling(),t.overlayImage&&this.setOverlayImage(t.overlayImage,i),t.backgroundImage&&this.setBackgroundImage(t.backgroundImage,i),t.backgroundColor&&this.setBackgroundColor(t.backgroundColor,i),t.overlayColor&&this.setOverlayColor(t.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return x.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,x.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var e=x.devicePixelRatio;this.__initRetinaScaling(e,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(e,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(e,t,i){t.setAttribute("width",this.width*e),t.setAttribute("height",this.height*e),i.scale(e,e)},calcOffset:function(){return this._offset=t(this.lowerCanvasEl),this},setOverlayImage:function(e,t,i){return this.__setBgOverlayImage("overlayImage",e,t,i)},setBackgroundImage:function(e,t,i){return this.__setBgOverlayImage("backgroundImage",e,t,i)},setOverlayColor:function(e,t){return this.__setBgOverlayColor("overlayColor",e,t)},setBackgroundColor:function(e,t){return this.__setBgOverlayColor("backgroundColor",e,t)},__setBgOverlayImage:function(e,t,i,r){return"string"==typeof t?x.util.loadImage(t,(function(t,n){if(t){var s=new x.Image(t,r);this[e]=s,s.canvas=this}i&&i(t,n)}),this,r&&r.crossOrigin):(r&&t.setOptions(r),this[e]=t,t&&(t.canvas=this),i&&i(t,!1)),this},__setBgOverlayColor:function(e,t,i){return this[e]=t,this._initGradient(t,e),this._initPattern(t,e,i),this},_createCanvasElement:function(){var e=a();if(!e)throw h;if(e.style||(e.style={}),void 0===e.getContext)throw h;return e},_initOptions:function(e){var t=this.lowerCanvasEl;this._setOptions(e),this.width=this.width||parseInt(t.width,10)||0,this.height=this.height||parseInt(t.height,10)||0,this.lowerCanvasEl.style&&(t.width=this.width,t.height=this.height,t.style.width=this.width+"px",t.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(e){e&&e.getContext?this.lowerCanvasEl=e:this.lowerCanvasEl=x.util.getById(e)||this._createCanvasElement(),x.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(e,t){return this.setDimensions({width:e},t)},setHeight:function(e,t){return this.setDimensions({height:e},t)},setDimensions:function(e,t){var i;for(var r in t=t||{},e)i=e[r],t.cssOnly||(this._setBackstoreDimension(r,e[r]),i+="px",this.hasLostContext=!0),t.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),t.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(e,t){return this.lowerCanvasEl[e]=t,this.upperCanvasEl&&(this.upperCanvasEl[e]=t),this.cacheCanvasEl&&(this.cacheCanvasEl[e]=t),this[e]=t,this},_setCssDimension:function(e,t){return this.lowerCanvasEl.style[e]=t,this.upperCanvasEl&&(this.upperCanvasEl.style[e]=t),this.wrapperEl&&(this.wrapperEl.style[e]=t),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(e){var t,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=e,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",t),this._setSVGObjects(i,t),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",t),i.push(""),i.join("")},_setSVGPreamble:function(e,t){t.suppressPreamble||e.push('\n','\n')},_setSVGHeader:function(e,t){var i,n=t.width||this.width,s=t.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=x.Object.NUM_FRACTION_DIGITS;t.viewBox?o='viewBox="'+t.viewBox.x+" "+t.viewBox.y+" "+t.viewBox.width+" "+t.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),e.push("\n',"Created with Fabric.js ",x.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(t),"\n")},createSVGClipPathMarkup:function(e){var t=this.clipPath;return t?(t.clipPathId="CLIPPATH_"+x.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(e.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var e=this;return["background","overlay"].map((function(t){var i=e[t+"Color"];if(i&&i.toLive){var r=e[t+"Vpt"],n=e.viewportTransform,s={width:e.width/(r?n[0]:1),height:e.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?x.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var e,t,i,r,n,s,o,a,h="",l={},c=x.fontPaths,u=[];for(this._objects.forEach((function e(t){u.push(t),t._objects&&t._objects.forEach(e)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(e,t){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else e.push('\n")},sendToBack:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(t=(n=s._objects).length;t--;)r=n[t],i(this._objects,r),this._objects.unshift(r);else i(this._objects,e),this._objects.unshift(e);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(n=s._objects,t=0;t0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(e))&&(o=this._findNewLowerIndex(e,s,t),i(this._objects,e),this._objects.splice(o,0,e));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(e,t,i){var r,n;if(i){for(r=t,n=t-1;n>=0;--n)if(e.intersectsWithObject(this._objects[n])||e.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(e)){r=n;break}}else r=t-1;return r},bringForward:function(e,t){if(!e)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(e===h&&"activeSelection"===e.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),e(x.StaticCanvas.prototype,x.Observable),e(x.StaticCanvas.prototype,x.Collection),e(x.StaticCanvas.prototype,x.DataURLExporter),e(x.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(e){var t=a();if(!t||!t.getContext)return null;var i=t.getContext("2d");return i&&"setLineDash"===e?void 0!==i.setLineDash:null}}),x.StaticCanvas.prototype.toJSON=x.StaticCanvas.prototype.toObject,x.isLikelyNode&&(x.StaticCanvas.prototype.createPNGStream=function(){var e=o(this.lowerCanvasEl);return e&&e.createPNGStream()},x.StaticCanvas.prototype.createJPEGStream=function(e){var t=o(this.lowerCanvasEl);return t&&t.createJPEGStream(e)})}}(),x.BaseBrush=x.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(e){e.strokeStyle=this.color,e.lineWidth=this.width,e.lineCap=this.strokeLineCap,e.miterLimit=this.strokeMiterLimit,e.lineJoin=this.strokeLineJoin,e.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(e){var t=this.canvas.viewportTransform;e.save(),e.transform(t[0],t[1],t[2],t[3],t[4],t[5])},_setShadow:function(){if(this.shadow){var e=this.canvas,t=this.shadow,i=e.contextTop,r=e.getZoom();e&&e._isRetinaScaling()&&(r*=x.devicePixelRatio),i.shadowColor=t.color,i.shadowBlur=t.blur*r,i.shadowOffsetX=t.offsetX*r,i.shadowOffsetY=t.offsetY*r}},needsFullRender:function(){return new x.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var e=this.canvas.contextTop;e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0},_isOutSideCanvas:function(e){return e.x<0||e.x>this.canvas.getWidth()||e.y<0||e.y>this.canvas.getHeight()}}),x.PencilBrush=x.util.createClass(x.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(e){this.canvas=e,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(e,t,i){var r=t.midPointFrom(i);return e.quadraticCurveTo(t.x,t.y,r.x,r.y),r},onMouseDown:function(e,t){this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],this._prepareForDrawing(e),this._captureDrawingPath(e),this._render())},onMouseMove:function(e,t){if(this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(e))&&this._captureDrawingPath(e)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(e){return!this.canvas._isMainEvent(e.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(e){var t=new x.Point(e.x,e.y);this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)},_addPoint:function(e){return!(this._points.length>1&&e.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(e),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(e){var t=new x.Point(e.x,e.y);return this._addPoint(t)},_render:function(e){var t,i,r=this._points[0],n=this._points[1];if(e=e||this.canvas.contextTop,this._saveAndTransform(e),e.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new x.Point(r.x,r.y),n=new x.Point(n.x,n.y),r.x-=s,n.x+=s}for(e.moveTo(r.x,r.y),t=1,i=this._points.length;t=n&&(o=e[i],a.push(o));return a.push(e[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var e=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(e))this.canvas.requestRenderAll();else{var t=this.createPath(e);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:t}),this.canvas.add(t),this.canvas.requestRenderAll(),t.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:t})}}}),x.CircleBrush=x.util.createClass(x.BaseBrush,{width:10,initialize:function(e){this.canvas=e,this.points=[]},drawDot:function(e){var t=this.addPoint(e),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,t),i.restore()},dot:function(e,t){e.fillStyle=t.fill,e.beginPath(),e.arc(t.x,t.y,t.radius,0,2*Math.PI,!1),e.closePath(),e.fill()},onMouseDown:function(e){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(e)},_render:function(){var e,t,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),e=0,t=r.length;e0&&!this.preserveObjectStacking){t=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),t.push.apply(t,i)}else t=this._objects;return t},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var e=this.contextContainer;return this.renderCanvas(e,this._chooseObjectsToRender()),this},renderTopLayer:function(e){e.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(e),this.contextTopDirty=!0),e.restore()},renderTop:function(){var e=this.contextTop;return this.clearContext(e),this.renderTopLayer(e),this.fire("after:render"),this},_normalizePointer:function(e,t){var i=e.calcTransformMatrix(),r=x.util.invertTransform(i),n=this.restorePointerVpt(t);return x.util.transformPoint(n,r)},isTargetTransparent:function(e,t,i){if(e.shouldCache()&&e._cacheCanvas&&e!==this._activeObject){var r=this._normalizePointer(e,{x:t,y:i}),n=Math.max(e.cacheTranslationX+r.x*e.zoomX,0),s=Math.max(e.cacheTranslationY+r.y*e.zoomY,0);return x.util.isTransparent(e._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=e.selectionBackgroundColor,h=this.viewportTransform;return e.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),e.render(o),o.restore(),e.selectionBackgroundColor=a,x.util.isTransparent(o,t,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(e){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(t){return!0===e[t]})):e[this.selectionKey]},_shouldClearSelection:function(e,t){var i=this.getActiveObjects(),r=this._activeObject;return!t||t&&r&&i.length>1&&-1===i.indexOf(t)&&r!==t&&!this._isSelectionKeyPressed(e)||t&&!t.evented||t&&!t.selectable&&r&&r!==t},_shouldCenterTransform:function(e,t,i){var r;if(e)return"scale"===t||"scaleX"===t||"scaleY"===t||"resizing"===t?r=this.centeredScaling||e.centeredScaling:"rotate"===t&&(r=this.centeredRotation||e.centeredRotation),r?!i:i},_getOriginFromCorner:function(e,t){var i={x:e.originX,y:e.originY};return"ml"===t||"tl"===t||"bl"===t?i.x="right":"mr"!==t&&"tr"!==t&&"br"!==t||(i.x="left"),"tl"===t||"mt"===t||"tr"===t?i.y="bottom":"bl"!==t&&"mb"!==t&&"br"!==t||(i.y="top"),i},_getActionFromCorner:function(e,t,i,r){if(!t||!e)return"drag";var n=r.controls[t];return n.getActionName(i,n,r)},_setupCurrentTransform:function(e,i,r){if(i){var n=this.getPointer(e),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(e,i,o):x.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,e,i),l=this._getOriginFromCorner(i,s),c=e[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:t(i.angle),width:i.width*i.scaleX,shiftKey:e.shiftKey,altKey:c,original:x.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(e)}},setCursor:function(e){this.upperCanvasEl.style.cursor=e},_drawSelection:function(e){var t=this._groupSelector,i=new x.Point(t.ex,t.ey),r=x.util.transformPoint(i,this.viewportTransform),n=new x.Point(t.ex+t.left,t.ey+t.top),s=x.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,x.Object.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(o,a,h-o,l-a))},findTarget:function(e,t){if(!this.skipTargetFind){var r,n,s=this.getPointer(e,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(e),l=a.length>1&&!t||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!t&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return e[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(e,t,i){if(t&&t.visible&&t.evented&&t.containsPoint(e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;if(!this.isTargetTransparent(t,i.x,i.y))return!0}},_searchPossibleTargets:function(e,t){for(var i,r,n=e.length;n--;){var s=e[n],o=s.group?this._normalizePointer(s.group,t):t;if(this._checkTarget(o,s,t)){(i=e[n]).subTargetCheck&&i instanceof x.Group&&(r=this._searchPossibleTargets(i._objects,t))&&this.targets.push(r);break}}return i},restorePointerVpt:function(e){return x.util.transformPoint(e,x.util.invertTransform(this.viewportTransform))},getPointer:function(t,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=e(t),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var e=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),t=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),x.util.addClass(i,"upper-canvas "+e),this.wrapperEl.appendChild(i),this._copyCanvasStyle(t,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=x.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),x.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),x.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(e){var t=this.width||e.width,i=this.height||e.height;x.util.setStyle(e,{position:"absolute",width:t+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),e.width=t,e.height=i,x.util.makeElementUnselectable(e)},_copyCanvasStyle:function(e,t){t.style.cssText=e.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var e=this._activeObject;return e?"activeSelection"===e.type&&e._objects?e._objects.slice(0):[e]:[]},_onObjectRemoved:function(e){e===this._activeObject&&(this.fire("before:selection:cleared",{target:e}),this._discardActiveObject(),this.fire("selection:cleared",{target:e}),e.fire("deselected")),e===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",e)},_fireSelectionEvents:function(e,t){var i=!1,r=this.getActiveObjects(),n=[],s=[];e.forEach((function(e){-1===r.indexOf(e)&&(i=!0,e.fire("deselected",{e:t,target:e}),s.push(e))})),r.forEach((function(r){-1===e.indexOf(r)&&(i=!0,r.fire("selected",{e:t,target:r}),n.push(r))})),e.length>0&&r.length>0?i&&this.fire("selection:updated",{e:t,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:t,selected:n}):e.length>0&&this.fire("selection:cleared",{e:t,deselected:s})},setActiveObject:function(e,t){var i=this.getActiveObjects();return this._setActiveObject(e,t),this._fireSelectionEvents(i,t),this},_setActiveObject:function(e,t){return this._activeObject!==e&&!!this._discardActiveObject(t,e)&&!e.onSelect({e:t})&&(this._activeObject=e,!0)},_discardActiveObject:function(e,t){var i=this._activeObject;if(i){if(i.onDeselect({e,object:t}))return!1;this._activeObject=null}return!0},discardActiveObject:function(e){var t=this.getActiveObjects(),i=this.getActiveObject();return t.length&&this.fire("before:selection:cleared",{target:i,e}),this._discardActiveObject(e),this._fireSelectionEvents(t,e),this},dispose:function(){var e=this.wrapperEl;return this.removeListeners(),e.removeChild(this.upperCanvasEl),e.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(e){x.util.cleanUpJsdomNode(this[e]),this[e]=void 0}.bind(this)),e.parentNode&&e.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,x.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(e){var t=this._activeObject;t&&t._renderControls(e)},_toObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(e),n=this.callSuper("_toObject",e,t,i);return this._unwindGroupTransformOnObject(e,r),n},_realizeGroupTransformOnObject:function(e){if(e.group&&"activeSelection"===e.group.type&&this._activeObject===e.group){var t={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){t[i]=e[i]})),x.util.addTransformToObject(e,this._activeObject.calcOwnMatrix()),t}return null},_unwindGroupTransformOnObject:function(e,t){t&&e.set(t)},_setSVGObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(t);this.callSuper("_setSVGObject",e,t,i),this._unwindGroupTransformOnObject(t,r)},setViewportTransform:function(e){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),x.StaticCanvas.prototype.setViewportTransform.call(this,e)}}),x.StaticCanvas)"prototype"!==r&&(x.Canvas[r]=x.StaticCanvas[r])}(),function(){var e=x.util.addListener,t=x.util.removeListener,i={passive:!1};function r(e,t){return e.button&&e.button===t-1}x.util.object.extend(x.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(e,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(e,t){var r=this.upperCanvasEl,n=this._getEventPrefix();e(x.window,"resize",this._onResize),e(r,n+"down",this._onMouseDown),e(r,n+"move",this._onMouseMove,i),e(r,n+"out",this._onMouseOut),e(r,n+"enter",this._onMouseEnter),e(r,"wheel",this._onMouseWheel),e(r,"contextmenu",this._onContextMenu),e(r,"dblclick",this._onDoubleClick),e(r,"dragover",this._onDragOver),e(r,"dragenter",this._onDragEnter),e(r,"dragleave",this._onDragLeave),e(r,"drop",this._onDrop),this.enablePointerEvents||e(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&t in eventjs&&(eventjs[t](r,"gesture",this._onGesture),eventjs[t](r,"drag",this._onDrag),eventjs[t](r,"orientation",this._onOrientationChange),eventjs[t](r,"shake",this._onShake),eventjs[t](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(t,"remove");var e=this._getEventPrefix();t(x.document,e+"up",this._onMouseUp),t(x.document,"touchend",this._onTouchEnd,i),t(x.document,e+"move",this._onMouseMove,i),t(x.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(e,t){this.__onTransformGesture&&this.__onTransformGesture(e,t)},_onDrag:function(e,t){this.__onDrag&&this.__onDrag(e,t)},_onMouseWheel:function(e){this.__onMouseWheel(e)},_onMouseOut:function(e){var t=this._hoveredTarget;this.fire("mouse:out",{target:t,e}),this._hoveredTarget=null,t&&t.fire("mouseout",{e});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:t,e}),r&&t.fire("mouseout",{e})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(e){e.isEditing&&e.hiddenTextarea.focus()}))},_onMouseEnter:function(e){this._currentTransform||this.findTarget(e)||(this.fire("mouse:over",{target:null,e}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(e,t){this.__onOrientationChange&&this.__onOrientationChange(e,t)},_onShake:function(e,t){this.__onShake&&this.__onShake(e,t)},_onLongPress:function(e,t){this.__onLongPress&&this.__onLongPress(e,t)},_onDragOver:function(e){e.preventDefault();var t=this._simpleEventHandler("dragover",e);this._fireEnterLeaveEvents(t,e)},_onDrop:function(e){return this._simpleEventHandler("drop:before",e),this._simpleEventHandler("drop",e)},_onContextMenu:function(e){return this.stopContextMenu&&(e.stopPropagation(),e.preventDefault()),!1},_onDoubleClick:function(e){this._cacheTransformEventData(e),this._handleEvent(e,"dblclick"),this._resetTransformEventData(e)},getPointerId:function(e){var t=e.changedTouches;return t?t[0]&&t[0].identifier:this.enablePointerEvents?e.pointerId:-1},_isMainEvent:function(e){return!0===e.isPrimary||!1!==e.isPrimary&&("touchend"===e.type&&0===e.touches.length||!e.changedTouches||e.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(x.document,"touchend",this._onTouchEnd,i),e(x.document,"touchmove",this._onMouseMove,i),t(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(n,s+"move",this._onMouseMove,i),e(x.document,s+"up",this._onMouseUp),e(x.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();t(x.document,"touchend",this._onTouchEnd,i),t(x.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){e(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(t(x.document,s+"up",this._onMouseUp),t(x.document,s+"move",this._onMouseMove,i),e(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(e){!this.allowTouchScrolling&&e.preventDefault&&e.preventDefault(),this.__onMouseMove(e)},_onResize:function(){this.calcOffset()},_shouldRender:function(e){var t=this._activeObject;return!!(!!t!=!!e||t&&e&&t!==e)||(t&&t.isEditing,!1)},__onMouseUp:function(e){var t,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(e),t=this._target,this._handleEvent(e,"up:before"),r(e,3))this.fireRightClick&&this._handleEvent(e,"up",3,o);else{if(r(e,2))return this.fireMiddleClick&&this._handleEvent(e,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(e);else if(this._isMainEvent(e)){if(i&&(this._finalizeCurrentTransform(e),s=i.actionPerformed),!o){var a=t===this._activeObject;this._maybeGroupObjects(e),s||(s=this._shouldRender(t)||!a&&t===this._activeObject)}var h,l;if(t){if(h=t._findTargetCorner(this.getPointer(e,!0),x.util.isTouchEvent(e)),t.selectable&&t!==this._activeObject&&"up"===t.activeOn)this.setActiveObject(t,e),s=!0;else{var c=t.controls[h],u=c&&c.getMouseUpHandler(e,t,c);u&&u(e,i,(l=this.getPointer(e)).x,l.y)}t.isMoving=!1}if(i&&(i.target!==t||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(e,t,c);l=l||this.getPointer(e),f&&f(e,i,l.x,l.y)}this._setCursorFromEvent(e,t),this._handleEvent(e,"up",1,o),this._groupSelector=null,this._currentTransform=null,t&&(t.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(e,t){var i=this.findTarget(t),r=this.targets,n={e:t,target:i,subTargets:r};if(this.fire(e,n),i&&i.fire(e,n),!r)return i;for(var s=0;s1&&(t=new x.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(t,e))},_collectObjects:function(e){for(var t,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new x.Point(v(r,s),v(n,o)),h=new x.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((t=this._objects[u])&&t.selectable&&t.visible&&(l&&t.intersectsWithRect(a,h,!0)||t.isContainedWithinRect(a,h,!0)||l&&t.containsPoint(a,null,!0)||l&&t.containsPoint(h,null,!0))&&(i.push(t),c)););return i.length>1&&(i=i.filter((function(t){return!t.onSelect({e})}))),i},_maybeGroupObjects:function(e){this.selection&&this._groupSelector&&this._groupSelectedObjects(e),this.setCursor(this.defaultCursor),this._groupSelector=null}}),x.util.object.extend(x.StaticCanvas.prototype,{toDataURL:function(e){e||(e={});var t=e.format||"png",i=e.quality||1,r=(e.multiplier||1)*(e.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,e);return x.util.toDataURL(n,t,i)},toCanvasElement:function(e,t){e=e||1;var i=((t=t||{}).width||this.width)*e,r=(t.height||this.height)*e,n=this.getZoom(),s=this.width,o=this.height,a=n*e,h=this.viewportTransform,l=(h[4]-(t.left||0))*e,c=(h[5]-(t.top||0))*e,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=x.util.createCanvasElement(),_=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=_,g}}),x.util.object.extend(x.StaticCanvas.prototype,{loadFromJSON:function(e,t,i){if(e){var r="string"==typeof e?JSON.parse(e):x.util.object.clone(e),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(e){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,e,o,t)})):n.__setupCanvas.call(n,r,e,o,t)}))}),i),this}},__setupCanvas:function(e,t,i,r){var n=this;t.forEach((function(e,t){n.insertAt(e,t)})),this.renderOnAddRemove=i,delete e.objects,delete e.backgroundImage,delete e.overlayImage,delete e.background,delete e.overlay,this._setOptions(e),this.renderAll(),r&&r()},_setBgOverlay:function(e,t){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(e.backgroundImage||e.overlayImage||e.background||e.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&t&&t()};this.__setBgOverlay("backgroundImage",e.backgroundImage,i,r),this.__setBgOverlay("overlayImage",e.overlayImage,i,r),this.__setBgOverlay("backgroundColor",e.background,i,r),this.__setBgOverlay("overlayColor",e.overlay,i,r)}else t&&t()},__setBgOverlay:function(e,t,i,r){var n=this;if(!t)return i[e]=!0,void(r&&r());"backgroundImage"===e||"overlayImage"===e?x.util.enlivenObjects([t],(function(t){n[e]=t[0],i[e]=!0,r&&r()})):this["set"+x.util.string.capitalize(e,!0)](t,(function(){i[e]=!0,r&&r()}))},_enlivenObjects:function(e,t,i){e&&0!==e.length?x.util.enlivenObjects(e,(function(e){t&&t(e)}),null,i):t&&t([])},_toDataURL:function(e,t){this.clone((function(i){t(i.toDataURL(e))}))},_toDataURLWithMultiplier:function(e,t,i){this.clone((function(r){i(r.toDataURLWithMultiplier(e,t))}))},clone:function(e,t){var i=JSON.stringify(this.toJSON(t));this.cloneWithoutData((function(t){t.loadFromJSON(i,(function(){e&&e(t)}))}))},cloneWithoutData:function(e){var t=x.util.createCanvasElement();t.width=this.width,t.height=this.height;var i=new x.Canvas(t);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),e&&e(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):e&&e(i)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n=t.util.toFixed,s=t.util.string.capitalize,o=t.util.degreesToRadians,a=!t.isLikelyNode;t.Object||(t.Object=t.util.createClass(t.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(e){e&&this.setOptions(e)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=t.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(e){var i=t.perfLimitSizeTotal,r=e.width,n=e.height,s=t.maxCacheSideLimit,o=t.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(e.zoomX/=r/c,e.width=c,e.capped=!0),n>u&&(e.zoomY/=n/u,e.height=u,e.capped=!0),e},_getCacheCanvasDimensions:function(){var e=this.getTotalObjectScaling(),t=this._getTransformedDimensions(0,0),i=t.x*e.scaleX/this.scaleX,r=t.y*e.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:e.scaleX,zoomY:e.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var e=this.canvas;if(this.noScaleCache&&e&&e._currentTransform){var i=e._currentTransform.target,r=e._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=t.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,_=f||g,p=0,m=0,v=!1;if(f){var y=this._cacheCanvas.width,S=this._cacheCanvas.height,C=l>y||c>S;v=C||(l<.9*y||c<.9*S)&&y>h&&S>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,m=.1*c)}return this instanceof t.Text&&this.path&&(_=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!_&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+m)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(e){this._setOptions(e),this._initGradient(e.fill,"fill"),this._initGradient(e.stroke,"stroke"),this._initPattern(e.fill,"fill"),this._initPattern(e.stroke,"stroke")},transform:function(e){var t=this.group&&!this.group._transformDone||this.group&&this.canvas&&e===this.canvas.contextTop,i=this.calcTransformMatrix(!t);e.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(e){var i=t.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:t.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(e),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),t.util.populateWithProperties(this,r,e),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(e){return this.toObject(e)},_removeDefaultValues:function(e){var i=t.util.getKlass(e.type).prototype;return i.stateProperties.forEach((function(t){"left"!==t&&"top"!==t&&(e[t]===i[t]&&delete e[t],Array.isArray(e[t])&&Array.isArray(i[t])&&0===e[t].length&&0===i[t].length&&delete e[t])})),e},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var e=t.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(e.scaleX),scaleY:Math.abs(e.scaleY)}},getTotalObjectScaling:function(){var e=this.getObjectScaling(),t=e.scaleX,i=e.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();t*=r*n,i*=r*n}return{scaleX:t,scaleY:i}},getObjectOpacity:function(){var e=this.opacity;return this.group&&(e*=this.group.getObjectOpacity()),e},_set:function(e,i){var r="scaleX"===e||"scaleY"===e,n=this[e]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===e&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===e&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==e||!i||i instanceof t.Shadow?"dirty"===e&&this.group&&this.group.set("dirty",i):i=new t.Shadow(i),this[e]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(e)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(e)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:t.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(e){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(e.save(),this._setupCompositeOperation(e),this.drawSelectionBackground(e),this.transform(e),this._setOpacity(e),this._setShadow(e,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(e)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(e),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),e.restore())},renderCache:function(e){e=e||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,e.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(e,i){if(e.save(),i.inverted?e.globalCompositeOperation="destination-out":e.globalCompositeOperation="destination-in",i.absolutePositioned){var r=t.util.invertTransform(this.calcTransformMatrix());e.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(e),e.scale(1/i.zoomX,1/i.zoomY),e.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),e.restore()},drawObject:function(e,t){var i=this.fill,r=this.stroke;t?(this.fill="black",this.stroke="",this._setClippingProperties(e)):this._renderBackground(e),this._render(e),this._drawClipPath(e,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(e,t){t&&(t.canvas=this.canvas,t.shouldCache(),t._transformDone=!0,t.renderCache({forClipping:!0}),this.drawClipPathOnCache(e,t))},drawCacheOnCanvas:function(e){e.scale(1/this.zoomX,1/this.zoomY),e.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(e){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!e&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!e){var t=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-t/2,-i/2,t,i)}return!0}return!1},_renderBackground:function(e){if(this.backgroundColor){var t=this._getNonTransformedDimensions();e.fillStyle=this.backgroundColor,e.fillRect(-t.x/2,-t.y/2,t.x,t.y),this._removeShadow(e)}},_setOpacity:function(e){this.group&&!this.group._transformDone?e.globalAlpha=this.getObjectOpacity():e.globalAlpha*=this.opacity},_setStrokeStyles:function(e,t){var i=t.stroke;i&&(e.lineWidth=t.strokeWidth,e.lineCap=t.strokeLineCap,e.lineDashOffset=t.strokeDashOffset,e.lineJoin=t.strokeLineJoin,e.miterLimit=t.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(e,i):(e.strokeStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,i)):e.strokeStyle=t.stroke)},_setFillStyles:function(e,t){var i=t.fill;i&&(i.toLive?(e.fillStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,t.fill)):e.fillStyle=i)},_setClippingProperties:function(e){e.globalAlpha=1,e.strokeStyle="transparent",e.fillStyle="#000000"},_setLineDash:function(e,t){t&&0!==t.length&&(1&t.length&&t.push.apply(t,t),e.setLineDash(t))},_renderControls:function(e,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=t.util.multiplyTransformMatrices(a,h),r=t.util.qrDecompose(h),e.save(),e.translate(r.translateX,r.translateY),e.lineWidth=1*this.borderScaleFactor,this.group||(e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),e.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(e,r,i):n&&this.drawBorders(e,i),s&&this.drawControls(e,i),e.restore()},_setShadow:function(e){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=t.devicePixelRatio,o*=t.devicePixelRatio),e.shadowColor=r.color,e.shadowBlur=r.blur*t.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,e.shadowOffsetX=r.offsetX*s*i.scaleX,e.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(e){this.shadow&&(e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0)},_applyPatternGradientTransform:function(e,t){if(!t||!t.toLive)return{offsetX:0,offsetY:0};var i=t.gradientTransform||t.patternTransform,r=-this.width/2+t.offsetX||0,n=-this.height/2+t.offsetY||0;return"percentage"===t.gradientUnits?e.transform(this.width,0,0,this.height,r,n):e.transform(1,0,0,1,r,n),i&&e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(e){"stroke"===this.paintFirst?(this._renderStroke(e),this._renderFill(e)):(this._renderFill(e),this._renderStroke(e))},_render:function(){},_renderFill:function(e){this.fill&&(e.save(),this._setFillStyles(e,this),"evenodd"===this.fillRule?e.fill("evenodd"):e.fill(),e.restore())},_renderStroke:function(e){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this.strokeUniform&&this.group){var t=this.getObjectScaling();e.scale(1/t.scaleX,1/t.scaleY)}else this.strokeUniform&&e.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(e,this.strokeDashArray),this._setStrokeStyles(e,this),e.stroke(),e.restore()}},_applyPatternForTransformedGradient:function(e,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=t.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(e),r.fill(),e.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),e.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),e.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var e=t.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",e.scaleX),this.set("scaleY",e.scaleY),this.angle=e.angle,this.skewX=e.skewX,this.skewY=0}},_removeTransformMatrix:function(e){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=t.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,e&&(this.scaleX*=e.scaleX,this.scaleY*=e.scaleY,this.cropX=e.cropX,this.cropY=e.cropY,i.x+=e.offsetLeft,i.y+=e.offsetTop,this.width=e.width,this.height=e.height),this.setPositionByOrigin(i,"center","center")},clone:function(e,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,e):t.Object._fromObject("Object",r,e)},cloneAsImage:function(e,i){var r=this.toCanvasElement(i);return e&&e(new t.Image(r)),this},toCanvasElement:function(e){e||(e={});var i=t.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(e.multiplier||1)*(e.enableRetinaScaling?t.devicePixelRatio:1);delete this.group,e.withoutTransform&&i.resetObjectTransform(this),e.withoutShadow&&(this.shadow=null);var h,l,c,u,d=t.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),_.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+_.x,u=f.height+_.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new t.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===e.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new t.Point(p.width/2,p.height/2),"center","center");var m=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,e);return this.shadow=s,this.set("canvas",m),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(e){return e||(e={}),t.util.toDataURL(this.toCanvasElement(e),e.format||"png",e.quality||1)},isType:function(e){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===e},complexity:function(){return 1},toJSON:function(e){return this.toObject(e)},rotate:function(e){var t=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return t&&this._setOriginToCenter(),this.set("angle",e),t&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(e,i){i=i||this.canvas.getPointer(e);var r=new t.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=t.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(e){this.globalCompositeOperation&&(e.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){t.runningAnimations&&t.runningAnimations.cancelByTarget(this)}}),t.util.createAccessors&&t.util.createAccessors(t.Object),i(t.Object.prototype,t.Observable),t.Object.NUM_FRACTION_DIGITS=2,t.Object.ENLIVEN_PROPS=["clipPath"],t.Object._fromObject=function(e,i,n,s){var o=t[e];i=r(i,!0),t.util.enlivenPatterns([i.fill,i.stroke],(function(e){void 0!==e[0]&&(i.fill=e[0]),void 0!==e[1]&&(i.stroke=e[1]),t.util.enlivenObjectEnlivables(i,i,(function(){var e=s?new o(i[s],i):new o(i);n&&n(e)}))}))},t.Object.__uid=0)}(t),S=x.util.degreesToRadians,C={left:-.5,center:0,right:.5},w={top:-.5,center:0,bottom:.5},x.util.object.extend(x.Object.prototype,{translateToGivenOrigin:function(e,t,i,r,n){var s,o,a,h=e.x,l=e.y;return"string"==typeof t?t=C[t]:t-=.5,"string"==typeof r?r=C[r]:r-=.5,"string"==typeof i?i=w[i]:i-=.5,"string"==typeof n?n=w[n]:n-=.5,o=n-i,((s=r-t)||o)&&(a=this._getTransformedDimensions(),h=e.x+s*a.x,l=e.y+o*a.y),new x.Point(h,l)},translateToCenterPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,t,i,"center","center");return this.angle?x.util.rotatePoint(r,e,S(this.angle)):r},translateToOriginPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,"center","center",t,i);return this.angle?x.util.rotatePoint(r,e,S(this.angle)):r},getCenterPoint:function(){var e=new x.Point(this.left,this.top);return this.translateToCenterPoint(e,this.originX,this.originY)},getPointByOrigin:function(e,t){var i=this.getCenterPoint();return this.translateToOriginPoint(i,e,t)},toLocalPoint:function(e,t,i){var r,n,s=this.getCenterPoint();return r=void 0!==t&&void 0!==i?this.translateToGivenOrigin(s,"center","center",t,i):new x.Point(this.left,this.top),n=new x.Point(e.x,e.y),this.angle&&(n=x.util.rotatePoint(n,s,-S(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(e,t,i){var r=this.translateToCenterPoint(e,t,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(e){var t,i,r=S(this.angle),n=this.getScaledWidth(),s=x.util.cos(r)*n,o=x.util.sin(r)*n;t="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof e?C[e]:e-.5,this.left+=s*(i-t),this.top+=o*(i-t),this.setCoords(),this.originX=e},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var e=this.getCenterPoint();this.originX="center",this.originY="center",this.left=e.x,this.top=e.y},_resetOrigin:function(){var e=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=e.x,this.top=e.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var e=x.util,t=e.degreesToRadians,i=e.multiplyTransformMatrices,r=e.transformPoint;e.object.extend(x.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(e,t){return t?e?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),e?this.aCoords:this.lineCoords)},getCoords:function(e,t){return i=this._getCoords(e,t),[new x.Point(i.tl.x,i.tl.y),new x.Point(i.tr.x,i.tr.y),new x.Point(i.br.x,i.br.y),new x.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(e,t,i,r){var n=this.getCoords(i,r);return"Intersection"===x.Intersection.intersectPolygonRectangle(n,e,t).status},intersectsWithObject:function(e,t,i){return"Intersection"===x.Intersection.intersectPolygonPolygon(this.getCoords(t,i),e.getCoords(t,i)).status||e.isContainedWithinObject(this,t,i)||this.isContainedWithinObject(e,t,i)},isContainedWithinObject:function(e,t,i){for(var r=this.getCoords(t,i),n=t?e.aCoords:e.lineCoords,s=0,o=e._getImageLines(n);s<4;s++)if(!e.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(e,t,i,r){var n=this.getBoundingRect(i,r);return n.left>=e.x&&n.left+n.width<=t.x&&n.top>=e.y&&n.top+n.height<=t.y},containsPoint:function(e,t,i,r){var n=this._getCoords(i,r),s=(t=t||this._getImageLines(n),this._findCrossPoints(e,t));return 0!==s&&s%2==1},isOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,e).some((function(e){return e.x<=i.x&&e.x>=t.x&&e.y<=i.y&&e.y>=t.y}))||!!this.intersectsWithRect(t,i,!0,e)||this._containsCenterOfCanvas(t,i,e)},_containsCenterOfCanvas:function(e,t,i){var r={x:(e.x+t.x)/2,y:(e.y+t.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(t,i,!0,e)||this.getCoords(!0,e).every((function(e){return(e.x>=i.x||e.x<=t.x)&&(e.y>=i.y||e.y<=t.y)}))&&this._containsCenterOfCanvas(t,i,e)},_getImageLines:function(e){return{topline:{o:e.tl,d:e.tr},rightline:{o:e.tr,d:e.br},bottomline:{o:e.br,d:e.bl},leftline:{o:e.bl,d:e.tl}}},_findCrossPoints:function(e,t){var i,r,n,s=0;for(var o in t)if(!((n=t[o]).o.y=e.y&&n.d.y>=e.y||(n.o.x===n.d.x&&n.o.x>=e.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(e.y-0*e.x-(n.o.y-i*n.o.x))/(0-i)),r>=e.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(t,i){var r=this.getCoords(t,i);return e.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(e){return Math.abs(e)\n')}},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(e),{reviver:e})},toClipPathSVG:function(e){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(e),{reviver:e})},_createBaseClipPathSVGMarkup:function(e,t){var i=(t=t||{}).reviver,r=t.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=e.indexOf("COMMON_PARTS");return e[s]=n,i?i(e.join("")):e.join("")},_createBaseSVGMarkup:function(e,t){var i,r,n=(t=t||{}).noStyle,s=t.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=t.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=e.indexOf("COMMON_PARTS"),p=t.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+x.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),e[_]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(e.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var e=x.util.object.extend,t="stateProperties";function i(t,i,r){var n={};r.forEach((function(e){n[e]=t[e]})),e(t[i],n,!0)}function r(e,t,i){if(e===t)return!0;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(var n=0,s=e.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(t?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(e){for(var t in this.controls)e(this.controls[t],t,this)},_setCornerCoords:function(){var e=this.oCoords;for(var t in e){var i=this.controls[t];e[t].corner=i.calcCornerCoords(this.angle,this.cornerSize,e[t].x,e[t].y,!1),e[t].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,e[t].x,e[t].y,!0)}},drawSelectionBackground:function(t){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;t.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return t.translate(i.x,i.y),t.scale(1/n[0],1/n[3]),t.rotate(e(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-r.x/2,-r.y/2,r.x,r.y),t.restore(),this},drawBorders:function(e,t){t=t||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==t.hasControls?t.hasControls:this.hasControls,a=!1;return e.save(),e.strokeStyle=t.borderColor||this.borderColor,this._setLineDash(e,t.borderDashArray||this.borderDashArray),e.strokeRect(-n/2,-s/2,n,s),o&&(e.beginPath(),this.forEachControl((function(t,i,r){t.withConnection&&t.getVisibility(r,i)&&(a=!0,e.moveTo(t.x*n,t.y*s),e.lineTo(t.x*n+t.offsetX,t.y*s+t.offsetY))})),a&&e.stroke()),e.restore(),this},drawBordersInGroup:function(e,t,i){i=i||{};var r=x.util.sizeAfterTransform(this.width,this.height,t),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():t.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():t.scaleY)+o;return e.save(),this._setLineDash(e,i.borderDashArray||this.borderDashArray),e.strokeStyle=i.borderColor||this.borderColor,e.strokeRect(-a/2,-h/2,a,h),e.restore(),this},drawControls:function(e,t){t=t||{},e.save();var i,r,n=this.canvas.getRetinaScaling();return e.setTransform(n,0,0,n,0,0),e.strokeStyle=e.fillStyle=t.cornerColor||this.cornerColor,this.transparentCorners||(e.strokeStyle=t.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(e,t.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=x.util.transformPoint(r,i)),n.render(e,r.x,r.y,t,o))})),e.restore(),this},isControlVisible:function(e){return this.controls[e]&&this.controls[e].getVisibility(this,e)},setControlVisible:function(e,t){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[e]=t,this},setControlsVisibility:function(e){for(var t in e||(e={}),e)this.setControlVisible(t,e[t]);return this},onDeselect:function(){},onSelect:function(){}})}(),x.util.object.extend(x.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(t){e.set("left",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxCenterObjectV:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(t){e.set("top",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxRemove:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(t){e.set("opacity",t),s.requestRenderAll(),n()},onComplete:function(){s.remove(e),r()}})}}),x.util.object.extend(x.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var e,t,i=[],r=[];for(e in arguments[0])i.push(e);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(e);"from"in i||(i.from=a),o||(t=~t.indexOf("=")?a+parseFloat(t.replace("=","")):parseFloat(t));var h={target:this,startValue:i.from,endValue:t,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(e,t,r){return i.abort.call(s,e,t,r)},onChange:function(t,o,a){n?s[n[0]][n[1]]=t:s.set(e,t),r||i.onChange&&i.onChange(t,o,a)},onComplete:function(e,t,n){r||(s.setCoords(),i.onComplete&&i.onComplete(e,t,n))}};return o?x.util.animateColor(h.startValue,h.endValue,h.duration,h):x.util.animate(h)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(e,t){var i=e.origin,r=e.axis1,n=e.axis2,s=e.dimension,o=t.nearest,a=t.center,h=t.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}t.Line?t.warn("fabric.Line is already defined"):(t.Line=t.util.createClass(t.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:t.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(e,t){e||(e=[0,0,0,0]),this.callSuper("initialize",t),this.set("x1",e[0]),this.set("y1",e[1]),this.set("x2",e[2]),this.set("y2",e[3]),this._setWidthHeight(t)},_setWidthHeight:function(e){e||(e={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in e?e.left:this._getLeftToOriginX(),this.top="top"in e?e.top:this._getTopToOriginY()},_set:function(e,t){return this.callSuper("_set",e,t),void 0!==n[e]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(e){e.beginPath();var t=this.calcLinePoints();e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineWidth=this.strokeWidth;var i=e.strokeStyle;e.strokeStyle=this.stroke||e.fillStyle,this.stroke&&this._renderStroke(e),e.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(e){return i(this.callSuper("toObject",e),this.calcLinePoints())},_getNonTransformedDimensions:function(){var e=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(e.y-=this.strokeWidth),0===this.height&&(e.x-=this.strokeWidth)),e},calcLinePoints:function(){var e=this.x1<=this.x2?-1:1,t=this.y1<=this.y2?-1:1,i=e*this.width*.5,r=t*this.height*.5;return{x1:i,x2:e*this.width*-.5,y1:r,y2:t*this.height*-.5}},_toSVG:function(){var e=this.calcLinePoints();return["\n']}}),t.Line.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),t.Line.fromElement=function(e,r,n){n=n||{};var s=t.parseAttributes(e,t.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new t.Line(o,i(s,n)))},t.Line.fromObject=function(e,i){var n=r(e,!0);n.points=[e.x1,e.y1,e.x2,e.y2],t.Object._fromObject("Line",n,(function(e){delete e.points,i&&i(e)}),"points")})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians;t.Circle?t.warn("fabric.Circle is already defined."):(t.Circle=t.util.createClass(t.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:t.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(e,t){return this.callSuper("_set",e,t),"radius"===e&&this.setRadius(t),this},toObject:function(e){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(e))},_toSVG:function(){var e,r=(this.endAngle-this.startAngle)%360;if(0===r)e=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;e=['180?"1":"0")+" 1"," "+t.util.cos(s)*o+" "+t.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return e},_render:function(e){e.beginPath(),e.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(e)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(e){return this.radius=e,this.set("width",2*e).set("height",2*e)}}),t.Circle.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),t.Circle.fromElement=function(e,i){var r,n=t.parseAttributes(e,t.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new t.Circle(n))},t.Circle.fromObject=function(e,i){t.Object._fromObject("Circle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={});t.Triangle?t.warn("fabric.Triangle is already defined"):(t.Triangle=t.util.createClass(t.Object,{type:"triangle",width:100,height:100,_render:function(e){var t=this.width/2,i=this.height/2;e.beginPath(),e.moveTo(-t,i),e.lineTo(0,-i),e.lineTo(t,i),e.closePath(),this._renderPaintInOrder(e)},_toSVG:function(){var e=this.width/2,t=this.height/2;return["']}}),t.Triangle.fromObject=function(e,i){return t.Object._fromObject("Triangle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=2*Math.PI;t.Ellipse?t.warn("fabric.Ellipse is already defined."):(t.Ellipse=t.util.createClass(t.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this.set("rx",e&&e.rx||0),this.set("ry",e&&e.ry||0)},_set:function(e,t){switch(this.callSuper("_set",e,t),e){case"rx":this.rx=t,this.set("width",2*t);break;case"ry":this.ry=t,this.set("height",2*t)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']},_render:function(e){e.beginPath(),e.save(),e.transform(1,0,0,this.ry/this.rx,0,0),e.arc(0,0,this.rx,0,i,!1),e.restore(),this._renderPaintInOrder(e)}}),t.Ellipse.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),t.Ellipse.fromElement=function(e,i){var r=t.parseAttributes(e,t.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new t.Ellipse(r))},t.Ellipse.fromObject=function(e,i){t.Object._fromObject("Ellipse",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend;t.Rect?t.warn("fabric.Rect is already defined"):(t.Rect=t.util.createClass(t.Object,{stateProperties:t.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(e){var t=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==t||0!==i,h=.4477152502;e.beginPath(),e.moveTo(s+t,o),e.lineTo(s+r-t,o),a&&e.bezierCurveTo(s+r-h*t,o,s+r,o+h*i,s+r,o+i),e.lineTo(s+r,o+n-i),a&&e.bezierCurveTo(s+r,o+n-h*i,s+r-h*t,o+n,s+r-t,o+n),e.lineTo(s+t,o+n),a&&e.bezierCurveTo(s+h*t,o+n,s,o+n-h*i,s,o+n-i),e.lineTo(s,o+i),a&&e.bezierCurveTo(s,o+h*i,s+h*t,o,s+t,o),e.closePath(),this._renderPaintInOrder(e)},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']}}),t.Rect.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),t.Rect.fromElement=function(e,r,n){if(!e)return r(null);n=n||{};var s=t.parseAttributes(e,t.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new t.Rect(i(n?t.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},t.Rect.fromObject=function(e,i){return t.Object._fromObject("Rect",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.array.min,n=t.util.array.max,s=t.util.toFixed,o=t.util.projectStrokeOnPoints;t.Polyline?t.warn("fabric.Polyline is already defined"):(t.Polyline=t.util.createClass(t.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:t.Object.prototype.cacheProperties.concat("points"),initialize:function(e,t){t=t||{},this.points=e||[],this.callSuper("initialize",t),this._setPositionDimensions(t)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(e){var t,i=this._calcDimensions(e),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,e.fromSVG||(t=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===e.left&&(this.left=e.fromSVG?i.left:t.x),void 0===e.top&&(this.top=e.fromSVG?i.top:t.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var e=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,t=r(e,"x")||0,i=r(e,"y")||0;return{left:t,top:i,width:(n(e,"x")||0)-t,height:(n(e,"y")||0)-i}},toObject:function(e){return i(this.callSuper("toObject",e),{points:this.points.concat()})},_toSVG:function(){for(var e=[],i=this.pathOffset.x,r=this.pathOffset.y,n=t.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(e){var t,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;e.beginPath(),e.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(e){return n(this.callSuper("toObject",e),{path:this.path.map((function(e){return e.slice()}))})},toDatalessObject:function(e){var t=this.toObject(["sourcePath"].concat(e));return t.sourcePath&&delete t.path,t},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var e=t.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,e)+", "+o(-this.pathOffset.y,e)+")"},toClipPathSVG:function(e){var t=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},toSVG:function(e){var t=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var e,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(e){var i=!!this.group;return this._restoreObjectsState(),t.util.resetObjectTransform(this),e&&(i&&t.util.removeTransformFromObject(e,this.group.calcTransformMatrix()),this._objects.push(e),e.group=this,e._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(e){return this._restoreObjectsState(),t.util.resetObjectTransform(this),this.remove(e),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(e){this.dirty=!0,e.group=this,e._set("canvas",this.canvas)},_onObjectRemoved:function(e){this.dirty=!0,delete e.group},_set:function(e,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(e,i);if("canvas"===e)for(;r--;)this._objects[r]._set(e,i);t.Object.prototype._set.call(this,e,i)},toObject:function(e){var i=this.includeDefaultValues,r=this._objects.filter((function(e){return!e.excludeFromExport})).map((function(t){var r=t.includeDefaultValues;t.includeDefaultValues=i;var n=t.toObject(e);return t.includeDefaultValues=r,n})),n=t.Object.prototype.toObject.call(this,e);return n.objects=r,n},toDatalessObject:function(e){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(t){var i=t.includeDefaultValues;t.includeDefaultValues=n;var r=t.toDatalessObject(e);return t.includeDefaultValues=i,r}))}var s=t.Object.prototype.toDatalessObject.call(this,e);return s.objects=i,s},render:function(e){this._transformDone=!0,this.callSuper("render",e),this._transformDone=!1},shouldCache:function(){var e=t.Object.prototype.shouldCache.call(this);if(e)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),t},getSvgStyles:function(){var e=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",t=this.visible?"":" visibility: hidden;";return[e,this.getSvgFilter(),t].join("")},toClipPathSVG:function(e){for(var t=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(e,t,i){e.save(),e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",e,t),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,e=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?t.concat(e,i):t.concat(i,e)},getSrc:function(e){var t=e?this._element:this._originalElement;return t?t.toDataURL?t.toDataURL():this.srcFromAttribute?t.getAttribute("src"):t.src:this.src||""},setSrc:function(e,t,i){return x.util.loadImage(e,(function(e,r){this.setElement(e,i),this._setWidthHeight(),t&&t(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var e=this.resizeFilter,t=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!e||r>t&&n>t)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);x.filterBackend||(x.filterBackend=x.initFilterBackend());var o=x.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=n,x.filterBackend.applyFilters([e],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(e){if(e=(e=e||this.filters||[]).filter((function(e){return e&&!e.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===e.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var t=this._originalElement,i=t.naturalWidth||t.width,r=t.naturalHeight||t.height;if(this._element===this._originalElement){var n=x.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return x.filterBackend||(x.filterBackend=x.initFilterBackend()),x.filterBackend.applyFilters(e,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(e){x.util.setImageSmoothing(e,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(e),this._renderPaintInOrder(e)},drawCacheOnCanvas:function(e){x.util.setImageSmoothing(e,this.imageSmoothing),x.Object.prototype.drawCacheOnCanvas.call(this,e)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(e){var t=this._element;if(t){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=t.naturalWidth||t.width,u=t.naturalHeight||t.height,d=h*i,f=l*r,g=o(n*i,c-d),_=o(s*r,u-f),p=-n/2,m=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);t&&e.drawImage(t,d,f,g,_,p,m,v,y)}},_needsResize:function(){var e=this.getTotalObjectScaling();return e.scaleX!==this._lastScaleX||e.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(e,t){this.setElement(x.util.getById(e),t),x.util.addClass(this.getElement(),x.Image.CSS_CANVAS)},_initConfig:function(e){e||(e={}),this.setOptions(e),this._setWidthHeight(e)},_initFilters:function(e,t){e&&e.length?x.util.enlivenObjects(e,(function(e){t&&t(e)}),"fabric.Image.filters"):t&&t()},_setWidthHeight:function(e){e||(e={});var t=this.getElement();this.width=e.width||t.naturalWidth||t.width||0,this.height=e.height||t.naturalHeight||t.height||0},parsePreserveAspectRatioAttribute:function(){var e,t=x.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!t||"none"===t.alignX&&"none"===t.alignY?(n=c/i,s=u/r):("meet"===t.meetOrSlice&&(e=(c-i*(n=s=x.util.findScaleToFit(this._element,d)))/2,"Min"===t.alignX&&(o=-e),"Max"===t.alignX&&(o=e),e=(u-r*s)/2,"Min"===t.alignY&&(a=-e),"Max"===t.alignY&&(a=e)),"slice"===t.meetOrSlice&&(e=i-c/(n=s=x.util.findScaleToCover(this._element,d)),"Mid"===t.alignX&&(h=e/2),"Max"===t.alignX&&(h=e),e=r-u/s,"Mid"===t.alignY&&(l=e/2),"Max"===t.alignY&&(l=e),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),x.Image.CSS_CANVAS="canvas-img",x.Image.prototype.getSvgSrc=x.Image.prototype.getSrc,x.Image.fromObject=function(e,t){var i=x.util.object.clone(e);x.util.loadImage(i.src,(function(e,r){r?t&&t(null,!0):x.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],x.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],x.util.enlivenObjectEnlivables(i,i,(function(){var r=new x.Image(e,i);t(r,!1)}))}))}))}),null,i.crossOrigin)},x.Image.fromURL=function(e,t,i){x.util.loadImage(e,(function(e,r){t&&t(new x.Image(e,i),r)}),null,i&&i.crossOrigin)},x.Image.ATTRIBUTE_NAMES=x.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),x.Image.fromElement=function(e,i,r){var n=x.parseAttributes(e,x.Image.ATTRIBUTE_NAMES);x.Image.fromURL(n["xlink:href"],i,t(r?x.util.object.clone(r):{},n))})}(t),x.util.object.extend(x.Object.prototype,{_getAngleValueForStraighten:function(){var e=this.angle%360;return e>0?90*Math.round((e-1)/90):90*Math.round(e/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(e){var t=function(){},i=(e=e||{}).onComplete||t,r=e.onChange||t,n=this;return x.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(e){n.rotate(e),r()},onComplete:function(){n.setCoords(),i()}})}}),x.util.object.extend(x.StaticCanvas.prototype,{straightenObject:function(e){return e.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(e){return e.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function e(e,t){var i="precision "+t+" float;\nvoid main(){}",r=e.createShader(e.FRAGMENT_SHADER);return e.shaderSource(r,i),e.compileShader(r),!!e.getShaderParameter(r,e.COMPILE_STATUS)}function t(e){e&&e.tileSize&&(this.tileSize=e.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}x.isWebglSupported=function(t){if(x.isLikelyNode)return!1;t=t||x.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){x.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=x.maxTextureSize>=t;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(e(r,s[o])){x.webGlPrecision=s[o];break}}return this.isSupported=n,n},x.WebglFilterBackend=t,t.prototype={tileSize:2048,resources:{},setupGLContext:function(e,t){this.dispose(),this.createWebGLCanvas(e,t),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(e,t)},chooseFastestCopyGLTo2DMethod:function(e,t){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(e){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=x.util.createCanvasElement(),a=new ArrayBuffer(e*t*4);if(x.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=I);var h,l,c={imageBuffer:a,destinationWidth:e,destinationHeight:t,targetCanvas:o};o.width=e,o.height=t,h=window.performance.now(),E.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),I.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=I):this.copyGLTo2D=E}},createWebGLCanvas:function(e,t){var i=x.util.createCanvasElement();i.width=e,i.height=t;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(e,t,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,t));var h={originalWidth:t.width||t.originalWidth,originalHeight:t.height||t.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&t),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&t),passes:e.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),e.forEach((function(e){e&&e.applyTo(h)})),function(e){var t=e.targetCanvas,i=t.width,r=t.height,n=e.destinationWidth,s=e.destinationHeight;i===n&&r===s||(t.width=n,t.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(e,t,i,r){var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),r?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,i,0,e.RGBA,e.UNSIGNED_BYTE,null),n},getCachedTexture:function(e,t){if(this.textureCache[e])return this.textureCache[e];var i=this.createTexture(this.gl,t.width,t.height,t);return this.textureCache[e]=i,i},evictCachesForKey:function(e){this.textureCache[e]&&(this.gl.deleteTexture(this.textureCache[e]),delete this.textureCache[e])},copyGLTo2D:E,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var e=this.gl,t={renderer:"",vendor:""};if(!e)return t;var i=e.getExtension("WEBGL_debug_renderer_info");if(i){var r=e.getParameter(i.UNMASKED_RENDERER_WEBGL),n=e.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(t.renderer=r.toLowerCase()),n&&(t.vendor=n.toLowerCase())}return this.gpuInfo=t,t}}}(),function(){var e=function(){};function t(){}x.Canvas2dFilterBackend=t,t.prototype={evictCachesForKey:e,dispose:e,clearWebGLCaches:e,resources:{},applyFilters:function(e,t,i,r,n){var s=n.getContext("2d");s.drawImage(t,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:t,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return e.forEach((function(e){e.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),x.Image=x.Image||{},x.Image.filters=x.Image.filters||{},x.Image.filters.BaseFilter=x.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(e){e&&this.setOptions(e)},setOptions:function(e){for(var t in e)this[t]=e[t]},createProgram:function(e,t,i){t=t||this.fragmentSource,i=i||this.vertexSource,"highp"!==x.webGlPrecision&&(t=t.replace(/precision highp float/g,"precision "+x.webGlPrecision+" float"));var r=e.createShader(e.VERTEX_SHADER);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+e.getShaderInfoLog(r));var n=e.createShader(e.FRAGMENT_SHADER);if(e.shaderSource(n,t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+e.getShaderInfoLog(n));var s=e.createProgram();if(e.attachShader(s,r),e.attachShader(s,n),e.linkProgram(s),!e.getProgramParameter(s,e.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+e.getProgramInfoLog(s));var o=this.getAttributeLocations(e,s),a=this.getUniformLocations(e,s)||{};return a.uStepW=e.getUniformLocation(s,"uStepW"),a.uStepH=e.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(e,t){return{aPosition:e.getAttribLocation(t,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(e,t,i){var r=t.aPosition,n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW)},_setupFrameBuffer:function(e){var t,i,r=e.context;e.passes>1?(t=e.destinationWidth,i=e.destinationHeight,e.sourceWidth===t&&e.sourceHeight===i||(r.deleteTexture(e.targetTexture),e.targetTexture=e.filterBackend.createTexture(r,t,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(e){e.passes--,e.pass++;var t=e.targetTexture;e.targetTexture=e.sourceTexture,e.sourceTexture=t},isNeutralState:function(){var e=this.mainParameter,t=x.Image.filters[this.type].prototype;if(e){if(Array.isArray(t[e])){for(var i=t[e].length;i--;)if(this[e][i]!==t[e][i])return!1;return!0}return t[e]===this[e]}return!1},applyTo:function(e){e.webgl?(this._setupFrameBuffer(e),this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)},retrieveShader:function(e){return e.programCache.hasOwnProperty(this.type)||(e.programCache[this.type]=this.createProgram(e.context)),e.programCache[this.type]},applyToWebGL:function(e){var t=e.context,i=this.retrieveShader(e);0===e.pass&&e.originalTexture?t.bindTexture(t.TEXTURE_2D,e.originalTexture):t.bindTexture(t.TEXTURE_2D,e.sourceTexture),t.useProgram(i.program),this.sendAttributeData(t,i.attributeLocations,e.aPosition),t.uniform1f(i.uniformLocations.uStepW,1/e.sourceWidth),t.uniform1f(i.uniformLocations.uStepH,1/e.sourceHeight),this.sendUniformData(t,i.uniformLocations),t.viewport(0,0,e.destinationWidth,e.destinationHeight),t.drawArrays(t.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(e,t,i){e.activeTexture(i),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE0)},unbindAdditionalTexture:function(e,t){e.activeTexture(t),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(e){this[this.mainParameter]=e},sendUniformData:function(){},createHelpLayer:function(e){if(!e.helpLayer){var t=document.createElement("canvas");t.width=e.sourceWidth,t.height=e.sourceHeight,e.helpLayer=t}},toObject:function(){var e={type:this.type},t=this.mainParameter;return t&&(e[t]=this[t]),e},toJSON:function(){return this.toObject()}}),x.Image.filters.BaseFilter.fromObject=function(e,t){var i=new x.Image.filters[e.type](e);return t&&t(i),i},function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(e){this.callSuper("initialize",e),this.matrix=this.matrix.slice(0)},applyTo2d:function(e){var t,i,r,n,s,o=e.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=S||o<0||o>=y||(h=4*(a*y+o),l=p[f*m+d],t+=_[h]*l,i+=_[h+1]*l,r+=_[h+2]*l,b||(n+=_[h+3]*l));w[s]=t,w[s+1]=i,w[s+2]=r,w[s+3]=b?_[s+3]:n}e.imageData=C},getUniformLocations:function(e,t){return{uMatrix:e.getUniformLocation(t,"uMatrix"),uOpaque:e.getUniformLocation(t,"uOpaque"),uHalfSize:e.getUniformLocation(t,"uHalfSize"),uSize:e.getUniformLocation(t,"uSize")}},sendUniformData:function(e,t){e.uniform1fv(t.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),t.Image.filters.Convolute.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(e){var t,i,r=e.imageData.data,n=r.length,s=this.mode;for(t=0;tl[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[e]+"}\n}"},retrieveShader:function(e){var t,i=this.type+"_"+this.mode;return e.programCache.hasOwnProperty(i)||(t=this.buildSource(this.mode),e.programCache[i]=this.createProgram(e.context,t)),e.programCache[i]},applyTo2d:function(e){var i,r,n,s,o,a,h,l=e.imageData.data,c=l.length,u=1-this.alpha;i=(h=new t.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=e||t<=-e)return 0;if(t<1.1920929e-7&&t>-1.1920929e-7)return 1;var i=(t*=Math.PI)/e;return a(t)/t*a(i)/i}},applyTo2d:function(e){var t=e.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=t.width,a=t.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(e,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(e,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(e,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(e,s,a,h,l)),e.imageData=n},sliceByTwo:function(e,i,n,s,o){var a,h,l=e.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,_=t.filterBackend.resources,p=0,m=0,v=i,y=0;for(_.sliceByTwo||(_.sliceByTwo=document.createElement("canvas")),((a=_.sliceByTwo).width<1.5*i||a.height=t)){M=r(1e3*s(x-C.x)),S[M]||(S[M]={});for(var L=w.y-y;L<=w.y+y;L++)L<0||L>=o||(F=r(1e3*s(L-C.y)),S[M][F]||(S[M][F]=f(n(i(M*p,2)+i(F*m,2))/1e3)),(T=S[M][F])>0&&(I+=T,A+=T*c[E=4*(L*t+x)],O+=T*c[E+1],R+=T*c[E+2],D+=T*c[E+3]))}d[E=4*(b*a+h)]=A/I,d[E+1]=O/I,d[E+2]=R/I,d[E+3]=D/I}return++h1&&F<-1||(y=2*F*F*F-3*F*F+1)>0&&(T+=y*f[3+(M=4*(D+I*t))],C+=y,f[M+3]<255&&(y=y*f[M+3]/250),w+=y*f[M],b+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=w/S,_[v+1]=b/S,_[v+2]=x/S,_[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),t.Image.filters.Resize.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(e){if(0!==this.contrast){var t,i=e.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(t=0;t1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio),e=t*this.blur*.12,this.horizontal?i[0]=e:i[1]=e,i}}),i.Blur.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(e){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,e)},applyTo2d:function(e){var t,i=e.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),t=0,n=256;t'},_getCacheCanvasDimensions:function(){var e=this.callSuper("_getCacheCanvasDimensions"),t=this.fontSize;return e.width+=t*e.zoomX,e.height+=t*e.zoomY,e},_render:function(e){var t=this.path;t&&!t.isNotVisible()&&t._render(e),this._setTextStyles(e),this._renderTextLinesBackground(e),this._renderTextDecoration(e,"underline"),this._renderText(e),this._renderTextDecoration(e,"overline"),this._renderTextDecoration(e,"linethrough")},_renderText:function(e){"stroke"===this.paintFirst?(this._renderTextStroke(e),this._renderTextFill(e)):(this._renderTextFill(e),this._renderTextStroke(e))},_setTextStyles:function(e,t,i){if(e.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":e.textBaseline="middle";break;case"ascender":e.textBaseline="top";break;case"descender":e.textBaseline="bottom"}e.font=this._getFontDeclaration(t,i)},calcTextWidth:function(){for(var e=this.getLineWidth(0),t=1,i=this._textLines.length;te&&(e=r)}return e},_renderTextLine:function(e,t,i,r,n,s){this._renderChars(e,t,i,r,n,s)},_renderTextLinesBackground:function(e){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var t,i,r,n,s,o,a,h=e.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,_=this._textLines.length;g<_;g++)if(t=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){r=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,n=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,m=r.length;p=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(e,i,r){var n=e+i.kernedWidth/2,s=this.path,o=t.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(e,t,i,r,n){var s,o=this.getCompleteStyleDeclaration(t,i),a=r?this.getCompleteStyleDeclaration(t,i-1):{},h=this._measureChar(e,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[t][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(e){if(this.__lineHeights[e])return this.__lineHeights[e];for(var t=this._textLines[e],i=this.getHeightOfChar(e,0),r=1,n=t.length;r0){var I=v+s+u;"rtl"===this.direction&&(I=this.width-I-d),l&&m&&(e.fillStyle=m,e.fillRect(I,c+w*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,m=p,r=n,o=a}else d+=f.kernedWidth;I=v+s+u,"rtl"===this.direction&&(I=this.width-I-d),e.fillStyle=p,g&&p&&e.fillRect(I,c+w*r+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(e)}},_getFontDeclaration:function(e,i){var r=e||this,n=this.fontFamily,s=t.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[t.isLikelyNode?r.fontWeight:r.fontStyle,t.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(e){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",e)))},_splitTextIntoLines:function(e){for(var i=e.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(e.underline=!0),e.textDecoration.indexOf("line-through")>-1&&(e.linethrough=!0),e.textDecoration.indexOf("overline")>-1&&(e.overline=!0),delete e.textDecoration)}x.IText=x.util.createClass(x.Text,x.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(e,t){this.callSuper("initialize",e,t),this.initBehavior()},setSelectionStart:function(e){e=Math.max(e,0),this._updateAndFire("selectionStart",e)},setSelectionEnd:function(e){e=Math.min(e,this.text.length),this._updateAndFire("selectionEnd",e)},_updateAndFire:function(e,t){this[e]!==t&&(this._fireSelectionChanged(),this[e]=t),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(e){this.clearContextTop(),this.callSuper("render",e),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(e){this.callSuper("_render",e)},clearContextTop:function(e){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this.canvas.contextTop,i=this.canvas.viewportTransform;t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(t),this._clearTextArea(t),e||t.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this._getCursorBoundaries(),t=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(e,t):this.renderSelection(e,t),t.restore()}},_clearTextArea:function(e){var t=this.width+4,i=this.height+4;e.clearRect(-t/2,-i/2,t,i)},_getCursorBoundaries:function(e){void 0===e&&(e=this.selectionStart);var t=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(e);return{left:t,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(e){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var t,i,r,n,s=0,o=0,a=this.get2DCursorLocation(e);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(e,t){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=e.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(e,t),t.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),t.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,t.fillRect(e.left+e.leftOffset-a/2,h+e.top+l,a,s)},renderSelection:function(e,t){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=e.left+f+_,y=p-_,S=g,C=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,C=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+C,y,S),e.topOffset+=d}},getCurrentCharFontSize:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fontSize")},getCurrentCharColor:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fill")},_getCurrentCharIndex:function(){var e=this.get2DCursorLocation(this.selectionStart,!0),t=e.charIndex>0?e.charIndex-1:0;return{l:e.lineIndex,c:t}}}),x.IText.fromObject=function(t,i){if(e(t),t.styles)for(var r in t.styles)for(var n in t.styles[r])e(t.styles[r][n]);x.Object._fromObject("IText",t,i,"text")}}(),b=x.util.object.clone,x.util.object.extend(x.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var e=this;this.on("added",(function(){var t=e.canvas;t&&(t._hasITextHandlers||(t._hasITextHandlers=!0,e._initCanvasHandlers(t)),t._iTextInstances=t._iTextInstances||[],t._iTextInstances.push(e))}))},initRemovedHandler:function(){var e=this;this.on("removed",(function(){var t=e.canvas;t&&(t._iTextInstances=t._iTextInstances||[],x.util.removeFromArray(t._iTextInstances,e),0===t._iTextInstances.length&&(t._hasITextHandlers=!1,e._removeCanvasHandlers(t)))}))},_initCanvasHandlers:function(e){e._mouseUpITextHandler=function(){e._iTextInstances&&e._iTextInstances.forEach((function(e){e.__isMousedown=!1}))},e.on("mouse:up",e._mouseUpITextHandler)},_removeCanvasHandlers:function(e){e.off("mouse:up",e._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(e,t,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},e.animate("_currentCursorOpacity",t,{duration:i,onComplete:function(){n.isAborted||e[r]()},onChange:function(){e.canvas&&e.selectionStart===e.selectionEnd&&e.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var e=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){e._currentTickCompleteState=e._animateCursor(e,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(e){var t=this,i=e?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){t._tick()}),i)},abortCursorAnimation:function(){var e=this._currentTickState||this._currentTickCompleteState,t=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,e&&t&&t.clearContext(t.contextTop||t.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(e){var t=0,i=e-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i--;for(;/\S/.test(this._text[i])&&i>-1;)t++,i--;return e-t},findWordBoundaryRight:function(e){var t=0,i=e;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i++;for(;/\S/.test(this._text[i])&&i-1;)t++,i--;return e-t},findLineBoundaryRight:function(e){for(var t=0,i=e;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=t):(this.selectionStart=t,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(e,t,i){var r=i.slice(0,e),n=x.util.string.graphemeSplit(r).length;if(e===t)return{selectionStart:n,selectionEnd:n};var s=i.slice(e,t);return{selectionStart:n,selectionEnd:n+x.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(e,t,i){var r=i.slice(0,e).join("").length;return e===t?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(e,t).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var e=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=e.selectionStart,this.hiddenTextarea.selectionEnd=e.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var e=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var e=this._calcTextareaPosition();this.hiddenTextarea.style.left=e.left,this.hiddenTextarea.style.top=e.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var e=this.inCompositionMode?this.compositionStart:this.selectionStart,t=this._getCursorBoundaries(e),i=this.get2DCursorLocation(e),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=t.leftOffset,a=this.calcTransformMatrix(),h={x:t.left+o,y:t.top+t.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,_=c.clientWidth/u,p=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=_,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var e=this._textBeforeEdit!==this.text,t=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),e&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),e&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var e in this.styles)this._textLines[e]||delete this.styles[e]},removeStyleFromTo:function(e,t){var i,r,n=this.get2DCursorLocation(e,!0),s=this.get2DCursorLocation(t,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(e,t){var i=b(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>e&&(this.styles[n+t]=i[n],i[n-t]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(e,t,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[e].length===t;for(var h in i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&(n=this.styles[e][0===t?t:t-1]),this.styles[e]){var l=parseInt(h,10);l>=t&&(o=!0,s[l-t]=this.styles[e][h],a&&0===t||delete this.styles[e][h])}var c=!1;for(o&&!a&&(this.styles[e+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[e+i]={0:b(r[i-1])}:n?this.styles[e+i]={0:b(n)}:delete this.styles[e+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(e,t,i,r){this.styles||(this.styles={});var n=this.styles[e],s=n?b(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=t&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[e]||(this.styles[e]={}),this.styles[e][t+i]=b(r[i]));else if(n)for(var h=n[t?t-1:1];h&&i--;)this.styles[e][t+i]=b(h)},insertNewStyleBlock:function(e,t,i){for(var r=this.get2DCursorLocation(t,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(e,t,i){i<=e?(t===e?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=e),this.selectionStart=i):i>e&&ie?this.selectionStart=e:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>e?this.selectionEnd=e:this.selectionEnd<0&&(this.selectionEnd=0)}}),x.util.object.extend(x.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(e){if(this.canvas){this.__newClickTime=+new Date;var t=e.pointer;this.isTripleClick(t)&&(this.fire("tripleclick",e),this._stopEvent(e.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=t,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(e){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===e.x&&this.__lastPointer.y===e.y},_stopEvent:function(e){e.preventDefault&&e.preventDefault(),e.stopPropagation&&e.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(e){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(e.e))},tripleClickHandler:function(e){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(e.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(e.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(e){if(this.__isMousedown=!1,!(!this.editable||this.group||e.transform&&e.transform.actionPerformed||e.e.button&&1!==e.e.button)){if(this.canvas){var t=this.canvas._activeObject;if(t&&t!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(e.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(e){var t=this.getSelectionStartFromPointer(e),i=this.selectionStart,r=this.selectionEnd;e.shiftKey?this.setSelectionStartEndWithShift(i,r,t):(this.selectionStart=t,this.selectionEnd=t),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(e){for(var t,i=this.getLocalPointer(e),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,t=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=t.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),x.util.object.extend(x.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=x.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var e=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+e.top+"; left: "+e.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+e.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):x.document.body.appendChild(this.hiddenTextarea),x.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),x.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),x.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),x.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(x.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(e){if(this.isEditing){var t="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(e.keyCode in t)this[t[e.keyCode]](e);else{if(!(e.keyCode in this.ctrlKeysMapDown)||!e.ctrlKey&&!e.metaKey)return;this[this.ctrlKeysMapDown[e.keyCode]](e)}e.stopImmediatePropagation(),e.preventDefault(),e.keyCode>=33&&e.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(e){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:e.keyCode in this.ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)&&(this[this.ctrlKeysMapUp[e.keyCode]](e),e.stopImmediatePropagation(),e.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(e){var t=this.fromPaste;if(this.fromPaste=!1,e&&e.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[e][t-1]).left+i.width),r},getDownCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||e.metaKey||34===e.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(e,t){return e.shiftKey&&this.selectionStart!==this.selectionEnd&&t?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||e.metaKey||33===e.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(e,t){for(var i,r,n=this._textLines[e],s=this._getLineLeftOffset(e),o=0,a=0,h=n.length;at){r=!0;var l=s-i,c=s,u=Math.abs(l-t);o=Math.abs(c-t)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",e)},moveCursorUp:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",e)},_moveCursorUpOrDown:function(e,t){var i=this["get"+e+"CursorOffset"](t,"right"===this._selectionDirection);t.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(e){var t="left"===this._selectionDirection?this.selectionStart+e:this.selectionEnd+e;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,t),0!==e},moveCursorWithoutShift:function(e){return e<0?(this.selectionStart+=e,this.selectionEnd=this.selectionStart):(this.selectionEnd+=e,this.selectionStart=this.selectionEnd),0!==e},moveCursorLeft:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",e)},_move:function(e,t,i){var r;if(e.altKey)r=this["findWordBoundary"+i](this[t]);else{if(!e.metaKey&&35!==e.keyCode&&36!==e.keyCode)return this[t]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[t])}if(void 0!==typeof r&&this[t]!==r)return this[t]=r,!0},_moveLeft:function(e,t){return this._move(e,t,"Left")},_moveRight:function(e,t){return this._move(e,t,"Right")},moveCursorLeftWithoutShift:function(e){var t=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(t=this._moveLeft(e,"selectionStart")),this.selectionEnd=this.selectionStart,t},moveCursorLeftWithShift:function(e){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(e,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(e,"selectionStart")):void 0},moveCursorRight:function(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",e)},_moveCursorLeftOrRight:function(e,t){var i="moveCursor"+e+"With";this._currentCursorOpacity=1,t.shiftKey?i+="Shift":i+="outShift",this[i](t)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(e){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(e,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(e,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(e){var t=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(t=this._moveRight(e,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,t},removeChars:function(e,t){void 0===t&&(t=e+1),this.removeStyleFromTo(e,t),this._text.splice(e,t-e),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(e,t,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=x.util.string.graphemeSplit(e);this.insertNewStyleBlock(n,i,t),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var e=x.util.toFixed,t=/ +/g;x.util.object.extend(x.Text.prototype,{_toSVG:function(){var e=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(e.textTop,e.textLeft);return this._wrapSVGTextAndBg(t)},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(e){var t=this.getSvgTextDecoration(this);return[e.textBgRects.join(""),'\t\t",e.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(e,t){var i,r=[],n=[],s=e;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",x.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(e,t,i,r){var n,s,o,a,h,l=this.getHeightOfLine(t),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[t];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)h=g===_||this.charSpacing,u+=f[g],o=this.__charBounds[t][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(t,g),s=this.getCompleteStyleDeclaration(t,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(t,g)||{},e.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(t,i,r,n,s,o){var a=x.Object.NUM_FRACTION_DIGITS;t.push("\t\t\n')},_setSVGTextLineBg:function(e,t,i,r){for(var n,s,o=this._textLines[t],a=this.getHeightOfLine(t)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(e){for(var t=0,i=0,r=0,n={},s=0;s0?(i=0,r++,t++):!this.splitByGrapheme&&this._reSpaceAndTab.test(e.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:t,offset:i},r+=e.graphemeLines[s].length,i+=e.graphemeLines[s].length;return n},styleHas:function(e,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return t.Text.prototype.styleHas.call(this,e,i)},isEmptyStyles:function(e){if(!this.styles)return!0;var t,i,r=0,n=!1,s=this._styleMap[e],o=this._styleMap[e+1];for(var a in s&&(e=s.line,r=s.offset),o&&(n=o.line===e,t=o.offset),i=void 0===e?this.styles:{line:this.styles[e]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=m,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(h),_+n>this.dynamicMinWidth&&(this.dynamicMinWidth=_-m+n),a},isEndOfWrapping:function(e){return!this._styleMap[e+1]||this._styleMap[e+1].line!==this._styleMap[e].line},missingNewlineOffset:function(e){return this.splitByGrapheme?this.isEndOfWrapping(e)?1:0:1},_splitTextIntoLines:function(e){for(var i=t.Text.prototype._splitTextIntoLines.call(this,e),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},k={};function B(e){var t=k[e];if(void 0!==t)return t.exports;var i=k[e]={exports:{}};return P[e](i,i.exports,B),i.exports}B.d=(e,t)=>{for(var i in t)B.o(t,i)&&!B.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},B.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var N={};(()=>{let e;B.d(N,{R:()=>e}),e="undefined"!=typeof document&&"undefined"!=typeof window?B(653).fabric:{version:"5.2.1"}})();var j=N.R; /*! * Dynamsoft JavaScript Library * @product Dynamsoft Camera Enhancer JS Edition @@ -18,4 +18,4 @@ * @version 3.3.1 (js 20230217) * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest - */const V="undefined"==typeof self;let U,G,W,H,Y;if("undefined"!=typeof navigator&&(U=navigator,G=U.userAgent,W=U.platform,H=U.mediaDevices),!V){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:U.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:W,search:"Win"},Mac:{str:W},Linux:{str:W}};let i="unknownBrowser",r=0,n="unknownOS";for(let t in e){const n=e[t]||{};let s=n.str||G,o=n.search||t,a=n.verStr||G,h=n.verSearch||t;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=t;for(let e of h){let t=a.indexOf(e);if(-1!=t){r=parseFloat(a.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let r=i.str||G,s=i.search||e;if(-1!=r.indexOf(s)){n=e;break}}"Linux"==n&&-1!=G.indexOf("Windows NT")&&(n="HarmonyOS"),Y={browser:i,version:r,OS:n}}V&&(Y={browser:"ssr",version:0,OS:"ssr"});const X="undefined"!=typeof WebAssembly&&G&&!(/Safari/.test(G)&&!/Chrome/.test(G)&&/\(.+\s11_2_([2-6]).*\)/.test(G)),z=!("undefined"==typeof Worker),Z=!(!H||!H.getUserMedia),K=async()=>{let e=!1;if(Z)try{(await H.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===Y.browser&&Y.version>66||"Safari"===Y.browser&&Y.version>13||"OPR"===Y.browser&&Y.version>43||"Edge"===Y.browser&&Y.version;const J=(()=>{if(!V&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})();class q{constructor(e,t){this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,this._setFabricObject(e),this._mediaType=e.type,this.styleSelector="default",this.styleId=t}get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}_setFabricObject(e){this._fabricObject=e,this._fabricObject.on("selected",(()=>{this.styleSelector="selected"})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.styleSelector="selected":this.styleSelector="default","textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),e.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}_on(e,t){if(!t)return;const i=e.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${e}' does not exist.`);let n=r.get(t);n||(n=e=>{const i=e.e;if(!i)return void(t&&t.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let e,t,n,s;const o=i.target.getBoundingClientRect();e=o.left,t=o.top,n=e+window.scrollX,s=t+window.scrollY;const a=this._drawingLayer.fabricCanvas.lowerCanvasEl.width,h=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,l=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),c=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),u=l/c,d=a/h,f=this._drawingLayer._getObjectFit();let g,_,p,m,v=1;if("contain"===f)u0?i-1:r,ee),actionName:"modifyPolygon",pointIndex:i}),e}),{})}_extendSet(e,t){if("vertices"===e){const e=this._fabricObject;if(e.group){const i=e.group;e.points=t.map((e=>({x:e.x-i.left-i.width/2,y:e.y-i.top-i.height/2}))),i.addWithUpdate()}else e.points=t;const i=e.points.length-1;return e.controls=e.points.reduce((function(e,t,r){return e["p"+r]=new j.Control({positionHandler:Q,actionHandler:te(r>0?r-1:i,ee),actionName:"modifyPolygon",pointIndex:r}),e}),{}),e._setPositionDimensions({}),!0}}_extendGet(e){if("vertices"===e){const e=[],t=this._fabricObject;if(t.selectable&&!t.group)for(let i in t.oCoords)e.push({x:t.oCoords[i].x,y:t.oCoords[i].y});else for(let i of t.points){let r=i.x-t.pathOffset.x,n=i.y-t.pathOffset.y;const s=j.util.transformPoint({x:r,y:n},t.calcTransformMatrix());e.push({x:s.x,y:s.y})}return e}}}const re=e=>{let t=(e=>e.split("\n").map((e=>e.split("\t"))))(e);return(e=>{for(let t=0;;t++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=e[r].length-1)continue;let n=" ".repeat(i+2-e[r][t].length);e[r][t]=e[r][t].concat(n)}}})(t),(e=>{let t="";for(let i=0;im?(g=d,_=d/p,{x:n.x*i.width,y:(n.y-(f-_)/2)*i.width}):(g=f*p,_=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>m?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},j.Canvas.prototype._onTouchStart=function(e){var t=this.findTarget(e);!this.allowTouchScrolling&&e.cancelable&&e.preventDefault&&e.preventDefault(),t&&e.cancelable&&e.preventDefault&&e.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(e)),this.__onMouseDown(e),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();j.util.addListener(j.document,"touchend",this._onTouchEnd,{passive:!1}),j.util.addListener(j.document,"touchmove",this._onMouseMove,{passive:!1}),j.util.removeListener(i,r+"down",this._onMouseDown)},j.Textbox.prototype._wrapLine=function(e,t,i,r){const n=e.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?j.util.string.graphemeSplit(e):e.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,_=0,p=0,m=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!m?(h.push(l),l=[],o=g,m=!0):o+=v,m||a||l.push(f),l=l.concat(u),_=a?0:this._measureWord([f],t,d),d++,m=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class se{constructor(e,t,i,r){let n,s;switch(this.mapMediaType_Style=new Map,this.mode="viewer",this.onSelectionChange=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,e.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=e.getFabricCanvas():(this.fabricCanvas=new j.Canvas(e,Object.assign(r,{allowTouchScrolling:!0})),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(e){const t=e.selected,i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(e){const t=this.getActiveObjects(),i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{const t=[];for(let r of i)e.hasDrawingItem(r)&&t.push(r);t.length>0&&e.onSelectionChange&&e.onSelectionChange([],t)}),0)}})),this.fabricCanvas.on("selection:updated",(function(e){const t=e.selected,i=e.deselected,r=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of i){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of r){const r=[],n=[];for(let i of t){const t=i.getDrawingItem();t._drawingLayer===e&&r.push(t)}for(let t of i){const i=t.getDrawingItem();i._drawingLayer===e&&n.push(i)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(r,n)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",e.getFabricCanvas=()=>this.fabricCanvas),this.id=t,this._mapDrawingStyles=i,t){case 1:n=i.get(1),s=i.get(5);break;case 2:n=i.get(2),s=i.get(6);break;case 3:n=i.get(3),s=i.get(7);break;default:n=i.get(4),s=i.get(8)}for(let e of q.arrMediaTypes)this.mapMediaType_Style.set(e,{default:n,selected:s})}getId(){return this.id}_getDrawingStyle(e,t){if("number"!=typeof e)throw new Error("Invalid style id.");const i=this._mapDrawingStyles.get(e);return i?t?JSON.parse(JSON.stringify(i)):i:null}setVisible(e){if(e){for(let e of this._arrFabricObject)e.visible=!0;this._visible=!0}else{for(let e of this._arrFabricObject)e.visible=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(e){return e.styleId?e.styleId:this.mapMediaType_Style.get(e._mediaType)[e.styleSelector].styleId}_getItemCurrentStyle(e){if(e.styleId)return this._getDrawingStyle(e.styleId);return e._mapStyle.get(e.styleSelector)||null}_changeMediaTypeCurStyleInStyleSelector(e,t,i,r){let n;switch(e){case"rect":n=this.fabricCanvas.getObjects("rect");break;case"arc":n=this.fabricCanvas.getObjects("circle");break;case"polygon":n=this.fabricCanvas.getObjects("polygon");break;case"image":n=this.fabricCanvas.getObjects("image");break;case"text":n=this.fabricCanvas.getObjects("textbox");break;case"line":n=this.fabricCanvas.getObjects("line");break;case"path":n=this.fabricCanvas.getObjects("path")}for(let e of n){if(!this._arrFabricObject.includes(e))continue;const r=e.getDrawingItem();r.styleSelector===t&&this._changeItemStyle(r,i,!0)}r||this.fabricCanvas.renderAll()}_changeItemStyle(e,t,i){if(!e||!t)return;const r=e._getFabricObject();"number"==typeof e.styleId&&(t=this._getDrawingStyle(e.styleId)),r.strokeWidth=t.lineWidth,"fill"===t.paintMode?(r.fill=t.fillStyle,r.stroke=t.fillStyle):"stroke"===t.paintMode?(r.fill="transparent",r.stroke=t.strokeStyle):"strokeAndFill"===t.paintMode&&(r.fill=t.fillStyle,r.stroke=t.strokeStyle),r.fontFamily&&(r.fontFamily=t.fontFamily),r.fontSize&&(r.fontSize=t.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(e,t,i){if(!e||!t)return;const r=e.getChildItems();if("add"===i){if(r.includes(t))return;const i=t._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");t._zIndex=null}else{let i;if(t.styleId)i=this._getDrawingStyle(t.styleId);else{i=this.mapMediaType_Style.get(t._mediaType)[e.styleSelector];const r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected,!0)},n=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default,!0)};t._on("selected",r),t._on("deselected",n),t._funcChangeStyleToSelected=r,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,i,!0)}e._fabricObject.addWithUpdate(t._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(t))return;t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,e._fabricObject.removeWithUpdate(t._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(e,t){let i=e._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===e._mediaType){n=e.getChildItems();for(let e of n)if(e._drawingLayer&&e._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(t&&"object"==typeof t&&!Array.isArray(t))for(let e in t)i.set(e,t[e]);if(n){for(let e of n){const t=this.mapMediaType_Style.get(e._mediaType);for(let i of q.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)s=this._getDrawingStyle(e.styleId);else{s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e._on("selected",i),e._on("deselected",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of q.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)s=this._getDrawingStyle(e.styleId);else{s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default)};e._on("selected",i),e._on("deselected",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}this._changeItemStyle(e,s)}e._zIndex=this.id,e._drawingLayer=this,e._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let t=0;t{for(let t of this._arrDrawingLayer)if(t.getId()===e)return!0;return!1};if(void 0===t){for(let e=100;;e++)if(!i(e)){t=e;break}}else if(i(t))throw new Error("Existed drawing layer id.");const r=new se(e,t,this._mapDrawingStyles,{enableRetinaScaling:!1});return r._manager=this,this._arrDrawingLayer.push(r),this._switchPointerEvent(),r}deleteDrawingLayer(e){const t=this.getDrawingLayer(e);if(!t)return;const i=this._arrDrawingLayer;t.dispose(),i.splice(i.indexOf(t),1),this._switchPointerEvent()}clearDrawingLayers(){for(let e of this._arrDrawingLayer)e.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(e){for(let t of this._arrDrawingLayer)if(t.getId()===e)return t;return null}getDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const e=this._arrDrawingLayer[0].fabricCanvas.getActiveObjects(),t=[];for(let i of e)t.push(i.getDrawingItem());return t}setDimensions(e,t){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(e,t)}setObjectFit(e){for(let t of this._arrDrawingLayer)t&&t._setObjectFit(e)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(e){this._arrDrawingLayer.length&&(this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.display=e?"block":"none")}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let e of this._arrDrawingLayer)e.getMode()}}class ae{constructor(e){this._controlTarget=null,this._arrUsers=[],this._mapAction_UserArgs=new Map,this._mapProperty_UserValue=new Map,this._mapAction_Callbacks=new Map,this._controlTarget=e}setControlTarget(e){this._controlTarget=e}getControlTarget(){return this._controlTarget}register(e){this._arrUsers.includes(e)||this._arrUsers.push(e)}logout(e){const t=this._arrUsers.indexOf(e);-1!==t&&(this.clearUserDisiredAction({user:e}),this.clearUserDisiredValue({user:e}),this._arrUsers.splice(t,1))}getRegisteredUsers(){return this._arrUsers}ifUserExisted(e){return this._arrUsers.includes(e)}setDisiredValue(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");r&&(this._controlTarget[t]=i),this._mapProperty_UserValue.get(t)?this._mapProperty_UserValue.get(t).set(e,i):this._mapProperty_UserValue.set(t,new Map([[e,i]]))}clearUserDisiredValue(e){if(e&&(e.user||e.property)){if(e.property&&e.user){const t=this._mapProperty_UserValue.get(e.property);if(!t)return;t.delete(e.user)}else if(e.property)this._mapProperty_UserValue.delete(e.property);else if(e.user)for(let t of this._mapProperty_UserValue.values())t.delete(e.user)}else this._mapProperty_UserValue=new Map}getValue(e){if(!this._controlTarget)throw new Error("Control target is not set.");return this._controlTarget[e]}getPropertyDisiredValue(e){if(this._mapProperty_UserValue.get(e)){const t=[],i=this._mapProperty_UserValue.get(e);for(let e of i.values())t.push(e);return t}return null}setDisiredAction(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");return i||(i=[]),r?this._controlTarget[t](...i):(this._mapAction_UserArgs.get(t)?this._mapAction_UserArgs.get(t).set(e,i):this._mapAction_UserArgs.set(t,new Map([[e,i]])),this._render(t))}clearUserDisiredAction(e){if(e&&(e.user||e.actionName)){if(e.actionName&&e.user){const t=this._mapAction_UserArgs.get(e.actionName);if(!t)return;t.delete(e.user)}else if(e.actionName)this._mapAction_UserArgs.delete(e.actionName);else if(e.user)for(let t of this._mapAction_UserArgs.values())t.delete(e.user);this.render()}else this._mapAction_UserArgs=new Map}addCallback(e,t){const i=this._mapAction_Callbacks.get(e);i?i.push(t):this._mapAction_Callbacks.set(e,[t])}removeCallback(e,t){const i=this._mapAction_Callbacks.get(e);if(!i)return;const r=i.indexOf(t);-1!==r&&i.splice(r,1)}clearCallback(e){e?this._mapAction_Callbacks.delete(e):this._mapAction_Callbacks.clear()}_fireCallback(e){const t=this._mapAction_Callbacks.get(e);if(t)for(let e of t){if(!e)return;setTimeout(e.bind(this._controlTarget),0)}}_render(e){const t=this._mapAction_UserArgs.get(e);if(!t)throw new Error("Unrecorded action.");if(t.size===this._arrUsers.length){let i=[];for(let e of t.values())e.length>0&&(i=e);if(this._controlTarget[e]){const t=this._controlTarget[e](...i);return this._mapAction_UserArgs.delete(e),this._fireCallback(e),t}}}render(e){if(e)return this._render(e);for(let e of this._mapAction_UserArgs.keys())this._render(e)}}class he{static multiply(e,t){const i=[];for(let r=0;r<3;r++){const n=t.slice(3*r,3*r+3);for(let t=0;t<3;t++){const r=[e[t],e[t+3],e[t+6]].reduce(((e,t,i)=>e+t*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,t,i){return he.multiply(e,[1,0,0,0,1,0,t,i,1])}static rotate(e,t){var i=Math.cos(t),r=Math.sin(t);return he.multiply(e,[i,-r,0,r,i,0,0,0,1])}static scale(e,t,i){return he.multiply(e,[t,0,0,0,i,0,0,0,1])}}var le;!function(e){e.GREY="grey",e.GREY32="grey32",e.RGBA="rgba",e.RBGA="rbga",e.GRBA="grba",e.GBRA="gbra",e.BRGA="brga",e.BGRA="bgra"}(le||(le={}));const ce=(e,t,i,r)=>{let n=t+Math.round((e-t)/i)*i;return r&&(n=Math.min(n,r)),n};class ue{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this._predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this._mapCameraResolutions=new Map,this._bWebGLSupported=!0,this.extraBindings=[],this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode&&!this.getDrawingLayers().some((e=>"editor"==e.getMode()))){if(!this._singleFrameModeIpt){const e=document.createElement("input");this._singleFrameModeIpt=e,e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.addEventListener("change",(async()=>{const t=e.files[0];e.value="";const i=await(async e=>{let t=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(t=await createImageBitmap(e),t)return t}catch(e){}var r;return t||(i=await(r=e,new Promise(((e,t)=>{let i=URL.createObjectURL(r),n=new Image;n.dbrObjUrl=i,n.src=i,n.onload=()=>{e(n)},n.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})(t),r=i instanceof HTMLImageElement?i.naturalWidth:i.width,n=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=n;const s=e=>{const t=Date.now();if(0===r||0===n)return null;if(e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");const i=this._scanRegion,s=this.getFrameSize(r,n,i,this.maxCvsSideLength);if(!s)return null;let o=!0;r===s.sWidth&&n===s.sHeight&&(o=!1);const a=this.mapPixelFormatString_Enum.get(this.framePixelFormat.toLowerCase()),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:s.sx,sy:s.sy,width:s.dWidth,height:s.dHeight,colorMode:null,pixelFormat:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:s.sWidth,_sHeight:s.sHeight,_bUseWebGL:null},l=this._getImageData(e,r,n,s,null,{pixelFormat:a});if(!l)return null;const c=Date.now();return h.data=l.data,h.pixelFormat=h.colorMode=l.pixelFormat,h._bUseWebGL=l._bUseWebGL,h.timeSpent=c-t,h.timeStamp=c,l.pixelFormat===le.GREY?h.stride=h.width:h.stride=4*h.width,h};(e=>{let t=this._cvsSingleFrameMode;if(!t){if(t=document.createElement("canvas"),!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(t),t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit="contain",t.style.pointerEvents="none",this._cvsSingleFrameMode=t}t.width==r&&t.height==n||(t.width=r,t.height=n);const i=t.getContext("2d");i.clearRect(0,0,t.width,t.height),i.drawImage(e,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);let o;this._updateDrawingLayersSize();try{o=s(i)}catch(e){throw e}const a=this.mapCameraEvents.get("singleframeacquired");for(let e of a)if(e)try{const t={data:new Uint8Array(o.data),region:JSON.parse(JSON.stringify(o.region)),sx:o.sx,sy:o.sy,width:o.width,height:o.height,stride:o.stride,colorMode:o.colorMode,pixelFormat:o.pixelFormat,timeSpent:o.timeSpent,timeStamp:o.timeStamp,isCropped:o.isCropped,toCanvas:o.toCanvas,_sWidth:o._sWidth,_sHeight:o._sHeight,_bUseWebGL:o._bUseWebGL};await e.apply(this,[t])}catch(e){console.error(e)}})),e.style.position="fixed",e.style.left="-1px",e.style.top="-1px",e.style.width="1px",e.style.height="1px",e.style.backgroundColor="transparent",e.style.color="transparent",document.body.appendChild(e)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._framePixelFormat=void 0,this._defaultFramePixelFormat="rgba",this.mapPixelFormatString_Enum=new Map([["grey",le.GREY],["grey32",le.GREY32],["rgba",le.RGBA],["rbga",le.RBGA],["grba",le.GRBA],["gbra",le.GBRA],["brga",le.BRGA],["bgra",le.BGRA]]),this.shaderPixelFormat=le.RGBA,this.maxVideoCvsLength=3,this._reusedCvs=null,this._reusedWebGLCvs=null,this._tempDataContainer=null,this._webGLTexture=null,this._webGLProgramInfo=null,this._webGLBuffers=null,this._softwareScale=1,this._scaleCenter={x:0,y:0},this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,_focusArea:null},this._tapFocusEnabled=!0,this._focusSupported=!0,this._tapDoFocus=async e=>{if(this._touchMoved)return void(this._touchMoved=!1);if(!this._tapFocusEnabled)return;if(!this._bOpen)return;if(this.singleFrameMode)return;if(!this._video||this._video.paused)return;if(!this._videoTrack)return;if(!this._focusSupported)return;if(this.getDrawingLayers().some((e=>"editor"==e.getMode())))return;if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let t,i,r,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),e instanceof MouseEvent)t=e.clientX,i=e.clientY;else{if(!(e instanceof TouchEvent))throw new Error("Unknown event type.");if(!e.changedTouches.length)return;t=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY}const s=this.getVideoFit(),o=this._video.videoWidth,a=this._video.videoHeight,h=this._elContainer.getBoundingClientRect(),l=h.left,c=h.top,u=window.getComputedStyle(this._elContainer),d=parseFloat(u.width),f=parseFloat(u.height),g=d/f,_=o/a;let p=1;if("contain"===s)_>g?(p=d/o,r=(t-l)/p,n=(i-c-(f-d/_)/2)/p):(p=f/a,n=(i-c)/p,r=(t-l-(d-f*_)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");_>g?(p=f/a,n=(i-c)/p,r=(t-l+(f*_-d)/2)/p):(p=d/o,r=(t-l)/p,n=(i-c+(d/_-f)/2)/p)}const m={x:r+"px",y:n+"px"},v=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=v;await this._setLocalFocus(m,v,y,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance),this._focusParameters.taskBackToContinous=setTimeout((()=>{this._videoTrack&&this._videoTrack.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime)},this._touchMoved=!1,this._touchMoveEvent=()=>{this._touchMoved=!0},this._recordedStates={},this.playCallbackInfo=null,this._toCanvas=function(){const e=document.createElement("canvas");let t;if(e.width=this.width,e.height=this.height,"grey"===(this.pixelFormat||this.colorMode)){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}await this.setResolution(e,t),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this.singleFrameMode)if("visible"===document.visibilityState){if(ue._onLog&&ue._onLog("DCE: document visible."),this._bOpen&&this._vc_bPlayingVideoBeforeHide)if(this.videoSrc)this._video.play();else if(this._video.srcObject){const e=this._video.srcObject.getTracks()[0];this._video.srcObject.active&&e&&!e.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(ue._onLog&&ue._onLog("DCE: document hidden."),["iPhone","iPad"].includes(Y.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let e of this._arrScanRegionOverlays)e&&(e.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&(e.style.display="",this._updateScanRegionOverlay(e));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null}static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:X,worker:z,getUserMedia:Z,camera:await K(),browser:Y.browser,version:Y.version,OS:Y.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");ue._engineResourcePath=(e=>{if(null==e&&(e="./"),!V){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(e){let t;try{t=window[e];const i="__storage_test__";return t.setItem(i,i),t.removeItem(i),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&t&&0!==t.length}}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"data"in e&&"region"in e&&"sx"in e&&"sy"in e&&"width"in e&&"height"in e&&("colorMode"in e||"pixelFormat"in e)&&"timeSpent"in e&&"timeStamp"in e&&"isCropped"in e&&"toCanvas"in e&&"_sWidth"in e&&"_sHeight"in e&&"_bUseWebGL"in e}static async testCameraAccess(){try{if(!navigator||!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return{ok:!1,message:"Insecure context."};(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()}))}catch(e){if("OverconstrainedError"===e.name||"NotFoundError"===e.name)return{ok:!1,message:"No camera detected."};if("NotAllowedError"===e.name)return{ok:!1,message:"No permission to access camera."};if("AbortError"===e.name)return{ok:!1,message:"Some problem occurred which prevented the device from being used."};if("NotReadableError"===e.name)return{ok:!1,message:"A hardware error occurred."};if("SecurityError"===e.name)return{ok:!1,message:"User media support is disabled."};throw e}return{ok:!0,message:"Successfully accessed the camera."}}set maxCvsSideLength(e){if(e<=0)throw new Error("Invalid value.");this._maxCvsSideLength=e}get maxCvsSideLength(){if(void 0!==this._maxCvsSideLength)return this._maxCvsSideLength;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxCvsSideLength");if(e&&1===e.length)return e[0]}return this._defaultMaxCvsSideLength}static set defaultUIElementURL(e){ue._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=ue._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",ue.engineResourcePath)}getUIElement(){return this.UIElement}async setUIElement(e){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof e||e instanceof String){if(!e.trim().startsWith("<")){let t=await fetch(e);if(!t.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+t.statusText);e=await t.text()}if(!e.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let t=document.createElement("div");t.innerHTML=e;for(let e=0;e100||e.regionTop>100||e.regionRight>100||e.regionBottom>100)))}set scanRegion(e){if(!this._checkValidRegion(e))throw new Error("Invalid region.");this._scanRegion=JSON.parse(JSON.stringify(e)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}setScanRegion(e){this.scanRegion=e}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}_calculateCvsSize(){if(!this._bOpen)return null;let e,t,i;if(this.singleFrameMode)e=this._imgWidth,t=this._imgHeight,i="contain";else{if(!this._video)return null;e=this._video.videoWidth,t=this._video.videoHeight,i=this.getVideoFit()}return{width:e,height:t,objectFit:i}}addScanRegionOverlayCanvas(){this._assertOpen();const e=document.createElement("canvas");if(this._updateScanRegionOverlay(e),!this._scanRegionOverlayContainer){const e=document.createElement("div");if(this._scanRegionOverlayContainer=e,e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.overflow="hidden",e.style.pointerEvents="none",this._layerBaseCvs)this._layerBaseCvs.parentElement.after(e);else if(this._cvsScanRegion)this._cvsScanRegion.after(e);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(e);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e)}this._recordedStates.overlayShow=!0}return this._scanRegionOverlayContainer.append(e),this._arrScanRegionOverlays.push(e),e}removeScanRegionOverlayCanvas(e){const t=this._arrScanRegionOverlays.indexOf(e);-1!==t&&(e.remove(),this._arrScanRegionOverlays.splice(t,1))}_updateScanRegionOverlay(e){if(!e)return;const t=this._calculateCvsSize();if(!t)return;const{width:i,height:r,objectFit:n}=t;if(i<=0||r<=0)return e.width=0,void(e.height=0);const s=this._getRegionInPixels(i,r,this._scanRegion),o=this.getFrameSize(i,r,this._scanRegion,this.maxCvsSideLength),a=o.dWidth,h=o.dHeight;e.width==a&&e.height==h||(e.width=a,e.height=h);const l=window.getComputedStyle(this._elContainer),c=parseFloat(l.width),u=parseFloat(l.height),d=c/u,f=i/r;let g,_,p,m,v=1;"contain"===n?(f>d?(v=c/i,g=0,_=(u-r*v)/2):(v=u/r,g=(c-i*v)/2,_=0),g+=s.regionLeft*v,_+=s.regionTop*v,p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):"cover"===n?(f>d?(v=u/r,g=s.regionLeft*v-(i*v-c)/2,_=s.regionTop*v):(v=c/i,g=s.regionLeft*v,_=s.regionTop*v-(r*v-u)/2),p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):(g=0,_=0,p=0,m=0),e.style.position="absolute",e.style.left=g+"px",e.style.top=_+"px",e.style.width=p+"px",e.style.height=m+"px"}showScanRegionOverlays(){this._scanRegionOverlayContainer&&("none"==this._scanRegionOverlayContainer.style.display&&(this._scanRegionOverlayContainer.style.display=""),this._recordedStates.overlayShow=!0)}hideScanRegionOverlays(){this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none",this._recordedStates.overlayShow=!1)}setViewDecorator(e,t){if(!e)return void(this._cvsViewDecorator&&(this._cvsViewDecorator.remove(),this._cvsViewDecorator=null));if(!t)throw new Error("Invalid area.");this._assertOpen();let i=[];if("string"==typeof e?i.push(e):Array.isArray(e)&&(i=JSON.parse(JSON.stringify(e))),!this._cvsViewDecorator){if(this._cvsViewDecorator=document.createElement("canvas"),this._scanRegionOverlayContainer)this._scanRegionOverlayContainer.after(this._cvsViewDecorator);else if(this._layerBaseCvs)this._layerBaseCvs.parentElement.after(this._cvsViewDecorator);else if(this._cvsScanRegion)this._cvsScanRegion.after(this._cvsViewDecorator);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(this._cvsViewDecorator);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(this._cvsViewDecorator);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(this._cvsViewDecorator)}this._recordedStates.decoratorShow=!0}this._decoratorArea=JSON.parse(JSON.stringify(t)),this._decoratorType.length=0;const r=["rectangle","focus"],n=["crossline","crosshair"];let s=!1,o=!1;for(let e of i)e=e.toLowerCase(),r.includes(e)&&!s&&(s=!0,this._decoratorType.push(e)),n.includes(e)&&!o&&(o=!0,!this._decoratorType.includes(e)&&this._decoratorType.push(e));this._updateViewDecorator()}getViewDecorator(){return{type:JSON.parse(JSON.stringify(this._decoratorType)),area:JSON.parse(JSON.stringify(this._decoratorArea)),canvas:this._cvsViewDecorator}}showViewDecorator(){this._cvsViewDecorator&&("none"==this._cvsViewDecorator.style.display&&(this._cvsViewDecorator.style.display=""),this._recordedStates.decoratorShow=!0)}hideViewDecorator(){this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none",this._recordedStates.decoratorShow=!1)}setViewDecoratorLineWidth(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("lineWidth"))throw new Error(`It is not allowed to change the property 'lineWidth' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].lineWidth=t,this._updateViewDecorator()}setViewDecoratorStrokeStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("strokeStyle"))throw new Error(`It is not allowed to change the property 'strokeStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].strokeStyle=t,this._updateViewDecorator()}setViewDecoratorFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("fillStyle"))throw new Error(`It is not allowed to change the property 'fillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].fillStyle=t,this._updateViewDecorator()}setViewDecoratorMaskFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("maskFillStyle"))throw new Error(`It is not allowed to change the property 'maskFillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].maskFillStyle=t,this._updateViewDecorator()}_updateViewDecorator(){if(!this._bOpen)return;if(!this._cvsViewDecorator||!this._decoratorArea)return;let e;if(this.singleFrameMode)e="contain";else{if(!this._video)return;e=this.getVideoFit()}const t=this._cvsViewDecorator;t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit=e,t.style.pointerEvents="none";const i=this.getVisibleRegion(!0),r=i.regionRight-i.regionLeft,n=i.regionBottom-i.regionTop;if(t.width==r&&t.height==n||(t.width=r,t.height=n),r<=0||n<=0)return;const s=t.getContext("2d");s.clearRect(0,0,t.width,t.height);const o=this._decoratorArea.x/100*r,a=this._decoratorArea.y/100*n,h=this._decoratorArea.width/100*r,l=this._decoratorArea.height/100*n;for(let e of this._decoratorType){if("rectangle"===e){s.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,s.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const e=s.lineWidth/2;s.strokeRect(Math.round(o-e),Math.round(a-e),Math.round(h+s.lineWidth),Math.round(l+s.lineWidth))}if("focus"===e){s.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.focus.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.focus.lineWidth,s.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const e=s.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];s.beginPath();for(let e=0;e{const e=parseFloat(window.getComputedStyle(this._elContainer).width),t=parseFloat(window.getComputedStyle(this._elContainer).height);let s,o={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?e/tthis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){if(void 0!==this._maxNumberOfFramesInBuffer)return this._maxNumberOfFramesInBuffer;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxNumberOfFramesInBuffer");if(e&&1===e.length)return e[0]}return this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(e){this._refreshInterval=e}get refreshInterval(){if(void 0!==this._refreshInterval)return this._refreshInterval;if(this._controler){const e=this._controler.getPropertyDisiredValue("refreshInterval");if(e&&1===e.length)return e[0]}return this._defaultRefreshInterval}static async createInstance(e){let t=new ue;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,ue.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ue.onWarning&&ue.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ue.onWarning&&ue.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),t._drawingLayersManager=new oe,t}static async playVideo(e,t,i){return new Promise(((r,n)=>{e||n(new Error("Invalid video element.")),t||n(new Error("Invalid source.")),e.onloadedmetadata=async()=>{e.onloadedmetadata=null,await e.play(),r(e)},"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,void 0!==i&&setTimeout((()=>n(new Error("Failed to play video. Timeout."))),i)}))}static findBestRearCamera(e){if(!e||!e.length)return null;const t=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"];for(let i of e){const e=i.label.toLowerCase();if(e&&t.some((t=>e.includes(t)))&&/\b0(\b)?/.test(e))return i.deviceId}return["Android","HarmonyOS"].includes(Y.OS)?e[e.length-1].deviceId:null}async play(e,t,i,r){let n;if(this._video&&this.videoSrc){ue._onLog&&(n=Date.now(),ue._onLog("DCE: start loading static video: "+n));const e=await ue.playVideo(this._video,this.videoSrc,4e3);if(ue._onLog&&ue._onLog("DCE: finish loading static video. Costs: "+(Date.now()-n)),!this._video)return e.pause(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};const t={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};this.playCallbackInfo=JSON.parse(JSON.stringify(t));const i=this.mapCameraEvents.get("played");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[i])}),0)}return this._recordedStates.videoPlaying=!0,t}if(this.singleFrameMode)return r&&r.notTriggerSingleFrameClick||this._clickIptSingleFrameMode(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};if(!this._video)throw new Error("'video' is null or undefined.");const s=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,s{var r;try{this._video&&this._video.srcObject&&this.stop(),ue._onLog&&ue._onLog("DCE: ======before video========");const n=()=>{if(!this._video)throw a&&a.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},s=this.getVideoSettings();let o,a;if("boolean"==typeof s.video&&(s.video={}),e)delete s.video.facingMode,s.video.deviceId={exact:e};else if(s.video.deviceId);else if(this._lastDeviceId)delete s.video.facingMode,s.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&ue.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete s.video.facingMode,s.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),t=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&t&&(s.video.width=e,s.video.height=t)}else if(this.ifSkipCameraInspection);else if(s.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=s.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){o=!0;const e=ue.findBestRearCamera(this._allCameras);e&&(delete s.video.facingMode,s.video.deviceId={ideal:e})}}t&&(s.video.width={ideal:t}),i&&(s.video.height={ideal:i}),ue._onLog&&ue._onLog("DCE: ======try getUserMedia========");let h=[0,500],l=null;const c=async e=>{for(let t of h){t&&await new Promise((e=>setTimeout(e,t))),n();try{ue._onLog&&ue._onLog("DCE: ask "+JSON.stringify(e)),a=await navigator.mediaDevices.getUserMedia(e);break}catch(e){l=e,ue._onLog&&ue._onLog("DCE: "+e.message||e)}}};let u;if(await c(s),a||(ue._onLog&&ue._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(s)),"object"==typeof u.video&&(["iPhone","iPad"].includes(Y.OS)?(t>=1280||i>=1280?u.video.width=1280:t>=640||i>=640?u.video.width=640:(t<640||i<640)&&(u.video.width=320),delete u.video.height):o&&!s.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0),ue._onLog&&ue._onLog("DCE: "+u),await c(u)),a||(h=[1e3,2e3],await c(s)),a||await c(u),!a)throw l;const d=()=>{const e=a.getVideoTracks();let t,i;if(e.length&&(t=this._videoTrack=e[0]),this._video&&t){const e=t.getSettings();if(e)for(let r of this._allCameras)if(e.deviceId===r.deviceId){r._checked=!0,r.label=t.label,i=r;break}}this._currentCamera=i};if(await this.getAllCameras(!1),n(),o){d();const e=ue.findBestRearCamera(this._allCameras),t=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;e&&e!=t&&(a.getTracks().forEach((e=>{e.stop()})),h=[0,500,1e3,2e3],await c(s))}ue._onLog&&ue._onLog("DCE: ======play video========"),n(),await ue.playVideo(this._video,a,4e3),n(),ue._onLog&&ue._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=f,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),ue._onLog&&ue._onLog("DCE: got "+f),d(),this._renderSelCameraInfo();const g={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};g.deviceId&&(this._lastDeviceId=g.deviceId,this.ifSaveLastUsedCamera&&ue.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),s.video.width&&s.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(s.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(s.video.height)))));const _=this.mapCameraEvents.get("played");for(let e of _){if(!e)continue;const t=JSON.parse(JSON.stringify(g));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}return this.promisePlay=null,g}catch(e){throw this.promisePlay=null,this._bgLoading&&(this._bgLoading.style.display="none"),"NotFoundError"===e.name&&(DOMException?e=new DOMException("No camera available, please use a device with an accessible camera.",e.name):(e=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),e}})(),ue._onLog&&(n=Date.now(),ue._onLog("DCE: start opening camera: "+n));const o=await this.promisePlay;return ue._onLog&&ue._onLog("DCE: finish opening camera. Costs: "+(Date.now()-n)),this.playCallbackInfo=JSON.parse(JSON.stringify(o)),this._recordedStates.videoPlaying=!0,o}async resume(){this._assertOpen(),this._video&&(await this._video.play(),this._recordedStates.videoPlaying=!0),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&t.classList.contains("dce-opt-gotResolution")?this._optGotRsl=t:!this._btnClose&&t.classList.contains("dce-btn-close")?this._btnClose=t:!this._selMinLtr&&t.classList.contains("dlr-sel-minletter")?(this._selMinLtr=t,this._selMinLtr.options.length||(this._selMinLtr.innerHTML=[this._optGotMinLtr?"":'','','','','','','','','','',''].join(""),this._optGotMinLtr=this._optGotMinLtr||this._selMinLtr.options[0])):!this._optGotMinLtr&&t.classList.contains("dlr-opt-gotMinLtr")&&(this._optGotMinLtr=t);if(this.extraBindings&&this.extraBindings.length)for(let i of this.extraBindings)try{i(t)}catch(e){}}if(!this._video)throw this._unbindUI(),Error(`Can not find the video container element with class '${this.containerClassName}'`);this.singleFrameMode||this.videoSrc?(this.singleFrameMode&&(this._elContainer&&(this._elContainer.addEventListener("click",this._clickIptSingleFrameMode),this._elContainer.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._elContainer&&(["Android","HarmonyOS"].includes(Y.OS)?(this._elContainer.addEventListener("touchend",this._tapDoFocus),this._elContainer.addEventListener("touchmove",this._touchMoveEvent)):this._elContainer.addEventListener("click",this._tapDoFocus)),this._selCam&&(this._selCam.style.display="block",this._selCam.addEventListener("change",this._onCameraSelChange)),this._selRsl&&(this._selRsl.style.display="block",this._selRsl.addEventListener("change",this._onResolutionSelChange)),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._bgLoading&&(this._bgLoading.style.display="block")),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&(this._resizeObserver||(this._resizeObserver=new ResizeObserver((e=>{for(let t of e)t.target===this._elContainer&&this._updateLayers()}))),this._elContainer&&this._resizeObserver.observe(this._elContainer)),window.addEventListener("resize",this._updateLayers)}_unbindUI(){this.singleFrameMode?(this._elContainer&&(this._elContainer.removeEventListener("click",this._clickIptSingleFrameMode),this._elContainer.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._elContainer&&(this._elContainer.removeEventListener("click",this._tapDoFocus),this._elContainer.removeEventListener("touchend",this._tapDoFocus),this._elContainer.removeEventListener("touchmove",this._touchMoveEvent)),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._drawingLayersManager.setVisible(!1),this._hideOriginalImageCvs(),this._videoContainer&&this._videoContainer.remove(),this._video=null,this._videoContainer=null,this._elContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._updateLayers)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}async open(e){this.UIElement||await this.setUIElement(ue.defaultUIElementURL),this._bindUI(),e&&this.appendAndShowUI();let t=await this.play();this.bOpen=!0,this._focusParameters.fds=null,this._focusParameters.kTimeout=void 0,this._focusSupported=!0,this._tapFocusEnabled&&!this.singleFrameMode&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,this._focusParameters.fds||(this._focusSupported=!1,this._tapFocusEnabled=!1));const i=this.mapCameraEvents.get("cameraopen");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[i])}),0)}return t}close(e){if(!this._video)return;this.stop(),this._hideOriginalImage(!1),this.hideTip(),this._unbindUI(),e&&this.hideUI(),this.stopFetchingLoop(),this.bOpen=!1;const t=this.mapCameraEvents.get("cameraclose");for(let e of t){if(!e)continue;const t={width:0,height:0,deviceId:null};setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}stop(){this._video&&this._video.srcObject&&(ue._onLog&&ue._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((e=>{e.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(ue._onLog&&ue._onLog("DCE: ======stop existing video========"),this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0,this._reusedCvs&&this._reusedCvs.ctx2d&&this._reusedCvs.ctx2d.clearRect(0,0,this._reusedCvs.width,this._reusedCvs.height),this.forceLoseContext()}async getAllCameras(e=!0){let t=(await navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind));if(e&&t&&t.length&&!t[0].deviceId){let e=await navigator.mediaDevices.getUserMedia({video:!0});t=(await navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)),e.getTracks().forEach((e=>{e.stop()}))}const i=[],r=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&r.push(e);for(let e=0;e{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}if(r!==s.width||n!==s.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const e=this.mapCameraEvents.get("resolutionchange");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(s));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return s}getResolution(){if(this._bOpen)return[this._video.videoWidth,this._video.videoHeight];{let e=0,t=0;const i=this.videoSettings.video.width,r=this.videoSettings.video.height;return i&&(e=i.exact||i.ideal||i),r&&(t=r.exact||r.ideal||r),[e,t]}}async setResolution(e,t){let i,r;if(e instanceof Array?(i=e[0],r=e[1]):(i=e,r=t),this.videoSettings.video.width={ideal:i},this.videoSettings.video.height={ideal:r},!this._bOpen||this._video.paused)return null;const n=this._video.videoWidth,s=this._video.videoHeight,o=await this.play(null,i,r);if(n!==o.width||s!==o.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const e=this.mapCameraEvents.get("resolutionchange");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(o));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return o}async getResolutions(e){let t="";const i=(e,t)=>{const i=this._mapCameraResolutions.get(e);if(!i||!i.length)return!1;for(let e of i)if(e[0]===t.width&&e[1]===t.height)return!0;return!1},r=async(e,t,i)=>{const r={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(e){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const e=s[0].getSettings();o={width:e.width,height:e.height}}catch(e){const t=document.createElement("video");t.srcObject=n,o={width:t.videoWidth,height:t.videoHeight},t.srcObject=null}return s.forEach((e=>{e.stop()})),o};if(!this._bOpen){const n=this.videoSettings.video.deviceId;if(!n)return null;if(t=n.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:n.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!t)return null;let s=this._mapCameraResolutions.get(t);if(s&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),s=this._mapCameraResolutions.get(t);for(let e of this._predefinedResolutions){const n=await r(t,e.width,e.height);n&&!i(t,n)&&s.push([n.width,n.height])}return s}if(this._currentCamera){t=this._currentCamera.deviceId;let r=this._mapCameraResolutions.get(t);if(r&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),r=this._mapCameraResolutions.get(t);const n=this.getConstraints();for(let e of this._predefinedResolutions){await this._videoTrack.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const n=this._videoTrack.getSettings(),s={width:n.width,height:n.height};i(t,s)||r.push([s.width,s.height])}return await this._videoTrack.applyConstraints(n),r}return null}on(e,t){if(!t)return;const i=this.mapCameraEvents.get(e.toLowerCase());if(!i)throw new Error(`Event '${e}' does not exist.`);i.includes(t)||i.push(t)}off(e,t){const i=this.mapCameraEvents.get(e.toLowerCase());if(!i)throw new Error(`Event '${e}' does not exist.`);const r=i.indexOf(t);-1!==r&&i.splice(r,1)}offAll(e){if(e){if("string"==typeof e){const t=this.mapCameraEvents.get(e);t&&(t.length=0)}}else for(let e of this.mapCameraEvents.values())e&&(e.length=0)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(e){if(this.videoSettings=JSON.parse(JSON.stringify(e)),this._lastDeviceId=null,this._bOpen)return this.play()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return await this._videoTrack.applyConstraints(e)}async turnOnTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}async turnOffTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}async setColorTemperature(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let t=this.getCapabilities().colorTemperature;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({advanced:[{colorTemperature:e,whiteBalanceMode:"manual"}]})}getColorTemperature(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let t=this.getCapabilities().exposureCompensation;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({advanced:[{exposureCompensation:e}]})}getExposureCompensation(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setHardwareScale()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");if(!this._videoTrack)return;const t=this.getCapabilities().zoom;if(!t)throw new Error("Not supported.");return et.max&&(e=t.max),e=ce(e,t.min,t.step,t.max),await this._videoTrack.applyConstraints({advanced:[{zoom:e}]}),e}_getHardwareScale(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(e,t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setSoftwareScale()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");t&&this._setScaleCenter(t),this._softwareScale=e,this._scaleVideo(e,t)}_getSoftwareScale(){return this._softwareScale}_setScaleCenter(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setScaleCenter()' is unavailable in singleFrameMode.");if(!e||"string"!=typeof e.x||"string"!=typeof e.y)throw new Error("Invalid center.");const t=this._video.videoWidth,i=this._video.videoHeight;let r=0,n=0;if(e.x.endsWith("px"))r=parseFloat(e.x);else{if(!e.x.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(e.x)/100*t}if(e.y.endsWith("px"))n=parseFloat(e.y);else{if(!e.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(e.y)/100*i}if(NaN==r||NaN==n)throw new Error("Invalid scale center.");this._scaleCenter={x:r,y:n}}_resetScaleCenter(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_resetScaleCenter()' is unavailable in singleFrameMode.");const e=this._video.videoWidth,t=this._video.videoHeight;this._scaleCenter={x:e/2,y:t/2}}_isVideoCenter(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_isVideoCenter()' is unavailable in singleFrameMode.");return e&&e.x==this._video.videoWidth/2&&e.y==this._video.videoHeight/2}async _setZoom(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const t=await this._setHardwareScale(e);let i=this._getHardwareScale();1==i&&1!=t&&(i=t),e>i?this._setSoftwareScale(e/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(e)}catch(t){if("Not supported."!==(t.message||t))throw t;this._setSoftwareScale(e)}}async setZoom(e){if("number"!=typeof e&&"object"!=typeof e)throw new TypeError("Illegal type of argument.");if("number"==typeof e)return this._setZoom(e);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(e){if("number"!=typeof e.factor)throw new TypeError("Illegal type of 'factor'.");if(e.factor<1)throw new RangeError("Invalid value.");e.centerPoint?this._setScaleCenter(e.centerPoint):this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const t=await this._setHardwareScale(e.factor);let i=this._getHardwareScale();1==i&&1!=t&&(i=t),e.factor>i?this._setSoftwareScale(e.factor/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(e.factor)}catch(t){if("Not supported."!==(t.message||t))throw t;this._setSoftwareScale(e.factor)}}}getZoom(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?{factor:this._getHardwareScale()*this._softwareScale}:null}async resetZoom(){await this.setZoom({factor:1})}async setFrameRate(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let t=this.getCapabilities().frameRate;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:e})}getFrameRate(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(e,t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if("string"!=typeof e)throw Error("Invalid focus mode.");e=e.toLowerCase();const i=this.getCapabilities().focusMode,r=this.getCapabilities().focusDistance;if(!i)throw Error("Not supported.");if(!i.includes(e))throw Error("Unsupported mode.");if(t>=0){if(!r)throw Error("Manual focus unsupported.");return tr.max&&(t=r.max),t=ce(t,r.min,r.step,r.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:e,focusDistance:t}]})}return await this._videoTrack.applyConstraints({advanced:[{focusMode:e}]})}async setFocus(e,t){if("string"==typeof e)return this._setFocus(e,t);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if(!e)return;const i=this.getCapabilities(),r=i.focusMode,n=i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof e.mode)throw Error("Invalid focus mode.");const s=e.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"!==s)return this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:s}]});if(!n)throw Error("Manual focus unsupported.");if(e.hasOwnProperty("distance")){let t=e.distance;return tn.max&&(t=n.max),t=ce(t,n.min,n.step,n.max),this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:s,focusDistance:t}]})}if(!e.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const t=e.area.centerPoint;let i=e.area.width,r=e.area.height;if(!i||!r){const e=this._video.videoWidth,t=this._video.videoHeight;i||(i=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters._focusArea={centerPoint:{x:t.x,y:t.y},width:i,height:r},await this._setLocalFocus(t,i,r)}}getFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const e=this._videoTrack.getSettings().focusMode;return e?"continuous"===e?{mode:e}:{mode:e,distance:this._videoTrack.getSettings().focusDistance}:null}getFocusSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const e=this._videoTrack.getSettings(),t=e.focusMode;return t?"manual"===t?this._focusParameters._focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters._focusArea))}:{mode:"manual",distance:e.focusDistance}:{mode:t}:null}async _setFocusAndGetContract(e,t){const i=e=>{if(!this._bOpen||!this._videoTrack||this.video.paused||e.focusTaskId!=this._focusParameters.curFocusTaskId){this._bOpen&&this._videoTrack&&!this.video.paused||(this._focusParameters.isDoingFocus=0);const t=new Error(`Focus task ${e.focusTaskId} canceled.`);throw t.name="DeprecatedTaskError",t}1===this._focusParameters.isDoingFocus&&Date.now()-e.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;t=ce(t,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:"manual",focusDistance:t}]}),i(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/t),Math.abs(1/this._focusParameters.fds.max-1/t))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/t)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=t,await new Promise((e=>{setTimeout(e,r)})),i(e);let n=e.focusL-e.focusW/2,s=e.focusT-e.focusH/2,o=e.focusW,a=e.focusH;if(n>=this.video.videoWidth||s>=this.video.videoHeight)throw new Error("Invalid area.");n+o>this.video.videoWidth&&(o=this.video.videoWidth-n),s+a>this.video.videoHeight&&(a=this.video.videoHeight-s);const h=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:n,sy:s,sWidth:o,sHeight:a,dWidth:o,dHeight:a},null,{pixelFormat:le.RGBA});if(!h)return this._setFocusAndGetContract(e,t);const l=h.data;let c=0;for(let e=0,t=l.length-8;eo&&oc)return await this._doFocusDetail(e,s,o,r,n,l,c)}else{let a=await this._setFocusAndGetContract(e,l);if(o>a)return await this._doFocusDetail(e,s,o,r,n,l,a);if(o==a)return await this._doFocusDetail(e,s,o,l,a);let c=await this._setFocusAndGetContract(e,h);if(c>o&&o{try{(null==t||tthis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=ce(Math.sqrt(i*(t||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=ce(Math.sqrt((t||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=ce(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await this._setFocusAndGetContract(e,s),a=await this._setFocusAndGetContract(e,n),h=await this._setFocusAndGetContract(e,r);if(a>h&&ho&&a>o){let t=await this._setFocusAndGetContract(e,i);const n=await this._doFocusDetail(e,r,h,i,t,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const t=await this._doFocusDetail(e,r,h,s,o);return this._focusParameters.isDoingFocus=0,t}return d(e,t,i)}catch(e){if("DeprecatedTaskError"!==e.name)throw e}};return d(u,r,n)}async enableTapToFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'enableTapToFocus()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error("Video is not playing.");if(!this._focusSupported)throw new Error("Tapping to focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,this._tapFocusEnabled=!1,new Error("Tapping to focus unsupported.");this._tapFocusEnabled=!0}disableTapToFocus(){this._tapFocusEnabled=!1}isTapToFocusEnabled(){return this._tapFocusEnabled}_updateVideoContainerStyle(){if(!this._video)return;if(this.singleFrameMode)return;const e=this._getSoftwareScale(),t=this._videoContainer;if("contain"===this.videoFit&&e>1){const e=this._video.videoWidth,i=this._video.videoHeight,r=window.getComputedStyle(this._elContainer),n=parseFloat(r.width),s=parseFloat(r.height),o=e/i;if(n/sa?o/(i/e):s/(r/e));const c=l*(1-1/e)*(i/2-this._scaleCenter.x),u=l*(1-1/e)*(r/2-this._scaleCenter.y);this._video.style.transform=`translate(${c}px, ${u}px) scale(${e})`}this._updateVideoContainerStyle()}}getFrameSize(e,t,i,r){if(!e||!t)return null;let n,s,o,a,h=e,l=t;const c={regionLeft:0,regionTop:0,regionRight:h,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*h/100,c.regionTop=i.regionTop*l/100,c.regionRight=i.regionRight*h/100,c.regionBottom=i.regionBottom*l/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),n=Math.round(c.regionLeft),s=Math.round(c.regionTop),h=Math.round(c.regionRight-c.regionLeft),l=Math.round(c.regionBottom-c.regionTop)):(n=0,s=0,h=Math.round(h),l=Math.round(l));const u=Math.max(h,l);if(r&&r>0&&u>r){const e=r/u;h>l?(o=r,a=Math.round(l*e)):(o=Math.round(h*e),a=r)}else o=h,a=l;return o<=0||a<=0?null:{sx:n,sy:s,sWidth:h,sHeight:l,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoData()}getImage(){return this.getFrame()}_drawImage(e,t,i,r,n,s,o){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!i||!r)return null;if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let a;ue._onLog&&(a=Date.now(),ue._onLog("DCE: _drawImage(), START: "+a));let h=0,l=0,c=i,u=r,d=0,f=0,g=i,_=r;n&&(n.sx&&(h=Math.round(n.sx)),n.sy&&(l=Math.round(n.sy)),n.sWidth&&(c=Math.round(n.sWidth)),n.sHeight&&(u=Math.round(n.sHeight)),n.dx&&(d=Math.round(n.dx)),n.dy&&(f=Math.round(n.dy)),n.dWidth&&(g=Math.round(n.dWidth)),n.dHeight&&(_=Math.round(n.dHeight)));let p=le.RGBA;o&&o.pixelFormat&&(p=o.pixelFormat);const m=e;if(o&&o.bUseWebGL){ue._onLog&&ue._onLog("DCE: _drawImage() in WebGL."),(m.width{const t=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),e.STATIC_DRAW);const i=e.createBuffer();return e.bindBuffer(e.ARRAY_BUFFER,i),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),e.STATIC_DRAW),{positions:t,texCoords:i}},i=e=>{const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t},r=(e,t)=>{const i=e.createProgram();if(t.forEach((t=>e.attachShader(i,t))),e.linkProgram(i),!e.getProgramParameter(i,e.LINK_STATUS)){const t=new Error(`An error occured linking the program: ${e.getProgramInfoLog(i)}.`);throw t.name="WebGLError",t}return e.useProgram(i),i},n=(e,t,i)=>{const r=e.createShader(t);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){const t=new Error(`An error occured compiling the shader: ${e.getShaderInfoLog(r)}.`);throw t.name="WebGLError",t}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(e,[n(e,e.VERTEX_SHADER,s),n(e,e.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:h,attribLocations:{vertexPosition:e.getAttribLocation(h,"a_position"),texPosition:e.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:e.getUniformLocation(h,"u_image"),uColorFactor:e.getUniformLocation(h,"uColorFactor"),uMatrix:e.getUniformLocation(h,"u_matrix"),uTextureMatrix:e.getUniformLocation(h,"u_textureMatrix")}},this._webGLBuffers=t(e),this._webGLTexture=i(e),this.shaderPixelFormat=p}const n=(e,t,i)=>{e.bindBuffer(e.ARRAY_BUFFER,t),e.enableVertexAttribArray(i),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)},o=(e,t,i)=>{const r=e.RGBA,n=e.RGBA,s=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,r,n,s,i)},v=(e,t,s,o)=>{e.clearColor(0,0,0,1),e.clearDepth(1),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),n(e,s.positions,t.attribLocations.vertexPosition),n(e,s.texCoords,t.attribLocations.texPosition),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,o),e.uniform1i(t.uniformLocations.uSampler,0),e.uniform1f(t.uniformLocations.uColorFactor,[le.GREY,le.GREY32].includes(p)?1:0);let a,m,v=he.translate(he.identity(),-1,-1);v=he.scale(v,2,2),v=he.scale(v,1/e.canvas.width,1/e.canvas.height),a=he.translate(v,d,f),a=he.scale(a,g,_),e.uniformMatrix3fv(t.uniformLocations.uMatrix,!1,a),m=he.translate(he.identity(),h/i,l/r),m=he.scale(m,c/i,u/r),e.uniformMatrix3fv(t.uniformLocations.uTextureMatrix,!1,m),e.drawArrays(e.TRIANGLES,0,6)};let y;if(o(e,this._webGLTexture,t),v(e,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),s){if(s.lengtht||r.sy>i||r.sx+r.sWidth>t||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;ue._onLog&&(o=Date.now(),ue._onLog("DCE: _getImageData(), START: "+o));const a=Math.round(r.sx),h=Math.round(r.sy),l=Math.round(r.sWidth),c=Math.round(r.sHeight),u=Math.round(r.dWidth),d=Math.round(r.dHeight);let f=le.RGBA;s&&s.pixelFormat&&(f=s.pixelFormat);let g,_,p,m=this._bWebGLSupported;s&&0==s.bUseWebGL&&(m=!1),m?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),g=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),g=this._reusedCvs);try{if(m)if(ue._onLog&&ue._onLog("DCE: _getImageData() in WebGL."),n)if(f===le.GREY){if(p=new Uint8Array(u*d*4),_=this._drawImage(g,e,t,i,{sx:a,sy:h,sWidth:l,sHeight:c,dWidth:u,dHeight:d},p,{pixelFormat:f,bUseWebGL:m}),p=this._transformPixelFormat(p,_.pixelFormat,f),n){if(n.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");e=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return e}_fetchingLoop(e){if(this.isDisposed&&this.disposed)return;if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();const t=()=>{ue._onLog&&ue._onLog("DCE: start fetching a frame into buffer: "+Date.now());const e=this.getCurrentRegion();let t=this._getVideoData(null,{region:e});if(!t)return void ue._onLog;for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t);const i=this.mapCameraEvents.get("frameaddedtobuffer");for(let e of i)e&&setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this)}),0)},i=()=>{this.isDisposed&&this.disposed||(this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.isDisposed&&this.disposed||(this._bOpen&&this.isFetchingLoopStarted()?(t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,ue._onLog&&ue._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(ue._onLog&&ue._onLog("DCE: stop fetching loop: "+Date.now()),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1,this._recordedStates.fetchingLoopStart=!1)}getFrameFromBuffer(e){return this._frameQueue&&this._frameQueue.length?e?ee.getId()>=0))}getSelectedDrawingItems(){return this._drawingLayersManager.getSelectedDrawingItems()}createDrawingStyle(e){return this._drawingLayersManager.createDrawingStyle(e)}getDrawingStyle(e){return this._drawingLayersManager.getDrawingStyle(e)}getDrawingStyles(){return this._drawingLayersManager.getDrawingStyles()}updateDrawingStyle(e,t){return this._drawingLayersManager.updateDrawingStyle(e,t)}clearDrawingLayers(){const e=this.getDrawingLayers();for(let t of e)this.deleteDrawingLayer(t.getId())}showTip(e,t,i,r,n=3e3,s=!0){this._assertOpen(),this._tipArgs.x=e,this._tipArgs.y=t,this._tipArgs.width=i,this._tipArgs.autoShowSuggestedTip=!!s,this._drawingLayerOfTip||(this._drawingLayerOfTip=this._createDrawingLayer(-1)),this._tipStyleId||(this._tipStyleId=this.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip.clearDrawingItems();const o=new ne(r||"",e,t,i,this._tipStyleId);o._fabricObject.paddingTop=15,o._fabricObject.calcTextHeight=function(){for(var e=0,t=0,i=this._textLines.length;t0&&(this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}_hideTip(){this._drawingLayerOfTip&&(this.deleteDrawingLayer(this._drawingLayerOfTip.getId()),this._drawingLayerOfTip=null,this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId))}hideTip(){this._hideTip(),this._tipArgs.x=null,this._tipArgs.y=null,this._tipArgs.width=null,this._tipArgs.autoShowSuggestedTip=null}updateTipMessage(e){if(!this._drawingLayerOfTip)throw new Error("The Tip is not showing.");this._drawingLayerOfTip.getDrawingItems()[0].setAttribute("text",e),this._drawingLayerOfTip.renderAll(),this._tipArgs.duration>0&&(this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId),this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}suggestTip(e,t){this._tipArgs.autoShowSuggestedTip&&(this._drawingLayerOfTip?this.updateTipMessage(t):void 0!==this._tipArgs.x&&this.showTip(this._tipArgs.x,this._tipArgs.y,this._tipArgs.width,t,this._tipArgs.duration)),this.onTipSuggested&&setTimeout((()=>{this.isDisposed&&this.disposed||this.onTipSuggested.apply(this,[e,t])}),0)}_createControler(){if(this._controler||(this._controler=new ae(this)),this._controler)return this._controler}_destroyControler(){this._controler=null}setOriginalImage(e,t,i){if(!e||!t||!i)throw new Error("Invalid arguments");this._originalImageData={imageData:e,width:t,height:i};let r=this._cvsOriginalImage;r||(r=document.createElement("canvas"),r.style.position="absolute",r.style.width="100%",r.style.height="100%",r.style.left="0",r.style.top="0",r.style.backgroundColor="white",r.style.objectFit="contain",this._cvsOriginalImage=r),r.width===t&&r.height===i||(r.width=t,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),e instanceof Uint8Array||e instanceof Uint8ClampedArray?(e instanceof Uint8Array&&(e=new Uint8ClampedArray(e.buffer)),n.putImageData(new ImageData(e,t,i),0,0)):e instanceof HTMLCanvasElement&&n.drawImage(e,0,0),document.body.contains(r)&&""===r.style.display&&this._updateDrawingLayersSize({width:t,height:i,objectFit:"contain"})}getOriginalImage(){return this._originalImageData?Object.assign({},this._originalImageData):null}async deleteOriginalImage(){await this.hideOriginalImage(),this._cvsOriginalImage&&(this._cvsOriginalImage.remove(),this._cvsOriginalImage=null),this._originalImageData=null}_showOriginalImageCvs(){this._cvsOriginalImage&&"none"==this._cvsOriginalImage.style.display&&(this._cvsOriginalImage.style.display="")}_hideOriginalImageCvs(){this._cvsOriginalImage&&(this._cvsOriginalImage.style.display="none")}showOriginalImage(){if(!this._originalImageData)throw new Error("No original image is set.");const e=this._cvsOriginalImage;if(""===e.style.display&&document.body.contains(e))return;const{width:t,height:i}=this._originalImageData;if(this._updateDrawingLayersSize({width:t,height:i,objectFit:"contain"}),this._bOpen&&(this._video&&!this._video.paused&&this._video.pause(),this._bFetchingLoopStarted&&(this.stopFetchingLoop(),this._recordedStates.fetchingLoopStart=!0),this.ifShowScanRegionMask&&this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this.ifShowScanRegionLaser&&this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none"),this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none"),this._selCam&&(this._selCam.parentElement.style.display="none")),!document.body.contains(e))if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e)}this._showOriginalImageCvs()}async _hideOriginalImage(e){this._originalImageData&&this._cvsOriginalImage&&"none"!==this._cvsOriginalImage.style.display&&(this._updateDrawingLayersSize(),this._bOpen&&e&&(this._video&&this._recordedStates.videoPlaying&&await this.play(null,null,null,{notTriggerSingleFrameClick:!0}),this._recordedStates.fetchingLoopStart&&!this.singleFrameMode&&this.startFetchingLoop(),this.ifShowScanRegionMask&&this._cvsScanRegion&&this._recordedStates.maskShow&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this._divScanLight&&this._recordedStates.laserShow&&this.showScanRegionLaser(),this._cvsViewDecorator&&this._recordedStates.decoratorShow&&this.showViewDecorator(),this._scanRegionOverlayContainer&&this._recordedStates.overlayShow&&this.showScanRegionOverlays()),this._selCam&&(this._selCam.parentElement.style.display=""),this._hideOriginalImageCvs())}async hideOriginalImage(){return this._hideOriginalImage(!0)}dispose(e){this.UIElement&&(this._uiOriginalState&&this._uiOriginalState.inDom?this.UIElement.style.display=this._uiOriginalState.display:this.UIElement.style.display="none"),this.clearDrawingLayers(),this.close(),this.forceLoseContext(),this.setViewDecorator(null,null),this._scanRegionOverlayContainer&&this._scanRegionOverlayContainer.remove(),this._arrScanRegionOverlays.length=0,e&&this.UIElement&&this.UIElement.remove(),this.__proto__=null;for(let e in this)delete this[e];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"isDisposed",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}ue._jsVersion="3.3.1",ue._jsEditVersion="20230217",ue._version="JS "+ue._jsVersion+"."+ue._jsEditVersion,ue.browserInfo=Y,ue._hasEngineResourceLoaded=!1,ue._engineResourcePath=J,ue._defaultUIElementURL="@engineResourcePath/dce.ui.html";const de={DT_Arc:class extends q{constructor(e,t,i,r,n,s){super(new j.Circle({left:e,top:t,radius:i,startAngle:r,endAngle:n}),s),this._mediaType="arc"}},DT_Polygon:ie,DT_Rect:class extends q{constructor(e,t,i,r,n){super(new j.Rect({left:e,top:t,width:i,height:r}),n)}},DT_Image:class extends q{constructor(e,t,i,r){super(new j.Image(e,{left:t,top:i}),r),this.image=e}_extendSet(e,t){if("image"===e){if(t instanceof HTMLImageElement)return this._fabricObject.setElement(t),this.image=t,!0;if(t instanceof HTMLCanvasElement){const e=new Image;return e.src=t.toDataURL(),this._fabricObject.setElement(e),this.image=t,!0}throw new Error("Unsupported value.")}}_extendGet(e){if("image"===e)return this.image}},DT_Text:ne,DT_Line:class extends ie{constructor(e,t,i){super([e,t],i),this._mediaType="line"}_extendSet(e,t){if("startPoint"===e||"endPoint"===e){t="startPoint"===e?[t,this.get("endPoint")]:[this.get("startPoint"),t];const i=this._fabricObject;if(i.group){const e=i.group;i.points=t.map((t=>({x:t.x-e.left-e.width/2,y:t.y-e.top-e.height/2}))),e.addWithUpdate()}else i.points=t;const r=i.points.length-1;return i.controls=i.points.reduce((function(e,t,i){return e["p"+i]=new j.Control({positionHandler:Q,actionHandler:te(i>0?i-1:r,ee),actionName:"modifyPolygon",pointIndex:i}),e}),{}),i._setPositionDimensions({}),!0}}_extendGet(e){if("startPoint"===e||"endPoint"===e){const t=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let e in i.oCoords)t.push({x:i.oCoords[e].x,y:i.oCoords[e].y});else for(let e of i.points){let r=e.x-i.pathOffset.x,n=e.y-i.pathOffset.y;const s=j.util.transformPoint({x:r,y:n},i.calcTransformMatrix());t.push({x:s.x,y:s.y})}return"startPoint"===e?t[0]:t[1]}}},DT_Group:class extends q{constructor(e){super(new j.Group(e.map((e=>e._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.styleSelector="selected";const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.styleSelector="default";const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)}))}getChildItems(){return this._fabricObject._objects.map((e=>e.getDrawingItem()))}addChildItem(e){if(!e||!e.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"add"):this._fabricObject.addWithUpdate(e._getFabricObject())}removeChildItem(e){e&&e.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"remove"):this._fabricObject.removeWithUpdate(e._getFabricObject()))}}};function fe(e,t,i){return(i.x-e.x)*(t.y-e.y)==(t.x-e.x)*(i.y-e.y)&&Math.min(e.x,t.x)<=i.x&&i.x<=Math.max(e.x,t.x)&&Math.min(e.y,t.y)<=i.y&&i.y<=Math.max(e.y,t.y)}function ge(e){return Math.abs(e)<1e-6?0:e<0?-1:1}function _e(e,t,i,r){let n=e[0]*(i[1]-t[1])+t[0]*(e[1]-i[1])+i[0]*(t[1]-e[1]),s=e[0]*(r[1]-t[1])+t[0]*(e[1]-r[1])+r[0]*(t[1]-e[1]);return!((n^s)>=0&&0!==n&&0!==s)&&(n=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),s=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),!((n^s)>=0&&0!==n&&0!==s))}class pe extends L{constructor(){super(),this._barcodeFillStyle="rgba(254,180,32,0.3)",this._barcodeStrokeStyle="rgba(254,180,32,0.9)",this._barcodeLineWidth=1,this._barcodeFillStyleBeforeVerification="rgba(248,252,0,0.2)",this._barcodeStrokeStyleBeforeVerification="transparent",this._barcodeLineWidthBeforeVerification=2,this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${ue.getVersion()})`}static _fireHTTPSWarnning(){pe.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{pe.onWarning&&pe.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return ue.testCameraAccess()}_fireResolutionWarning(){if(!this.singleFrameMode&&this.onWarning&&this.dce.isOpen()){const e=this.dce.getConstraints();e&&e.width<1280&&e.height<720&&setTimeout((()=>{this.onWarning&&this.onWarning({id:3,message:"Camera resolution too low, please use a higher resolution (720P or better)."})}),0)}}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}get video(){return this.dce&&this.dce.video}set videoSrc(e){this.dce&&(this.dce.videoSrc=e)}get videoSrc(){return this.dce&&this.dce.videoSrc}set onTipSuggested(e){this.dce&&(this.dce.onTipSuggested=e)}get onTipSuggested(){return this.dce&&this.dce.onTipSuggested}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set barcodeFillStyle(e){this._barcodeFillStyle=e,this.dce&&this.dce.updateDrawingStyle(3,{fillStyle:e})}get barcodeFillStyle(){return this._barcodeFillStyle}set barcodeStrokeStyle(e){this._barcodeStrokeStyle=e,this.dce&&this.dce.updateDrawingStyle(3,{strokeStyle:e})}get barcodeStrokeStyle(){return this._barcodeStrokeStyle}set barcodeLineWidth(e){this._barcodeLineWidth=e,this.dce&&this.dce.updateDrawingStyle(3,{lineWidth:e})}get barcodeLineWidth(){return this._barcodeLineWidth}set barcodeFillStyleBeforeVerification(e){this._barcodeFillStyleBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{fillStyle:e})}get barcodeFillStyleBeforeVerification(){return this._barcodeFillStyleBeforeVerification}set barcodeStrokeStyleBeforeVerification(e){this._barcodeStrokeStyleBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{strokeStyle:e})}get barcodeStrokeStyleBeforeVerification(){return this._barcodeStrokeStyleBeforeVerification}set barcodeLineWidthBeforeVerification(e){this._barcodeLineWidthBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{lineWidth:e})}get barcodeLineWidthBeforeVerification(){return this._barcodeLineWidthBeforeVerification}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.framePixelFormat=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(L._onLog&&L._onLog("createDCEInstance()"),ue.defaultUIElementURL=null,this.dce=await ue.createInstance(),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=de,["iPhone","iPad","Android","HarmonyOS"].includes(L.browserInfo.OS)||this.dce.setResolution(1920,1080),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"}),this.barcodeLineWidth=this._barcodeLineWidth,this.dce.on("cameraChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async t=>{if(!t)return;if(!t.data)return;let i;this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:r,sx:n,sy:s,width:o,height:a,stride:h,pixelFormat:l,timeStamp:c,_sWidth:u,_sHeight:d}=t,f={timeStamp:c};if("grey"===l)i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_GrayScaled,0,f);else if("rgba"===l)i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_ABGR_8888,0,f);else{if("bgra"!==l)throw new Error(`Pixel format '${l}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_ARGB_8888,0,f)}if(await this.clearMapDecodeRecord(),L.recalculateResultLocation(i,n,s,u,d,o,a),this._drawResults(i),this.onFrameRead&&this.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(i);this.onFrameRead(e)}if(this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of i)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))})))}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new pe;t._instanceID=await pe.createInstanceInWorker(!0),await t.createDCEInstance(),"string"==typeof e&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return await t.dce.setUIElement(pe.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),pe._fireHTTPSWarnning(),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const i=this.dce._getVideoData(null,{region:t});return this._decode_DCEFrame(i)}async updateRuntimeSettings(t){let i;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=0,i.localizationModes=[2,0,0,0,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=9}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=512,i.deblurLevel=3,i.localizationModes=[2,16,0,0,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=9,i.timeout=1e5}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=512,i.deblurLevel=5,i.scaleDownThreshold=1e5,i.localizationModes=[2,16,4,8,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=9,i.timeout=1e5}else if("single"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region)}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=0,i.deblurLevel=7,i.scaleDownThreshold=1e5,i.localizationModes=[2,8,0,0,0,0,0,0],i.minResultConfidence=0,i.barcodeZoneMinDistanceToImageBorders=9,i.timeout=1e5}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=0,i.scaleDownThreshold=1e5,i.localizationModes=[2,8,0,0,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=9,i.timeout=1e5}else i=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(i=JSON.parse(JSON.stringify(t)),i.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(i.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!L._bUseFullFeature){if(0!=(i.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=i.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=i.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=i.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(i=>{if(i.success){try{this._handleRetJsonString(i.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(i)}})})),"string"==typeof t&&["speed","balance","coverage","dense","distance"].includes(t)&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","1"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","0"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","0"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){const t=await this.dce.selectCamera(e);return this._fireResolutionWarning(),t}getResolution(){return this.dce.getResolution()}async setResolution(e,t){const i=await this.dce.setResolution(e,t);return this._fireResolutionWarning(),i}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}set ifSaveLastUsedCamera(e){this.dce&&(this.dce.ifSaveLastUsedCamera=e)}get ifSaveLastUsedCamera(){return this.dce&&this.dce.ifSaveLastUsedCamera}set ifSkipCameraInspection(e){this.dce&&(this.dce.ifSkipCameraInspection=e)}get ifSkipCameraInspection(){return this.dce&&this.dce.ifSkipCameraInspection}stop(){this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.dce.stop(),this.dce.ifShowScanRegionLaser=!1,this.dce.hideViewDecorator(),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this.dce.pause()}async play(e,t,i){this.dce.ifShowScanRegionLaser=!0;const r=await this.dce.play(e,t,i);return this._fireResolutionWarning(),r}pauseScan(e){this._assertOpen(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}getColorTemperature(){return this.dce.getColorTemperature()}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}getExposureCompensation(){return this.dce.getExposureCompensation()}async setZoom(e){return this.dce.setZoom(e)}getZoomSettings(){return this.dce.getZoomSettings()}resetZoom(){return this.dce.resetZoom()}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}getFocusSettings(){return this.dce.getFocusSettings()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(!this.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return L._onLog&&L._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));L._onLog&&L._onLog("======= once read ======="),L._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return L._onLog&&L._onLog("Get invalid frame."),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{t._bUseWebGL||"grey"!==t.pixelFormat||(this.dce.framePixelFormat="rgba");let i=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:r,sx:n,sy:s,width:o,height:a,stride:h,pixelFormat:l,timeStamp:c,_sWidth:u,_sHeight:d}=t,f={timeStamp:c};if("grey"===l)i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_GrayScaled,0,f);else if("rgba"===l)i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_ABGR_8888,0,f);else{if("bgra"!==l)throw new Error(`Pixel format '${l}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_ARGB_8888,0,f)}if(L.recalculateResultLocation(i,n,s,u,d,o,a),0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(i),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration)),this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan&&(this.autoZoom||this.autoFocus||this.autoSuggestTip))if(i.length)this.autoZoomInFrameArray.length=0,this.autoZoomOutFrameCount=0,this.frameArrayInIdealZoom.length=0,this.suggestTipFrameArray.length=0,this.autoZoom&&this.autoFocus&&(this.nextActionInIdealZoom="focus"),this.autoFocusFrameArray.length=0,this.noIntermediateResultsCount=0;else{const t=await this.getIntermediateResults(),i=(e,t,i,r,n,s,o)=>{let a=s/r,h=o/n;e.x1=e.x1/a+t,e.x2=e.x2/a+t,e.x3=e.x3/a+t,e.x4=e.x4/a+t,e.y1=e.y1/h+i,e.y2=e.y2/h+i,e.y3=e.y3/h+i,e.y4=e.y4/h+i},r=t=>{if(!t)return null;const r={};let h,l,c,f,g;{const e=this.video.videoWidth*(1-this.autoZoomDetectionArea)/2,t=this.video.videoWidth*(1+this.autoZoomDetectionArea)/2,i=t,r=e,n=this.video.videoHeight*(1-this.autoZoomDetectionArea)/2,s=n,o=this.video.videoHeight*(1+this.autoZoomDetectionArea)/2;g={x1:e,x2:t,x3:i,x4:r,y1:n,y2:s,y3:o,y4:o}}const _=(e,t)=>{const i=(e,t)=>{if(!e&&!t)throw new Error("Invalid arguments.");return function(e,t,i){let r=!1;const n=e.length;if(n<=2)return!1;for(let s=0;s0!=ge(a.y-i)>0&&ge(t-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}([{x:t.x1,y:t.y1},{x:t.x2,y:t.y2},{x:t.x3,y:t.y3},{x:t.x4,y:t.y4}],e.x,e.y)},r=(e,t)=>!!(_e([e[0],e[1]],[e[2],e[3]],[t.x1,t.y1],[t.x2,t.y2])||_e([e[0],e[1]],[e[2],e[3]],[t.x2,t.y2],[t.x3,t.y3])||_e([e[0],e[1]],[e[2],e[3]],[t.x3,t.y3],[t.x4,t.y4])||_e([e[0],e[1]],[e[2],e[3]],[t.x4,t.y4],[t.x1,t.y1]));return!!(i({x:e.x1,y:e.y1},t)||i({x:e.x2,y:e.y2},t)||i({x:e.x3,y:e.y3},t)||i({x:e.x4,y:e.y4},t))||(!!(i({x:t.x1,y:t.y1},e)||i({x:t.x2,y:t.y2},e)||i({x:t.x3,y:t.y3},e)||i({x:t.x4,y:t.y4},e))||!!(r([t.x1,t.y1,t.x2,t.y2],e)||r([t.x2,t.y2,t.x3,t.y3],e)||r([t.x3,t.y3,t.x4,t.y4],e)||r([t.x4,t.y4,t.x1,t.y1],e)))},p=[];for(let r of t){if(r.resultType!==e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE)continue;const t=r.scaleDownRatio;for(let e of r.results){if(!e)continue;const r={x1:e.x1=e.x1*t,x2:e.x2=e.x2*t,x3:e.x3=e.x3*t,x4:e.x4=e.x4*t,y1:e.y1=e.y1*t,y2:e.y2=e.y2*t,y3:e.y4=e.y3*t,y4:e.y4=e.y4*t};i(r,n,s,u,d,o,a),_(g,r)&&p.push(e)}}const m=(t=>{if(!t||!t.length)return null;const i=e=>{const t=(e.x1+e.x2+e.x3+e.x4)/4,i=(e.y1+e.y2+e.y3+e.y4)/4;return(t-o/2)*(t-o/2)+(i-a/2)*(i-a/2)};let r,n=t.filter((t=>t.barcodeFormat==e.EnumBarcodeFormat.BF_QR_CODE||t.barcodeFormat==e.EnumBarcodeFormat.BF_DATAMATRIX));if(n.length||(n=t.filter((t=>t.barcodeFormat==e.EnumBarcodeFormat.BF_ONED)),n.length||(n=t)),!n.length)return null;r=n[0];let s=i(r);if(1!=n.length)for(let e=1;e1.1*r.confidence?(r=n[e],s=t):n[e].confidence>.9*r.confidence&&t!0===e)).length>=this.suggestTipFrameLimit[1]){this.suggestTipFrameArray.length=0;const e=h.x3-h.x1,t=h.y3-h.y1;h.result.moduleSizet?e>o*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):e>.6*o&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."):e<=t&&(t>a*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):t>.6*a&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."))}if(this.autoZoom){const e=this.autoZoomIdealArea[1];let t=(1-this.autoZoomTargetBorder)/2;const r=h.x1/u,l=(u-h.x3)/u,c=h.y1/d,f=(d-h.y3)/d;if(r>e&&l>e&&c>e&&f>e&&h.result.moduleSize{}))),this.autoZoomInFrameArray.filter((e=>!0===e)).length>=this.autoZoomInFrameLimit[1]){this.autoZoomInFrameArray.length=0;const e=[(.5-t)/(.5-r),(.5-t)/(.5-l),(.5-t)/(.5-c),(.5-t)/(.5-f)].filter((e=>e>0)),i=Math.min(...e,this.autoZoomInIdealModuleSize/h.result.moduleSize),n=this.dce.getZoomSettings().factor;let s=Math.max(Math.pow(n*i,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);s=Math.min(s,i);const o=n*s;await this.setZoom({factor:o}),this.dce.clearFrameBuffer()}}else if(this.autoZoomInFrameArray.length=0,this.frameArrayInIdealZoom.push(!0),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.frameArrayInIdealZoom.filter((e=>!0===e)).length>=this.frameLimitInIdealZoom[1])if(this.frameArrayInIdealZoom.length=0,"focus"===this.nextActionInIdealZoom&&this.autoFocus){i(h,n,s,u,d,o,a);try{await this.setFocus({mode:"manual",area:{centerPoint:{x:(h.x1+h.x3)/2+"px",y:(h.y1+h.y3)/2+"px"},width:h.x3-h.x1+"px",height:h.y3-h.y1+"px"}})}catch(e){}this.dce.clearFrameBuffer(),this.nextActionInIdealZoom="zoomOut"}else{if("zoomOut"!==this.nextActionInIdealZoom&&this.autoFocus)throw new Error("Invalid action.");if(this.enableZoomOutInIdealZoom){t=this.autoZoomIdealArea[1]+this.autoZoomOutStepRate_2;const e=[(.5-t)/(.5-r),(.5-t)/(.5-l),(.5-t)/(.5-c),(.5-t)/(.5-f)].filter((e=>e>0));let i=Math.min(...e)*this.dce.getZoomSettings().factor;await this.setZoom({factor:i}),this.dce.clearFrameBuffer(),this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((e=>{})))}}}else if(this.autoFocus&&(this.autoFocusFrameArray.push(!0),this.autoFocusFrameArray.splice(0,this.autoFocusFrameArray.length-this.autoFocusFrameLimit[0]),this.autoFocusFrameArray.filter((e=>!0===e)).length>=this.autoFocusFrameLimit[1])){this.autoFocusFrameArray.length=0;try{i(h,n,s,u,d,o,a),await this.setFocus({mode:"manual",area:{centerPoint:{x:(h.x1+h.x3)/2+"px",y:(h.y1+h.y3)/2+"px"},width:h.x3-h.x1+"px",height:h.y3-h.y1+"px"}})}catch(e){}this.dce.clearFrameBuffer()}}else if(this.noIntermediateResultsCount++,this.suggestTipFrameArray.push(!1),this.autoZoom){if(this.autoZoomInFrameArray.push(!1),this.autoZoomInFrameArray.splice(0,this.autoZoomInFrameArray.length-this.autoZoomInFrameLimit[0]),this.autoZoomOutFrameCount++,this.frameArrayInIdealZoom.push(!1),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.autoZoomOutFrameCount>=this.autoZoomOutFrameLimit){this.autoZoomOutFrameCount=0;const e=this.getZoomSettings().factor;if(e>this.autoZoomOutMinValue){const t=Math.max((e-1)*this.autoZoomOutStepRate,this.autoZoomOutMinStep),i=Math.max(e-t,this.autoZoomOutMinValue);await this.setZoom({factor:i}),this.dce.clearFrameBuffer()}}this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((e=>{})))}else this.autoFocus&&(this.autoFocusFrameArray.length=0,this.setFocus({mode:"continuous"}).catch((e=>{})))}return i})().then((e=>{if(L._onLog&&L._onLog(e),this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;const r=()=>{let r=0;if(this.region instanceof Array){let n=0,s=0;n=i+1>=this.region.length?0:i+1,s=n+1>=this.region.length?0:n+1,r=e[n]&&e[n].length&&t[s]&&t[s].length?Math.min(...e[n])-Math.max(...t[s]):0}else if(t&&t.length){let i=Math.min(...e),n=Math.max(...t);i&&n&&(r=i-n)}else r=0;return r>0?r:0};(()=>{if(this.region instanceof Array){for(e[i]&&e[i]instanceof Array||(e[i]=[]);e[i].length>=5;)e[i].shift();e[i].push(this._lastInnerDecodeDuration)}else{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=r()+this.intervalTime,L._onLog&&L._onLog("Next fetching frame loop interval: "+this._intervalGetVideoFrame)}if(this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onFrameRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){L._onLog&&L._onLog("Get frame in parallel.");let t=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,t||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;e=this.dce.getFrameFromBuffer();const i=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};i(e)}else L._onLog&&L._onLog("Get frame in serial."),this.dce.stopFetchingLoop(),e=this.dce.getFrame();return e}async open(){this._bindUI();const e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}close(){this.dce.close(),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}hide(){this.dce.close(!0),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}showTip(e,t,i,r,n=3e3,s=!0){this.dce&&this.dce.showTip(e,t,i,r,n,s)}hideTip(){this.dce&&this.dce.hideTip()}updateTipMessage(e){this.dce&&this.dce.updateTipMessage(e)}async enableTapToFocus(){this.dce&&this.dce.enableTapToFocus()}disableTapToFocus(){this.dce&&this.dce.disableTapToFocus()}isTapToFocusEnabled(){return this.dce.isTapToFocusEnabled()}destroyContext(){this.close(),this.dce&&this.dce.dispose(!1),this.bDestroyed||super.destroyContext()}}var me,ve,ye,Se,Ce,be,we,xe,Te,Ee,Ie,Ae,Oe,Re,De,Me,Fe,Le,Pe,ke,Be,Ne,je,Ve,Ue,Ge;e.EnumBarcodeColourMode=void 0,(me=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[me.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",me[me.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",me[me.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",me[me.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",me[me.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",me[me.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",me[me.BICM_SKIP=0]="BICM_SKIP",me[me.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(ve=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[ve.BCM_AUTO=1]="BCM_AUTO",ve[ve.BCM_GENERAL=2]="BCM_GENERAL",ve[ve.BCM_SKIP=0]="BCM_SKIP",ve[ve.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(ye=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[ye.BF2_NULL=0]="BF2_NULL",ye[ye.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",ye[ye.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",ye[ye.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",ye[ye.BF2_POSTNET=2097152]="BF2_POSTNET",ye[ye.BF2_PLANET=4194304]="BF2_PLANET",ye[ye.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",ye[ye.BF2_RM4SCC=16777216]="BF2_RM4SCC",ye[ye.BF2_DOTCODE=2]="BF2_DOTCODE",ye[ye.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",ye[ye.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",ye[ye.BF2_PHARMACODE=12]="BF2_PHARMACODE",ye[ye.BF2_ALL=4294967295]="BF2_ALL",e.EnumBinarizationMode=void 0,(Se=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[Se.BM_AUTO=1]="BM_AUTO",Se[Se.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",Se[Se.BM_SKIP=0]="BM_SKIP",Se[Se.BM_THRESHOLD=4]="BM_THRESHOLD",Se[Se.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(Ce=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[Ce.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(be=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[be.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(we=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[we.CCM_AUTO=1]="CCM_AUTO",we[we.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",we[we.CCM_SKIP=0]="CCM_SKIP",we[we.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(xe=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[xe.CICM_GENERAL=1]="CICM_GENERAL",xe[xe.CICM_SKIP=0]="CICM_SKIP",xe[xe.CICM_REV=2147483648]="CICM_REV",e.EnumConflictMode=void 0,(Te=e.EnumConflictMode||(e.EnumConflictMode={}))[Te.CM_IGNORE=1]="CM_IGNORE",Te[Te.CM_OVERWRITE=2]="CM_OVERWRITE",e.EnumDeblurMode=void 0,(Ee=e.EnumDeblurMode||(e.EnumDeblurMode={}))[Ee.DM_SKIP=0]="DM_SKIP",Ee[Ee.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",Ee[Ee.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",Ee[Ee.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",Ee[Ee.DM_SMOOTHING=8]="DM_SMOOTHING",Ee[Ee.DM_MORPHING=16]="DM_MORPHING",Ee[Ee.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",Ee[Ee.DM_SHARPENING=64]="DM_SHARPENING",Ee[Ee.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",Ee[Ee.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(Ie=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[Ie.DRM_AUTO=1]="DRM_AUTO",Ie[Ie.DRM_GENERAL=2]="DRM_GENERAL",Ie[Ie.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",Ie[Ie.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",Ie[Ie.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",Ie[Ie.DRM_SKIP=0]="DRM_SKIP",Ie[Ie.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(Ae=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[Ae.DPMCRM_AUTO=1]="DPMCRM_AUTO",Ae[Ae.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",Ae[Ae.DPMCRM_SKIP=0]="DPMCRM_SKIP",Ae[Ae.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(Oe=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[Oe.GTM_INVERTED=1]="GTM_INVERTED",Oe[Oe.GTM_ORIGINAL=2]="GTM_ORIGINAL",Oe[Oe.GTM_SKIP=0]="GTM_SKIP",Oe[Oe.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(Re=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[Re.IPM_AUTO=1]="IPM_AUTO",Re[Re.IPM_GENERAL=2]="IPM_GENERAL",Re[Re.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",Re[Re.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",Re[Re.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",Re[Re.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",Re[Re.IPM_SKIP=0]="IPM_SKIP",Re[Re.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(De=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[De.IRSM_MEMORY=1]="IRSM_MEMORY",De[De.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",De[De.IRSM_BOTH=4]="IRSM_BOTH",e.EnumLocalizationMode=void 0,(Me=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[Me.LM_SKIP=0]="LM_SKIP",Me[Me.LM_AUTO=1]="LM_AUTO",Me[Me.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",Me[Me.LM_LINES=8]="LM_LINES",Me[Me.LM_STATISTICS=4]="LM_STATISTICS",Me[Me.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",Me[Me.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",Me[Me.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",Me[Me.LM_CENTRE=128]="LM_CENTRE",Me[Me.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",Me[Me.LM_REV=2147483648]="LM_REV",e.EnumPDFReadingMode=void 0,(Fe=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[Fe.PDFRM_RASTER=1]="PDFRM_RASTER",Fe[Fe.PDFRM_AUTO=2]="PDFRM_AUTO",Fe[Fe.PDFRM_VECTOR=4]="PDFRM_VECTOR",Fe[Fe.PDFRM_REV=2147483648]="PDFRM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,(Le=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[Le.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",Le[Le.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",Le[Le.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",Le[Le.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,(Pe=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[Pe.RPM_AUTO=1]="RPM_AUTO",Pe[Pe.RPM_GENERAL=2]="RPM_GENERAL",Pe[Pe.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",Pe[Pe.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",Pe[Pe.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",Pe[Pe.RPM_SKIP=0]="RPM_SKIP",Pe[Pe.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(ke=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[ke.RCT_PIXEL=1]="RCT_PIXEL",ke[ke.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,(Be=e.EnumResultType||(e.EnumResultType={}))[Be.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",Be[Be.RT_RAW_TEXT=1]="RT_RAW_TEXT",Be[Be.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",Be[Be.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(Ne=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[Ne.SUM_AUTO=1]="SUM_AUTO",Ne[Ne.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",Ne[Ne.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",Ne[Ne.SUM_SKIP=0]="SUM_SKIP",Ne[Ne.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(je=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[je.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",je[je.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",je[je.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",je[je.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",je[je.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",je[je.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(Ve=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[Ve.TFM_AUTO=1]="TFM_AUTO",Ve[Ve.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",Ve[Ve.TFM_SKIP=0]="TFM_SKIP",Ve[Ve.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(Ue=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[Ue.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",Ue[Ue.TROM_POSITION=2]="TROM_POSITION",Ue[Ue.TROM_FORMAT=4]="TROM_FORMAT",Ue[Ue.TROM_SKIP=0]="TROM_SKIP",Ue[Ue.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(Ge=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[Ge.TDM_AUTO=1]="TDM_AUTO",Ge[Ge.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",Ge[Ge.TDM_SKIP=0]="TDM_SKIP",Ge[Ge.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=L,e.BarcodeScanner=pe,Object.defineProperty(e,"__esModule",{value:!0})})); + */const V="undefined"==typeof self;let U,G,W,H,Y;if("undefined"!=typeof navigator&&(U=navigator,G=U.userAgent,W=U.platform,H=U.mediaDevices),!V){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:U.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:W,search:"Win"},Mac:{str:W},Linux:{str:W}};let i="unknownBrowser",r=0,n="unknownOS";for(let t in e){const n=e[t]||{};let s=n.str||G,o=n.search||t,a=n.verStr||G,h=n.verSearch||t;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=t;for(let e of h){let t=a.indexOf(e);if(-1!=t){r=parseFloat(a.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let r=i.str||G,s=i.search||e;if(-1!=r.indexOf(s)){n=e;break}}"Linux"==n&&-1!=G.indexOf("Windows NT")&&(n="HarmonyOS"),Y={browser:i,version:r,OS:n}}V&&(Y={browser:"ssr",version:0,OS:"ssr"});const X="undefined"!=typeof WebAssembly&&G&&!(/Safari/.test(G)&&!/Chrome/.test(G)&&/\(.+\s11_2_([2-6]).*\)/.test(G)),z=!("undefined"==typeof Worker),Z=!(!H||!H.getUserMedia),K=async()=>{let e=!1;if(Z)try{(await H.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===Y.browser&&Y.version>66||"Safari"===Y.browser&&Y.version>13||"OPR"===Y.browser&&Y.version>43||"Edge"===Y.browser&&Y.version;const J=(()=>{if(!V&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})();class q{constructor(e,t){this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,this._setFabricObject(e),this._mediaType=e.type,this.styleSelector="default",this.styleId=t}get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}_setFabricObject(e){this._fabricObject=e,this._fabricObject.on("selected",(()=>{this.styleSelector="selected"})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.styleSelector="selected":this.styleSelector="default","textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),e.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}_on(e,t){if(!t)return;const i=e.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${e}' does not exist.`);let n=r.get(t);n||(n=e=>{const i=e.e;if(!i)return void(t&&t.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let e,t,n,s;const o=i.target.getBoundingClientRect();e=o.left,t=o.top,n=e+window.scrollX,s=t+window.scrollY;const a=this._drawingLayer.fabricCanvas.lowerCanvasEl.width,h=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,l=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),c=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),u=l/c,d=a/h,f=this._drawingLayer._getObjectFit();let g,_,p,m,v=1;if("contain"===f)u0?i-1:r,ee),actionName:"modifyPolygon",pointIndex:i}),e}),{})}_extendSet(e,t){if("vertices"===e){const e=this._fabricObject;if(e.group){const i=e.group;e.points=t.map((e=>({x:e.x-i.left-i.width/2,y:e.y-i.top-i.height/2}))),i.addWithUpdate()}else e.points=t;const i=e.points.length-1;return e.controls=e.points.reduce((function(e,t,r){return e["p"+r]=new j.Control({positionHandler:Q,actionHandler:te(r>0?r-1:i,ee),actionName:"modifyPolygon",pointIndex:r}),e}),{}),e._setPositionDimensions({}),!0}}_extendGet(e){if("vertices"===e){const e=[],t=this._fabricObject;if(t.selectable&&!t.group)for(let i in t.oCoords)e.push({x:t.oCoords[i].x,y:t.oCoords[i].y});else for(let i of t.points){let r=i.x-t.pathOffset.x,n=i.y-t.pathOffset.y;const s=j.util.transformPoint({x:r,y:n},t.calcTransformMatrix());e.push({x:s.x,y:s.y})}return e}}}const re=e=>{let t=(e=>e.split("\n").map((e=>e.split("\t"))))(e);return(e=>{for(let t=0;;t++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=e[r].length-1)continue;let n=" ".repeat(i+2-e[r][t].length);e[r][t]=e[r][t].concat(n)}}})(t),(e=>{let t="";for(let i=0;im?(g=d,_=d/p,{x:n.x*i.width,y:(n.y-(f-_)/2)*i.width}):(g=f*p,_=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>m?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},j.Canvas.prototype._onTouchStart=function(e){var t=this.findTarget(e);!this.allowTouchScrolling&&e.cancelable&&e.preventDefault&&e.preventDefault(),t&&e.cancelable&&e.preventDefault&&e.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(e)),this.__onMouseDown(e),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();j.util.addListener(j.document,"touchend",this._onTouchEnd,{passive:!1}),j.util.addListener(j.document,"touchmove",this._onMouseMove,{passive:!1}),j.util.removeListener(i,r+"down",this._onMouseDown)},j.Textbox.prototype._wrapLine=function(e,t,i,r){const n=e.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?j.util.string.graphemeSplit(e):e.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,_=0,p=0,m=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!m?(h.push(l),l=[],o=g,m=!0):o+=v,m||a||l.push(f),l=l.concat(u),_=a?0:this._measureWord([f],t,d),d++,m=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class se{constructor(e,t,i,r){let n,s;switch(this.mapMediaType_Style=new Map,this.mode="viewer",this.onSelectionChange=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,e.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=e.getFabricCanvas():(this.fabricCanvas=new j.Canvas(e,Object.assign(r,{allowTouchScrolling:!0})),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(e){const t=e.selected,i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(e){const t=this.getActiveObjects(),i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{const t=[];for(let r of i)e.hasDrawingItem(r)&&t.push(r);t.length>0&&e.onSelectionChange&&e.onSelectionChange([],t)}),0)}})),this.fabricCanvas.on("selection:updated",(function(e){const t=e.selected,i=e.deselected,r=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of i){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of r){const r=[],n=[];for(let i of t){const t=i.getDrawingItem();t._drawingLayer===e&&r.push(t)}for(let t of i){const i=t.getDrawingItem();i._drawingLayer===e&&n.push(i)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(r,n)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",e.getFabricCanvas=()=>this.fabricCanvas),this.id=t,this._mapDrawingStyles=i,t){case 1:n=i.get(1),s=i.get(5);break;case 2:n=i.get(2),s=i.get(6);break;case 3:n=i.get(3),s=i.get(7);break;default:n=i.get(4),s=i.get(8)}for(let e of q.arrMediaTypes)this.mapMediaType_Style.set(e,{default:n,selected:s})}getId(){return this.id}_getDrawingStyle(e,t){if("number"!=typeof e)throw new Error("Invalid style id.");const i=this._mapDrawingStyles.get(e);return i?t?JSON.parse(JSON.stringify(i)):i:null}setVisible(e){if(e){for(let e of this._arrFabricObject)e.visible=!0;this._visible=!0}else{for(let e of this._arrFabricObject)e.visible=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(e){return e.styleId?e.styleId:this.mapMediaType_Style.get(e._mediaType)[e.styleSelector].styleId}_getItemCurrentStyle(e){if(e.styleId)return this._getDrawingStyle(e.styleId);return e._mapStyle.get(e.styleSelector)||null}_changeMediaTypeCurStyleInStyleSelector(e,t,i,r){let n;switch(e){case"rect":n=this.fabricCanvas.getObjects("rect");break;case"arc":n=this.fabricCanvas.getObjects("circle");break;case"polygon":n=this.fabricCanvas.getObjects("polygon");break;case"image":n=this.fabricCanvas.getObjects("image");break;case"text":n=this.fabricCanvas.getObjects("textbox");break;case"line":n=this.fabricCanvas.getObjects("line");break;case"path":n=this.fabricCanvas.getObjects("path")}for(let e of n){if(!this._arrFabricObject.includes(e))continue;const r=e.getDrawingItem();r.styleSelector===t&&this._changeItemStyle(r,i,!0)}r||this.fabricCanvas.renderAll()}_changeItemStyle(e,t,i){if(!e||!t)return;const r=e._getFabricObject();"number"==typeof e.styleId&&(t=this._getDrawingStyle(e.styleId)),r.strokeWidth=t.lineWidth,"fill"===t.paintMode?(r.fill=t.fillStyle,r.stroke=t.fillStyle):"stroke"===t.paintMode?(r.fill="transparent",r.stroke=t.strokeStyle):"strokeAndFill"===t.paintMode&&(r.fill=t.fillStyle,r.stroke=t.strokeStyle),r.fontFamily&&(r.fontFamily=t.fontFamily),r.fontSize&&(r.fontSize=t.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(e,t,i){if(!e||!t)return;const r=e.getChildItems();if("add"===i){if(r.includes(t))return;const i=t._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");t._zIndex=null}else{let i;if(t.styleId)i=this._getDrawingStyle(t.styleId);else{i=this.mapMediaType_Style.get(t._mediaType)[e.styleSelector];const r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected,!0)},n=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default,!0)};t._on("selected",r),t._on("deselected",n),t._funcChangeStyleToSelected=r,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,i,!0)}e._fabricObject.addWithUpdate(t._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(t))return;t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,e._fabricObject.removeWithUpdate(t._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(e,t){let i=e._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===e._mediaType){n=e.getChildItems();for(let e of n)if(e._drawingLayer&&e._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(t&&"object"==typeof t&&!Array.isArray(t))for(let e in t)i.set(e,t[e]);if(n){for(let e of n){const t=this.mapMediaType_Style.get(e._mediaType);for(let i of q.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)s=this._getDrawingStyle(e.styleId);else{s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e._on("selected",i),e._on("deselected",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of q.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)s=this._getDrawingStyle(e.styleId);else{s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default)};e._on("selected",i),e._on("deselected",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}this._changeItemStyle(e,s)}e._zIndex=this.id,e._drawingLayer=this,e._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let t=0;t{for(let t of this._arrDrawingLayer)if(t.getId()===e)return!0;return!1};if(void 0===t){for(let e=100;;e++)if(!i(e)){t=e;break}}else if(i(t))throw new Error("Existed drawing layer id.");const r=new se(e,t,this._mapDrawingStyles,{enableRetinaScaling:!1});return r._manager=this,this._arrDrawingLayer.push(r),this._switchPointerEvent(),r}deleteDrawingLayer(e){const t=this.getDrawingLayer(e);if(!t)return;const i=this._arrDrawingLayer;t.dispose(),i.splice(i.indexOf(t),1),this._switchPointerEvent()}clearDrawingLayers(){for(let e of this._arrDrawingLayer)e.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(e){for(let t of this._arrDrawingLayer)if(t.getId()===e)return t;return null}getDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const e=this._arrDrawingLayer[0].fabricCanvas.getActiveObjects(),t=[];for(let i of e)t.push(i.getDrawingItem());return t}setDimensions(e,t){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(e,t)}setObjectFit(e){for(let t of this._arrDrawingLayer)t&&t._setObjectFit(e)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(e){this._arrDrawingLayer.length&&(this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.display=e?"block":"none")}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let e of this._arrDrawingLayer)e.getMode()}}class ae{constructor(e){this._controlTarget=null,this._arrUsers=[],this._mapAction_UserArgs=new Map,this._mapProperty_UserValue=new Map,this._mapAction_Callbacks=new Map,this._controlTarget=e}setControlTarget(e){this._controlTarget=e}getControlTarget(){return this._controlTarget}register(e){this._arrUsers.includes(e)||this._arrUsers.push(e)}logout(e){const t=this._arrUsers.indexOf(e);-1!==t&&(this.clearUserDisiredAction({user:e}),this.clearUserDisiredValue({user:e}),this._arrUsers.splice(t,1))}getRegisteredUsers(){return this._arrUsers}ifUserExisted(e){return this._arrUsers.includes(e)}setDisiredValue(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");r&&(this._controlTarget[t]=i),this._mapProperty_UserValue.get(t)?this._mapProperty_UserValue.get(t).set(e,i):this._mapProperty_UserValue.set(t,new Map([[e,i]]))}clearUserDisiredValue(e){if(e&&(e.user||e.property)){if(e.property&&e.user){const t=this._mapProperty_UserValue.get(e.property);if(!t)return;t.delete(e.user)}else if(e.property)this._mapProperty_UserValue.delete(e.property);else if(e.user)for(let t of this._mapProperty_UserValue.values())t.delete(e.user)}else this._mapProperty_UserValue=new Map}getValue(e){if(!this._controlTarget)throw new Error("Control target is not set.");return this._controlTarget[e]}getPropertyDisiredValue(e){if(this._mapProperty_UserValue.get(e)){const t=[],i=this._mapProperty_UserValue.get(e);for(let e of i.values())t.push(e);return t}return null}setDisiredAction(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");return i||(i=[]),r?this._controlTarget[t](...i):(this._mapAction_UserArgs.get(t)?this._mapAction_UserArgs.get(t).set(e,i):this._mapAction_UserArgs.set(t,new Map([[e,i]])),this._render(t))}clearUserDisiredAction(e){if(e&&(e.user||e.actionName)){if(e.actionName&&e.user){const t=this._mapAction_UserArgs.get(e.actionName);if(!t)return;t.delete(e.user)}else if(e.actionName)this._mapAction_UserArgs.delete(e.actionName);else if(e.user)for(let t of this._mapAction_UserArgs.values())t.delete(e.user);this.render()}else this._mapAction_UserArgs=new Map}addCallback(e,t){const i=this._mapAction_Callbacks.get(e);i?i.push(t):this._mapAction_Callbacks.set(e,[t])}removeCallback(e,t){const i=this._mapAction_Callbacks.get(e);if(!i)return;const r=i.indexOf(t);-1!==r&&i.splice(r,1)}clearCallback(e){e?this._mapAction_Callbacks.delete(e):this._mapAction_Callbacks.clear()}_fireCallback(e){const t=this._mapAction_Callbacks.get(e);if(t)for(let e of t){if(!e)return;setTimeout(e.bind(this._controlTarget),0)}}_render(e){const t=this._mapAction_UserArgs.get(e);if(!t)throw new Error("Unrecorded action.");if(t.size===this._arrUsers.length){let i=[];for(let e of t.values())e.length>0&&(i=e);if(this._controlTarget[e]){const t=this._controlTarget[e](...i);return this._mapAction_UserArgs.delete(e),this._fireCallback(e),t}}}render(e){if(e)return this._render(e);for(let e of this._mapAction_UserArgs.keys())this._render(e)}}class he{static multiply(e,t){const i=[];for(let r=0;r<3;r++){const n=t.slice(3*r,3*r+3);for(let t=0;t<3;t++){const r=[e[t],e[t+3],e[t+6]].reduce(((e,t,i)=>e+t*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,t,i){return he.multiply(e,[1,0,0,0,1,0,t,i,1])}static rotate(e,t){var i=Math.cos(t),r=Math.sin(t);return he.multiply(e,[i,-r,0,r,i,0,0,0,1])}static scale(e,t,i){return he.multiply(e,[t,0,0,0,i,0,0,0,1])}}var le;!function(e){e.GREY="grey",e.GREY32="grey32",e.RGBA="rgba",e.RBGA="rbga",e.GRBA="grba",e.GBRA="gbra",e.BRGA="brga",e.BGRA="bgra"}(le||(le={}));const ce=(e,t,i,r)=>{let n=t+Math.round((e-t)/i)*i;return r&&(n=Math.min(n,r)),n};class ue{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this._predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this._mapCameraResolutions=new Map,this._bWebGLSupported=!0,this.extraBindings=[],this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode&&!this.getDrawingLayers().some((e=>"editor"==e.getMode()))){if(!this._singleFrameModeIpt){const e=document.createElement("input");this._singleFrameModeIpt=e,e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.addEventListener("change",(async()=>{const t=e.files[0];e.value="";const i=await(async e=>{let t=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(t=await createImageBitmap(e),t)return t}catch(e){}var r;return t||(i=await(r=e,new Promise(((e,t)=>{let i=URL.createObjectURL(r),n=new Image;n.dbrObjUrl=i,n.src=i,n.onload=()=>{e(n)},n.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})(t),r=i instanceof HTMLImageElement?i.naturalWidth:i.width,n=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=n;const s=e=>{const t=Date.now();if(0===r||0===n)return null;if(e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");const i=this._scanRegion,s=this.getFrameSize(r,n,i,this.maxCvsSideLength);if(!s)return null;let o=!0;r===s.sWidth&&n===s.sHeight&&(o=!1);const a=this.mapPixelFormatString_Enum.get(this.framePixelFormat.toLowerCase()),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:s.sx,sy:s.sy,width:s.dWidth,height:s.dHeight,colorMode:null,pixelFormat:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:s.sWidth,_sHeight:s.sHeight,_bUseWebGL:null},l=this._getImageData(e,r,n,s,null,{pixelFormat:a});if(!l)return null;const c=Date.now();return h.data=l.data,h.pixelFormat=h.colorMode=l.pixelFormat,h._bUseWebGL=l._bUseWebGL,h.timeSpent=c-t,h.timeStamp=c,l.pixelFormat===le.GREY?h.stride=h.width:h.stride=4*h.width,h};(e=>{let t=this._cvsSingleFrameMode;if(!t){if(t=document.createElement("canvas"),!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(t),t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit="contain",t.style.pointerEvents="none",this._cvsSingleFrameMode=t}t.width==r&&t.height==n||(t.width=r,t.height=n);const i=t.getContext("2d");i.clearRect(0,0,t.width,t.height),i.drawImage(e,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);let o;this._updateDrawingLayersSize();try{o=s(i)}catch(e){throw e}const a=this.mapCameraEvents.get("singleframeacquired");for(let e of a)if(e)try{const t={data:new Uint8Array(o.data),region:JSON.parse(JSON.stringify(o.region)),sx:o.sx,sy:o.sy,width:o.width,height:o.height,stride:o.stride,colorMode:o.colorMode,pixelFormat:o.pixelFormat,timeSpent:o.timeSpent,timeStamp:o.timeStamp,isCropped:o.isCropped,toCanvas:o.toCanvas,_sWidth:o._sWidth,_sHeight:o._sHeight,_bUseWebGL:o._bUseWebGL};await e.apply(this,[t])}catch(e){console.error(e)}})),e.style.position="fixed",e.style.left="-1px",e.style.top="-1px",e.style.width="1px",e.style.height="1px",e.style.backgroundColor="transparent",e.style.color="transparent",document.body.appendChild(e)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._framePixelFormat=void 0,this._defaultFramePixelFormat="rgba",this.mapPixelFormatString_Enum=new Map([["grey",le.GREY],["grey32",le.GREY32],["rgba",le.RGBA],["rbga",le.RBGA],["grba",le.GRBA],["gbra",le.GBRA],["brga",le.BRGA],["bgra",le.BGRA]]),this.shaderPixelFormat=le.RGBA,this.maxVideoCvsLength=3,this._reusedCvs=null,this._reusedWebGLCvs=null,this._tempDataContainer=null,this._webGLTexture=null,this._webGLProgramInfo=null,this._webGLBuffers=null,this._softwareScale=1,this._scaleCenter={x:0,y:0},this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,_focusArea:null},this._tapFocusEnabled=!0,this._focusSupported=!0,this._tapDoFocus=async e=>{if(this._touchMoved)return void(this._touchMoved=!1);if(!this._tapFocusEnabled)return;if(!this._bOpen)return;if(this.singleFrameMode)return;if(!this._video||this._video.paused)return;if(!this._videoTrack)return;if(!this._focusSupported)return;if(this.getDrawingLayers().some((e=>"editor"==e.getMode())))return;if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let t,i,r,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),e instanceof MouseEvent)t=e.clientX,i=e.clientY;else{if(!(e instanceof TouchEvent))throw new Error("Unknown event type.");if(!e.changedTouches.length)return;t=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY}const s=this.getVideoFit(),o=this._video.videoWidth,a=this._video.videoHeight,h=this._elContainer.getBoundingClientRect(),l=h.left,c=h.top,u=window.getComputedStyle(this._elContainer),d=parseFloat(u.width),f=parseFloat(u.height),g=d/f,_=o/a;let p=1;if("contain"===s)_>g?(p=d/o,r=(t-l)/p,n=(i-c-(f-d/_)/2)/p):(p=f/a,n=(i-c)/p,r=(t-l-(d-f*_)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");_>g?(p=f/a,n=(i-c)/p,r=(t-l+(f*_-d)/2)/p):(p=d/o,r=(t-l)/p,n=(i-c+(d/_-f)/2)/p)}const m={x:r+"px",y:n+"px"},v=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=v;await this._setLocalFocus(m,v,y,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance),this._focusParameters.taskBackToContinous=setTimeout((()=>{this._videoTrack&&this._videoTrack.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime)},this._touchMoved=!1,this._touchMoveEvent=()=>{this._touchMoved=!0},this._recordedStates={},this.playCallbackInfo=null,this._toCanvas=function(){const e=document.createElement("canvas");let t;if(e.width=this.width,e.height=this.height,"grey"===(this.pixelFormat||this.colorMode)){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}await this.setResolution(e,t),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this.singleFrameMode)if("visible"===document.visibilityState){if(ue._onLog&&ue._onLog("DCE: document visible."),this._bOpen&&this._vc_bPlayingVideoBeforeHide)if(this.videoSrc)this._video.play();else if(this._video.srcObject){const e=this._video.srcObject.getTracks()[0];this._video.srcObject.active&&e&&!e.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(ue._onLog&&ue._onLog("DCE: document hidden."),["iPhone","iPad"].includes(Y.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let e of this._arrScanRegionOverlays)e&&(e.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&(e.style.display="",this._updateScanRegionOverlay(e));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null}static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:X,worker:z,getUserMedia:Z,camera:await K(),browser:Y.browser,version:Y.version,OS:Y.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");ue._engineResourcePath=(e=>{if(null==e&&(e="./"),!V){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(e){let t;try{t=window[e];const i="__storage_test__";return t.setItem(i,i),t.removeItem(i),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&t&&0!==t.length}}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"data"in e&&"region"in e&&"sx"in e&&"sy"in e&&"width"in e&&"height"in e&&("colorMode"in e||"pixelFormat"in e)&&"timeSpent"in e&&"timeStamp"in e&&"isCropped"in e&&"toCanvas"in e&&"_sWidth"in e&&"_sHeight"in e&&"_bUseWebGL"in e}static async testCameraAccess(){try{if(!navigator||!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return{ok:!1,message:"Insecure context."};(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()}))}catch(e){if("OverconstrainedError"===e.name||"NotFoundError"===e.name)return{ok:!1,message:"No camera detected."};if("NotAllowedError"===e.name)return{ok:!1,message:"No permission to access camera."};if("AbortError"===e.name)return{ok:!1,message:"Some problem occurred which prevented the device from being used."};if("NotReadableError"===e.name)return{ok:!1,message:"A hardware error occurred."};if("SecurityError"===e.name)return{ok:!1,message:"User media support is disabled."};throw e}return{ok:!0,message:"Successfully accessed the camera."}}set maxCvsSideLength(e){if(e<=0)throw new Error("Invalid value.");this._maxCvsSideLength=e}get maxCvsSideLength(){if(void 0!==this._maxCvsSideLength)return this._maxCvsSideLength;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxCvsSideLength");if(e&&1===e.length)return e[0]}return this._defaultMaxCvsSideLength}static set defaultUIElementURL(e){ue._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=ue._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",ue.engineResourcePath)}getUIElement(){return this.UIElement}async setUIElement(e){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof e||e instanceof String){if(!e.trim().startsWith("<")){let t=await fetch(e);if(!t.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+t.statusText);e=await t.text()}if(!e.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let t=document.createElement("div");t.innerHTML=e;for(let e=0;e100||e.regionTop>100||e.regionRight>100||e.regionBottom>100)))}set scanRegion(e){if(!this._checkValidRegion(e))throw new Error("Invalid region.");this._scanRegion=JSON.parse(JSON.stringify(e)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}setScanRegion(e){this.scanRegion=e}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}_calculateCvsSize(){if(!this._bOpen)return null;let e,t,i;if(this.singleFrameMode)e=this._imgWidth,t=this._imgHeight,i="contain";else{if(!this._video)return null;e=this._video.videoWidth,t=this._video.videoHeight,i=this.getVideoFit()}return{width:e,height:t,objectFit:i}}addScanRegionOverlayCanvas(){this._assertOpen();const e=document.createElement("canvas");if(this._updateScanRegionOverlay(e),!this._scanRegionOverlayContainer){const e=document.createElement("div");if(this._scanRegionOverlayContainer=e,e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.overflow="hidden",e.style.pointerEvents="none",this._layerBaseCvs)this._layerBaseCvs.parentElement.after(e);else if(this._cvsScanRegion)this._cvsScanRegion.after(e);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(e);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e)}this._recordedStates.overlayShow=!0}return this._scanRegionOverlayContainer.append(e),this._arrScanRegionOverlays.push(e),e}removeScanRegionOverlayCanvas(e){const t=this._arrScanRegionOverlays.indexOf(e);-1!==t&&(e.remove(),this._arrScanRegionOverlays.splice(t,1))}_updateScanRegionOverlay(e){if(!e)return;const t=this._calculateCvsSize();if(!t)return;const{width:i,height:r,objectFit:n}=t;if(i<=0||r<=0)return e.width=0,void(e.height=0);const s=this._getRegionInPixels(i,r,this._scanRegion),o=this.getFrameSize(i,r,this._scanRegion,this.maxCvsSideLength),a=o.dWidth,h=o.dHeight;e.width==a&&e.height==h||(e.width=a,e.height=h);const l=window.getComputedStyle(this._elContainer),c=parseFloat(l.width),u=parseFloat(l.height),d=c/u,f=i/r;let g,_,p,m,v=1;"contain"===n?(f>d?(v=c/i,g=0,_=(u-r*v)/2):(v=u/r,g=(c-i*v)/2,_=0),g+=s.regionLeft*v,_+=s.regionTop*v,p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):"cover"===n?(f>d?(v=u/r,g=s.regionLeft*v-(i*v-c)/2,_=s.regionTop*v):(v=c/i,g=s.regionLeft*v,_=s.regionTop*v-(r*v-u)/2),p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):(g=0,_=0,p=0,m=0),e.style.position="absolute",e.style.left=g+"px",e.style.top=_+"px",e.style.width=p+"px",e.style.height=m+"px"}showScanRegionOverlays(){this._scanRegionOverlayContainer&&("none"==this._scanRegionOverlayContainer.style.display&&(this._scanRegionOverlayContainer.style.display=""),this._recordedStates.overlayShow=!0)}hideScanRegionOverlays(){this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none",this._recordedStates.overlayShow=!1)}setViewDecorator(e,t){if(!e)return void(this._cvsViewDecorator&&(this._cvsViewDecorator.remove(),this._cvsViewDecorator=null));if(!t)throw new Error("Invalid area.");this._assertOpen();let i=[];if("string"==typeof e?i.push(e):Array.isArray(e)&&(i=JSON.parse(JSON.stringify(e))),!this._cvsViewDecorator){if(this._cvsViewDecorator=document.createElement("canvas"),this._scanRegionOverlayContainer)this._scanRegionOverlayContainer.after(this._cvsViewDecorator);else if(this._layerBaseCvs)this._layerBaseCvs.parentElement.after(this._cvsViewDecorator);else if(this._cvsScanRegion)this._cvsScanRegion.after(this._cvsViewDecorator);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(this._cvsViewDecorator);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(this._cvsViewDecorator);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(this._cvsViewDecorator)}this._recordedStates.decoratorShow=!0}this._decoratorArea=JSON.parse(JSON.stringify(t)),this._decoratorType.length=0;const r=["rectangle","focus"],n=["crossline","crosshair"];let s=!1,o=!1;for(let e of i)e=e.toLowerCase(),r.includes(e)&&!s&&(s=!0,this._decoratorType.push(e)),n.includes(e)&&!o&&(o=!0,!this._decoratorType.includes(e)&&this._decoratorType.push(e));this._updateViewDecorator()}getViewDecorator(){return{type:JSON.parse(JSON.stringify(this._decoratorType)),area:JSON.parse(JSON.stringify(this._decoratorArea)),canvas:this._cvsViewDecorator}}showViewDecorator(){this._cvsViewDecorator&&("none"==this._cvsViewDecorator.style.display&&(this._cvsViewDecorator.style.display=""),this._recordedStates.decoratorShow=!0)}hideViewDecorator(){this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none",this._recordedStates.decoratorShow=!1)}setViewDecoratorLineWidth(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("lineWidth"))throw new Error(`It is not allowed to change the property 'lineWidth' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].lineWidth=t,this._updateViewDecorator()}setViewDecoratorStrokeStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("strokeStyle"))throw new Error(`It is not allowed to change the property 'strokeStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].strokeStyle=t,this._updateViewDecorator()}setViewDecoratorFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("fillStyle"))throw new Error(`It is not allowed to change the property 'fillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].fillStyle=t,this._updateViewDecorator()}setViewDecoratorMaskFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("maskFillStyle"))throw new Error(`It is not allowed to change the property 'maskFillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].maskFillStyle=t,this._updateViewDecorator()}_updateViewDecorator(){if(!this._bOpen)return;if(!this._cvsViewDecorator||!this._decoratorArea)return;let e;if(this.singleFrameMode)e="contain";else{if(!this._video)return;e=this.getVideoFit()}const t=this._cvsViewDecorator;t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit=e,t.style.pointerEvents="none";const i=this.getVisibleRegion(!0),r=i.regionRight-i.regionLeft,n=i.regionBottom-i.regionTop;if(t.width==r&&t.height==n||(t.width=r,t.height=n),r<=0||n<=0)return;const s=t.getContext("2d");s.clearRect(0,0,t.width,t.height);const o=this._decoratorArea.x/100*r,a=this._decoratorArea.y/100*n,h=this._decoratorArea.width/100*r,l=this._decoratorArea.height/100*n;for(let e of this._decoratorType){if("rectangle"===e){s.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,s.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const e=s.lineWidth/2;s.strokeRect(Math.round(o-e),Math.round(a-e),Math.round(h+s.lineWidth),Math.round(l+s.lineWidth))}if("focus"===e){s.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.focus.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.focus.lineWidth,s.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const e=s.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];s.beginPath();for(let e=0;e{const e=parseFloat(window.getComputedStyle(this._elContainer).width),t=parseFloat(window.getComputedStyle(this._elContainer).height);let s,o={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?e/tthis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){if(void 0!==this._maxNumberOfFramesInBuffer)return this._maxNumberOfFramesInBuffer;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxNumberOfFramesInBuffer");if(e&&1===e.length)return e[0]}return this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(e){this._refreshInterval=e}get refreshInterval(){if(void 0!==this._refreshInterval)return this._refreshInterval;if(this._controler){const e=this._controler.getPropertyDisiredValue("refreshInterval");if(e&&1===e.length)return e[0]}return this._defaultRefreshInterval}static async createInstance(e){let t=new ue;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,ue.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ue.onWarning&&ue.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ue.onWarning&&ue.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),t._drawingLayersManager=new oe,t}static async playVideo(e,t,i){return new Promise(((r,n)=>{e||n(new Error("Invalid video element.")),t||n(new Error("Invalid source.")),e.onloadedmetadata=async()=>{e.onloadedmetadata=null,await e.play(),r(e)},"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,void 0!==i&&setTimeout((()=>n(new Error("Failed to play video. Timeout."))),i)}))}static findBestRearCamera(e){if(!e||!e.length)return null;const t=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"];for(let i of e){const e=i.label.toLowerCase();if(e&&t.some((t=>e.includes(t)))&&/\b0(\b)?/.test(e))return i.deviceId}return["Android","HarmonyOS"].includes(Y.OS)?e[e.length-1].deviceId:null}async play(e,t,i,r){let n;if(this._video&&this.videoSrc){ue._onLog&&(n=Date.now(),ue._onLog("DCE: start loading static video: "+n));const e=await ue.playVideo(this._video,this.videoSrc,4e3);if(ue._onLog&&ue._onLog("DCE: finish loading static video. Costs: "+(Date.now()-n)),!this._video)return e.pause(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};const t={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};this.playCallbackInfo=JSON.parse(JSON.stringify(t));const i=this.mapCameraEvents.get("played");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[i])}),0)}return this._recordedStates.videoPlaying=!0,t}if(this.singleFrameMode)return r&&r.notTriggerSingleFrameClick||this._clickIptSingleFrameMode(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};if(!this._video)throw new Error("'video' is null or undefined.");const s=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,s{var r;try{this._video&&this._video.srcObject&&this.stop(),ue._onLog&&ue._onLog("DCE: ======before video========");const n=()=>{if(!this._video)throw a&&a.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},s=this.getVideoSettings();let o,a;if("boolean"==typeof s.video&&(s.video={}),e)delete s.video.facingMode,s.video.deviceId={exact:e};else if(s.video.deviceId);else if(this._lastDeviceId)delete s.video.facingMode,s.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&ue.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete s.video.facingMode,s.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),t=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&t&&(s.video.width=e,s.video.height=t)}else if(this.ifSkipCameraInspection);else if(s.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=s.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){o=!0;const e=ue.findBestRearCamera(this._allCameras);e&&(delete s.video.facingMode,s.video.deviceId={ideal:e})}}t&&(s.video.width={ideal:t}),i&&(s.video.height={ideal:i}),ue._onLog&&ue._onLog("DCE: ======try getUserMedia========");let h=[0,500],l=null;const c=async e=>{for(let t of h){t&&await new Promise((e=>setTimeout(e,t))),n();try{ue._onLog&&ue._onLog("DCE: ask "+JSON.stringify(e)),a=await navigator.mediaDevices.getUserMedia(e);break}catch(e){l=e,ue._onLog&&ue._onLog("DCE: "+e.message||e)}}};let u;if(await c(s),a||(ue._onLog&&ue._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(s)),"object"==typeof u.video&&(["iPhone","iPad"].includes(Y.OS)?(t>=1280||i>=1280?u.video.width=1280:t>=640||i>=640?u.video.width=640:(t<640||i<640)&&(u.video.width=320),delete u.video.height):o&&!s.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0),ue._onLog&&ue._onLog("DCE: "+u),await c(u)),a||(h=[1e3,2e3],await c(s)),a||await c(u),!a)throw l;const d=()=>{const e=a.getVideoTracks();let t,i;if(e.length&&(t=this._videoTrack=e[0]),this._video&&t){const e=t.getSettings();if(e)for(let r of this._allCameras)if(e.deviceId===r.deviceId){r._checked=!0,r.label=t.label,i=r;break}}this._currentCamera=i};if(await this.getAllCameras(!1),n(),o){d();const e=ue.findBestRearCamera(this._allCameras),t=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;e&&e!=t&&(a.getTracks().forEach((e=>{e.stop()})),h=[0,500,1e3,2e3],await c(s))}ue._onLog&&ue._onLog("DCE: ======play video========"),n(),await ue.playVideo(this._video,a,4e3),n(),ue._onLog&&ue._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=f,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),ue._onLog&&ue._onLog("DCE: got "+f),d(),this._renderSelCameraInfo();const g={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};g.deviceId&&(this._lastDeviceId=g.deviceId,this.ifSaveLastUsedCamera&&ue.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),s.video.width&&s.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(s.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(s.video.height)))));const _=this.mapCameraEvents.get("played");for(let e of _){if(!e)continue;const t=JSON.parse(JSON.stringify(g));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}return this.promisePlay=null,g}catch(e){throw this.promisePlay=null,this._bgLoading&&(this._bgLoading.style.display="none"),"NotFoundError"===e.name&&(DOMException?e=new DOMException("No camera available, please use a device with an accessible camera.",e.name):(e=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),e}})(),ue._onLog&&(n=Date.now(),ue._onLog("DCE: start opening camera: "+n));const o=await this.promisePlay;return ue._onLog&&ue._onLog("DCE: finish opening camera. Costs: "+(Date.now()-n)),this.playCallbackInfo=JSON.parse(JSON.stringify(o)),this._recordedStates.videoPlaying=!0,o}async resume(){this._assertOpen(),this._video&&(await this._video.play(),this._recordedStates.videoPlaying=!0),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&t.classList.contains("dce-opt-gotResolution")?this._optGotRsl=t:!this._btnClose&&t.classList.contains("dce-btn-close")?this._btnClose=t:!this._selMinLtr&&t.classList.contains("dlr-sel-minletter")?(this._selMinLtr=t,this._selMinLtr.options.length||(this._selMinLtr.innerHTML=[this._optGotMinLtr?"":'','','','','','','','','','',''].join(""),this._optGotMinLtr=this._optGotMinLtr||this._selMinLtr.options[0])):!this._optGotMinLtr&&t.classList.contains("dlr-opt-gotMinLtr")&&(this._optGotMinLtr=t);if(this.extraBindings&&this.extraBindings.length)for(let i of this.extraBindings)try{i(t)}catch(e){}}if(!this._video)throw this._unbindUI(),Error(`Can not find the video container element with class '${this.containerClassName}'`);this.singleFrameMode||this.videoSrc?(this.singleFrameMode&&(this._elContainer&&(this._elContainer.addEventListener("click",this._clickIptSingleFrameMode),this._elContainer.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._elContainer&&(["Android","HarmonyOS"].includes(Y.OS)?(this._elContainer.addEventListener("touchend",this._tapDoFocus),this._elContainer.addEventListener("touchmove",this._touchMoveEvent)):this._elContainer.addEventListener("click",this._tapDoFocus)),this._selCam&&(this._selCam.style.display="block",this._selCam.addEventListener("change",this._onCameraSelChange)),this._selRsl&&(this._selRsl.style.display="block",this._selRsl.addEventListener("change",this._onResolutionSelChange)),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._bgLoading&&(this._bgLoading.style.display="block")),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&(this._resizeObserver||(this._resizeObserver=new ResizeObserver((e=>{for(let t of e)t.target===this._elContainer&&this._updateLayers()}))),this._elContainer&&this._resizeObserver.observe(this._elContainer)),window.addEventListener("resize",this._updateLayers)}_unbindUI(){this.singleFrameMode?(this._elContainer&&(this._elContainer.removeEventListener("click",this._clickIptSingleFrameMode),this._elContainer.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._elContainer&&(this._elContainer.removeEventListener("click",this._tapDoFocus),this._elContainer.removeEventListener("touchend",this._tapDoFocus),this._elContainer.removeEventListener("touchmove",this._touchMoveEvent)),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._drawingLayersManager.setVisible(!1),this._hideOriginalImageCvs(),this._videoContainer&&this._videoContainer.remove(),this._video=null,this._videoContainer=null,this._elContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._updateLayers)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}async open(e){this.UIElement||await this.setUIElement(ue.defaultUIElementURL),this._bindUI(),e&&this.appendAndShowUI();let t=await this.play();this.bOpen=!0,this._focusParameters.fds=null,this._focusParameters.kTimeout=void 0,this._focusSupported=!0,this._tapFocusEnabled&&!this.singleFrameMode&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,this._focusParameters.fds||(this._focusSupported=!1,this._tapFocusEnabled=!1));const i=this.mapCameraEvents.get("cameraopen");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[i])}),0)}return t}close(e){if(!this._video)return;this.stop(),this._hideOriginalImage(!1),this.hideTip(),this._unbindUI(),e&&this.hideUI(),this.stopFetchingLoop(),this.bOpen=!1;const t=this.mapCameraEvents.get("cameraclose");for(let e of t){if(!e)continue;const t={width:0,height:0,deviceId:null};setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}stop(){this._video&&this._video.srcObject&&(ue._onLog&&ue._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((e=>{e.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(ue._onLog&&ue._onLog("DCE: ======stop existing video========"),this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0,this._reusedCvs&&this._reusedCvs.ctx2d&&this._reusedCvs.ctx2d.clearRect(0,0,this._reusedCvs.width,this._reusedCvs.height),this.forceLoseContext()}async getAllCameras(e=!0){let t=(await navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind));if(e&&t&&t.length&&!t[0].deviceId){let e=await navigator.mediaDevices.getUserMedia({video:!0});t=(await navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)),e.getTracks().forEach((e=>{e.stop()}))}const i=[],r=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&r.push(e);for(let e=0;e{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}if(r!==s.width||n!==s.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const e=this.mapCameraEvents.get("resolutionchange");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(s));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return s}getResolution(){if(this._bOpen)return[this._video.videoWidth,this._video.videoHeight];{let e=0,t=0;const i=this.videoSettings.video.width,r=this.videoSettings.video.height;return i&&(e=i.exact||i.ideal||i),r&&(t=r.exact||r.ideal||r),[e,t]}}async setResolution(e,t){let i,r;if(e instanceof Array?(i=e[0],r=e[1]):(i=e,r=t),this.videoSettings.video.width={ideal:i},this.videoSettings.video.height={ideal:r},!this._bOpen||this._video.paused)return null;const n=this._video.videoWidth,s=this._video.videoHeight,o=await this.play(null,i,r);if(n!==o.width||s!==o.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const e=this.mapCameraEvents.get("resolutionchange");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(o));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return o}async getResolutions(e){let t="";const i=(e,t)=>{const i=this._mapCameraResolutions.get(e);if(!i||!i.length)return!1;for(let e of i)if(e[0]===t.width&&e[1]===t.height)return!0;return!1},r=async(e,t,i)=>{const r={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(e){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const e=s[0].getSettings();o={width:e.width,height:e.height}}catch(e){const t=document.createElement("video");t.srcObject=n,o={width:t.videoWidth,height:t.videoHeight},t.srcObject=null}return s.forEach((e=>{e.stop()})),o};if(!this._bOpen){const n=this.videoSettings.video.deviceId;if(!n)return null;if(t=n.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:n.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!t)return null;let s=this._mapCameraResolutions.get(t);if(s&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),s=this._mapCameraResolutions.get(t);for(let e of this._predefinedResolutions){const n=await r(t,e.width,e.height);n&&!i(t,n)&&s.push([n.width,n.height])}return s}if(this._currentCamera){t=this._currentCamera.deviceId;let r=this._mapCameraResolutions.get(t);if(r&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),r=this._mapCameraResolutions.get(t);const n=this.getConstraints();for(let e of this._predefinedResolutions){await this._videoTrack.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const n=this._videoTrack.getSettings(),s={width:n.width,height:n.height};i(t,s)||r.push([s.width,s.height])}return await this._videoTrack.applyConstraints(n),r}return null}on(e,t){if(!t)return;const i=this.mapCameraEvents.get(e.toLowerCase());if(!i)throw new Error(`Event '${e}' does not exist.`);i.includes(t)||i.push(t)}off(e,t){const i=this.mapCameraEvents.get(e.toLowerCase());if(!i)throw new Error(`Event '${e}' does not exist.`);const r=i.indexOf(t);-1!==r&&i.splice(r,1)}offAll(e){if(e){if("string"==typeof e){const t=this.mapCameraEvents.get(e);t&&(t.length=0)}}else for(let e of this.mapCameraEvents.values())e&&(e.length=0)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(e){if(this.videoSettings=JSON.parse(JSON.stringify(e)),this._lastDeviceId=null,this._bOpen)return this.play()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return await this._videoTrack.applyConstraints(e)}async turnOnTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}async turnOffTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}async setColorTemperature(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let t=this.getCapabilities().colorTemperature;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({advanced:[{colorTemperature:e,whiteBalanceMode:"manual"}]})}getColorTemperature(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let t=this.getCapabilities().exposureCompensation;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({advanced:[{exposureCompensation:e}]})}getExposureCompensation(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setHardwareScale()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");if(!this._videoTrack)return;const t=this.getCapabilities().zoom;if(!t)throw new Error("Not supported.");return et.max&&(e=t.max),e=ce(e,t.min,t.step,t.max),await this._videoTrack.applyConstraints({advanced:[{zoom:e}]}),e}_getHardwareScale(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(e,t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setSoftwareScale()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");t&&this._setScaleCenter(t),this._softwareScale=e,this._scaleVideo(e,t)}_getSoftwareScale(){return this._softwareScale}_setScaleCenter(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setScaleCenter()' is unavailable in singleFrameMode.");if(!e||"string"!=typeof e.x||"string"!=typeof e.y)throw new Error("Invalid center.");const t=this._video.videoWidth,i=this._video.videoHeight;let r=0,n=0;if(e.x.endsWith("px"))r=parseFloat(e.x);else{if(!e.x.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(e.x)/100*t}if(e.y.endsWith("px"))n=parseFloat(e.y);else{if(!e.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(e.y)/100*i}if(NaN==r||NaN==n)throw new Error("Invalid scale center.");this._scaleCenter={x:r,y:n}}_resetScaleCenter(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_resetScaleCenter()' is unavailable in singleFrameMode.");const e=this._video.videoWidth,t=this._video.videoHeight;this._scaleCenter={x:e/2,y:t/2}}_isVideoCenter(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_isVideoCenter()' is unavailable in singleFrameMode.");return e&&e.x==this._video.videoWidth/2&&e.y==this._video.videoHeight/2}async _setZoom(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const t=await this._setHardwareScale(e);let i=this._getHardwareScale();1==i&&1!=t&&(i=t),e>i?this._setSoftwareScale(e/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(e)}catch(t){if("Not supported."!==(t.message||t))throw t;this._setSoftwareScale(e)}}async setZoom(e){if("number"!=typeof e&&"object"!=typeof e)throw new TypeError("Illegal type of argument.");if("number"==typeof e)return this._setZoom(e);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(e){if("number"!=typeof e.factor)throw new TypeError("Illegal type of 'factor'.");if(e.factor<1)throw new RangeError("Invalid value.");e.centerPoint?this._setScaleCenter(e.centerPoint):this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const t=await this._setHardwareScale(e.factor);let i=this._getHardwareScale();1==i&&1!=t&&(i=t),e.factor>i?this._setSoftwareScale(e.factor/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(e.factor)}catch(t){if("Not supported."!==(t.message||t))throw t;this._setSoftwareScale(e.factor)}}}getZoom(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?{factor:this._getHardwareScale()*this._softwareScale}:null}async resetZoom(){await this.setZoom({factor:1})}async setFrameRate(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let t=this.getCapabilities().frameRate;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:e})}getFrameRate(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(e,t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if("string"!=typeof e)throw Error("Invalid focus mode.");e=e.toLowerCase();const i=this.getCapabilities().focusMode,r=this.getCapabilities().focusDistance;if(!i)throw Error("Not supported.");if(!i.includes(e))throw Error("Unsupported mode.");if(t>=0){if(!r)throw Error("Manual focus unsupported.");return tr.max&&(t=r.max),t=ce(t,r.min,r.step,r.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:e,focusDistance:t}]})}return await this._videoTrack.applyConstraints({advanced:[{focusMode:e}]})}async setFocus(e,t){if("string"==typeof e)return this._setFocus(e,t);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if(!e)return;const i=this.getCapabilities(),r=i.focusMode,n=i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof e.mode)throw Error("Invalid focus mode.");const s=e.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"!==s)return this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:s}]});if(!n)throw Error("Manual focus unsupported.");if(e.hasOwnProperty("distance")){let t=e.distance;return tn.max&&(t=n.max),t=ce(t,n.min,n.step,n.max),this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:s,focusDistance:t}]})}if(!e.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const t=e.area.centerPoint;let i=e.area.width,r=e.area.height;if(!i||!r){const e=this._video.videoWidth,t=this._video.videoHeight;i||(i=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters._focusArea={centerPoint:{x:t.x,y:t.y},width:i,height:r},await this._setLocalFocus(t,i,r)}}getFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const e=this._videoTrack.getSettings().focusMode;return e?"continuous"===e?{mode:e}:{mode:e,distance:this._videoTrack.getSettings().focusDistance}:null}getFocusSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const e=this._videoTrack.getSettings(),t=e.focusMode;return t?"manual"===t?this._focusParameters._focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters._focusArea))}:{mode:"manual",distance:e.focusDistance}:{mode:t}:null}async _setFocusAndGetContract(e,t){const i=e=>{if(!this._bOpen||!this._videoTrack||this.video.paused||e.focusTaskId!=this._focusParameters.curFocusTaskId){this._bOpen&&this._videoTrack&&!this.video.paused||(this._focusParameters.isDoingFocus=0);const t=new Error(`Focus task ${e.focusTaskId} canceled.`);throw t.name="DeprecatedTaskError",t}1===this._focusParameters.isDoingFocus&&Date.now()-e.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;t=ce(t,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:"manual",focusDistance:t}]}),i(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/t),Math.abs(1/this._focusParameters.fds.max-1/t))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/t)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=t,await new Promise((e=>{setTimeout(e,r)})),i(e);let n=e.focusL-e.focusW/2,s=e.focusT-e.focusH/2,o=e.focusW,a=e.focusH;if(n>=this.video.videoWidth||s>=this.video.videoHeight)throw new Error("Invalid area.");n+o>this.video.videoWidth&&(o=this.video.videoWidth-n),s+a>this.video.videoHeight&&(a=this.video.videoHeight-s);const h=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:n,sy:s,sWidth:o,sHeight:a,dWidth:o,dHeight:a},null,{pixelFormat:le.RGBA});if(!h)return this._setFocusAndGetContract(e,t);const l=h.data;let c=0;for(let e=0,t=l.length-8;eo&&oc)return await this._doFocusDetail(e,s,o,r,n,l,c)}else{let a=await this._setFocusAndGetContract(e,l);if(o>a)return await this._doFocusDetail(e,s,o,r,n,l,a);if(o==a)return await this._doFocusDetail(e,s,o,l,a);let c=await this._setFocusAndGetContract(e,h);if(c>o&&o{try{(null==t||tthis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=ce(Math.sqrt(i*(t||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=ce(Math.sqrt((t||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=ce(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await this._setFocusAndGetContract(e,s),a=await this._setFocusAndGetContract(e,n),h=await this._setFocusAndGetContract(e,r);if(a>h&&ho&&a>o){let t=await this._setFocusAndGetContract(e,i);const n=await this._doFocusDetail(e,r,h,i,t,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const t=await this._doFocusDetail(e,r,h,s,o);return this._focusParameters.isDoingFocus=0,t}return d(e,t,i)}catch(e){if("DeprecatedTaskError"!==e.name)throw e}};return d(u,r,n)}async enableTapToFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'enableTapToFocus()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error("Video is not playing.");if(!this._focusSupported)throw new Error("Tapping to focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,this._tapFocusEnabled=!1,new Error("Tapping to focus unsupported.");this._tapFocusEnabled=!0}disableTapToFocus(){this._tapFocusEnabled=!1}isTapToFocusEnabled(){return this._tapFocusEnabled}_updateVideoContainerStyle(){if(!this._video)return;if(this.singleFrameMode)return;const e=this._getSoftwareScale(),t=this._videoContainer;if("contain"===this.videoFit&&e>1){const e=this._video.videoWidth,i=this._video.videoHeight,r=window.getComputedStyle(this._elContainer),n=parseFloat(r.width),s=parseFloat(r.height),o=e/i;if(n/sa?o/(i/e):s/(r/e));const c=l*(1-1/e)*(i/2-this._scaleCenter.x),u=l*(1-1/e)*(r/2-this._scaleCenter.y);this._video.style.transform=`translate(${c}px, ${u}px) scale(${e})`}this._updateVideoContainerStyle()}}getFrameSize(e,t,i,r){if(!e||!t)return null;let n,s,o,a,h=e,l=t;const c={regionLeft:0,regionTop:0,regionRight:h,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*h/100,c.regionTop=i.regionTop*l/100,c.regionRight=i.regionRight*h/100,c.regionBottom=i.regionBottom*l/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),n=Math.round(c.regionLeft),s=Math.round(c.regionTop),h=Math.round(c.regionRight-c.regionLeft),l=Math.round(c.regionBottom-c.regionTop)):(n=0,s=0,h=Math.round(h),l=Math.round(l));const u=Math.max(h,l);if(r&&r>0&&u>r){const e=r/u;h>l?(o=r,a=Math.round(l*e)):(o=Math.round(h*e),a=r)}else o=h,a=l;return o<=0||a<=0?null:{sx:n,sy:s,sWidth:h,sHeight:l,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoData()}getImage(){return this.getFrame()}_drawImage(e,t,i,r,n,s,o){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!i||!r)return null;if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let a;ue._onLog&&(a=Date.now(),ue._onLog("DCE: _drawImage(), START: "+a));let h=0,l=0,c=i,u=r,d=0,f=0,g=i,_=r;n&&(n.sx&&(h=Math.round(n.sx)),n.sy&&(l=Math.round(n.sy)),n.sWidth&&(c=Math.round(n.sWidth)),n.sHeight&&(u=Math.round(n.sHeight)),n.dx&&(d=Math.round(n.dx)),n.dy&&(f=Math.round(n.dy)),n.dWidth&&(g=Math.round(n.dWidth)),n.dHeight&&(_=Math.round(n.dHeight)));let p=le.RGBA;o&&o.pixelFormat&&(p=o.pixelFormat);const m=e;if(o&&o.bUseWebGL){ue._onLog&&ue._onLog("DCE: _drawImage() in WebGL."),(m.width{const t=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),e.STATIC_DRAW);const i=e.createBuffer();return e.bindBuffer(e.ARRAY_BUFFER,i),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),e.STATIC_DRAW),{positions:t,texCoords:i}},i=e=>{const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t},r=(e,t)=>{const i=e.createProgram();if(t.forEach((t=>e.attachShader(i,t))),e.linkProgram(i),!e.getProgramParameter(i,e.LINK_STATUS)){const t=new Error(`An error occured linking the program: ${e.getProgramInfoLog(i)}.`);throw t.name="WebGLError",t}return e.useProgram(i),i},n=(e,t,i)=>{const r=e.createShader(t);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){const t=new Error(`An error occured compiling the shader: ${e.getShaderInfoLog(r)}.`);throw t.name="WebGLError",t}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(e,[n(e,e.VERTEX_SHADER,s),n(e,e.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:h,attribLocations:{vertexPosition:e.getAttribLocation(h,"a_position"),texPosition:e.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:e.getUniformLocation(h,"u_image"),uColorFactor:e.getUniformLocation(h,"uColorFactor"),uMatrix:e.getUniformLocation(h,"u_matrix"),uTextureMatrix:e.getUniformLocation(h,"u_textureMatrix")}},this._webGLBuffers=t(e),this._webGLTexture=i(e),this.shaderPixelFormat=p}const n=(e,t,i)=>{e.bindBuffer(e.ARRAY_BUFFER,t),e.enableVertexAttribArray(i),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)},o=(e,t,i)=>{const r=e.RGBA,n=e.RGBA,s=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,r,n,s,i)},v=(e,t,s,o)=>{e.clearColor(0,0,0,1),e.clearDepth(1),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),n(e,s.positions,t.attribLocations.vertexPosition),n(e,s.texCoords,t.attribLocations.texPosition),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,o),e.uniform1i(t.uniformLocations.uSampler,0),e.uniform1f(t.uniformLocations.uColorFactor,[le.GREY,le.GREY32].includes(p)?1:0);let a,m,v=he.translate(he.identity(),-1,-1);v=he.scale(v,2,2),v=he.scale(v,1/e.canvas.width,1/e.canvas.height),a=he.translate(v,d,f),a=he.scale(a,g,_),e.uniformMatrix3fv(t.uniformLocations.uMatrix,!1,a),m=he.translate(he.identity(),h/i,l/r),m=he.scale(m,c/i,u/r),e.uniformMatrix3fv(t.uniformLocations.uTextureMatrix,!1,m),e.drawArrays(e.TRIANGLES,0,6)};let y;if(o(e,this._webGLTexture,t),v(e,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),s){if(s.lengtht||r.sy>i||r.sx+r.sWidth>t||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;ue._onLog&&(o=Date.now(),ue._onLog("DCE: _getImageData(), START: "+o));const a=Math.round(r.sx),h=Math.round(r.sy),l=Math.round(r.sWidth),c=Math.round(r.sHeight),u=Math.round(r.dWidth),d=Math.round(r.dHeight);let f=le.RGBA;s&&s.pixelFormat&&(f=s.pixelFormat);let g,_,p,m=this._bWebGLSupported;s&&0==s.bUseWebGL&&(m=!1),m?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),g=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),g=this._reusedCvs);try{if(m)if(ue._onLog&&ue._onLog("DCE: _getImageData() in WebGL."),n)if(f===le.GREY){if(p=new Uint8Array(u*d*4),_=this._drawImage(g,e,t,i,{sx:a,sy:h,sWidth:l,sHeight:c,dWidth:u,dHeight:d},p,{pixelFormat:f,bUseWebGL:m}),p=this._transformPixelFormat(p,_.pixelFormat,f),n){if(n.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");e=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return e}_fetchingLoop(e){if(this.isDisposed&&this.disposed)return;if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();const t=()=>{ue._onLog&&ue._onLog("DCE: start fetching a frame into buffer: "+Date.now());const e=this.getCurrentRegion();let t=this._getVideoData(null,{region:e});if(!t)return void ue._onLog;for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t);const i=this.mapCameraEvents.get("frameaddedtobuffer");for(let e of i)e&&setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this)}),0)},i=()=>{this.isDisposed&&this.disposed||(this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.isDisposed&&this.disposed||(this._bOpen&&this.isFetchingLoopStarted()?(t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,ue._onLog&&ue._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(ue._onLog&&ue._onLog("DCE: stop fetching loop: "+Date.now()),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1,this._recordedStates.fetchingLoopStart=!1)}getFrameFromBuffer(e){return this._frameQueue&&this._frameQueue.length?e?ee.getId()>=0))}getSelectedDrawingItems(){return this._drawingLayersManager.getSelectedDrawingItems()}createDrawingStyle(e){return this._drawingLayersManager.createDrawingStyle(e)}getDrawingStyle(e){return this._drawingLayersManager.getDrawingStyle(e)}getDrawingStyles(){return this._drawingLayersManager.getDrawingStyles()}updateDrawingStyle(e,t){return this._drawingLayersManager.updateDrawingStyle(e,t)}clearDrawingLayers(){const e=this.getDrawingLayers();for(let t of e)this.deleteDrawingLayer(t.getId())}showTip(e,t,i,r,n=3e3,s=!0){this._assertOpen(),this._tipArgs.x=e,this._tipArgs.y=t,this._tipArgs.width=i,this._tipArgs.autoShowSuggestedTip=!!s,this._drawingLayerOfTip||(this._drawingLayerOfTip=this._createDrawingLayer(-1)),this._tipStyleId||(this._tipStyleId=this.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip.clearDrawingItems();const o=new ne(r||"",e,t,i,this._tipStyleId);o._fabricObject.paddingTop=15,o._fabricObject.calcTextHeight=function(){for(var e=0,t=0,i=this._textLines.length;t0&&(this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}_hideTip(){this._drawingLayerOfTip&&(this.deleteDrawingLayer(this._drawingLayerOfTip.getId()),this._drawingLayerOfTip=null,this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId))}hideTip(){this._hideTip(),this._tipArgs.x=null,this._tipArgs.y=null,this._tipArgs.width=null,this._tipArgs.autoShowSuggestedTip=null}updateTipMessage(e){if(!this._drawingLayerOfTip)throw new Error("The Tip is not showing.");this._drawingLayerOfTip.getDrawingItems()[0].setAttribute("text",e),this._drawingLayerOfTip.renderAll(),this._tipArgs.duration>0&&(this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId),this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}suggestTip(e,t){this._tipArgs.autoShowSuggestedTip&&(this._drawingLayerOfTip?this.updateTipMessage(t):void 0!==this._tipArgs.x&&this.showTip(this._tipArgs.x,this._tipArgs.y,this._tipArgs.width,t,this._tipArgs.duration)),this.onTipSuggested&&setTimeout((()=>{this.isDisposed&&this.disposed||this.onTipSuggested.apply(this,[e,t])}),0)}_createControler(){if(this._controler||(this._controler=new ae(this)),this._controler)return this._controler}_destroyControler(){this._controler=null}setOriginalImage(e,t,i){if(!e||!t||!i)throw new Error("Invalid arguments");this._originalImageData={imageData:e,width:t,height:i};let r=this._cvsOriginalImage;r||(r=document.createElement("canvas"),r.style.position="absolute",r.style.width="100%",r.style.height="100%",r.style.left="0",r.style.top="0",r.style.backgroundColor="white",r.style.objectFit="contain",this._cvsOriginalImage=r),r.width===t&&r.height===i||(r.width=t,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),e instanceof Uint8Array||e instanceof Uint8ClampedArray?(e instanceof Uint8Array&&(e=new Uint8ClampedArray(e.buffer)),n.putImageData(new ImageData(e,t,i),0,0)):e instanceof HTMLCanvasElement&&n.drawImage(e,0,0),document.body.contains(r)&&""===r.style.display&&this._updateDrawingLayersSize({width:t,height:i,objectFit:"contain"})}getOriginalImage(){return this._originalImageData?Object.assign({},this._originalImageData):null}async deleteOriginalImage(){await this.hideOriginalImage(),this._cvsOriginalImage&&(this._cvsOriginalImage.remove(),this._cvsOriginalImage=null),this._originalImageData=null}_showOriginalImageCvs(){this._cvsOriginalImage&&"none"==this._cvsOriginalImage.style.display&&(this._cvsOriginalImage.style.display="")}_hideOriginalImageCvs(){this._cvsOriginalImage&&(this._cvsOriginalImage.style.display="none")}showOriginalImage(){if(!this._originalImageData)throw new Error("No original image is set.");const e=this._cvsOriginalImage;if(""===e.style.display&&document.body.contains(e))return;const{width:t,height:i}=this._originalImageData;if(this._updateDrawingLayersSize({width:t,height:i,objectFit:"contain"}),this._bOpen&&(this._video&&!this._video.paused&&this._video.pause(),this._bFetchingLoopStarted&&(this.stopFetchingLoop(),this._recordedStates.fetchingLoopStart=!0),this.ifShowScanRegionMask&&this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this.ifShowScanRegionLaser&&this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none"),this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none"),this._selCam&&(this._selCam.parentElement.style.display="none")),!document.body.contains(e))if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e)}this._showOriginalImageCvs()}async _hideOriginalImage(e){this._originalImageData&&this._cvsOriginalImage&&"none"!==this._cvsOriginalImage.style.display&&(this._updateDrawingLayersSize(),this._bOpen&&e&&(this._video&&this._recordedStates.videoPlaying&&await this.play(null,null,null,{notTriggerSingleFrameClick:!0}),this._recordedStates.fetchingLoopStart&&!this.singleFrameMode&&this.startFetchingLoop(),this.ifShowScanRegionMask&&this._cvsScanRegion&&this._recordedStates.maskShow&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this._divScanLight&&this._recordedStates.laserShow&&this.showScanRegionLaser(),this._cvsViewDecorator&&this._recordedStates.decoratorShow&&this.showViewDecorator(),this._scanRegionOverlayContainer&&this._recordedStates.overlayShow&&this.showScanRegionOverlays()),this._selCam&&(this._selCam.parentElement.style.display=""),this._hideOriginalImageCvs())}async hideOriginalImage(){return this._hideOriginalImage(!0)}dispose(e){this.UIElement&&(this._uiOriginalState&&this._uiOriginalState.inDom?this.UIElement.style.display=this._uiOriginalState.display:this.UIElement.style.display="none"),this.clearDrawingLayers(),this.close(),this.forceLoseContext(),this.setViewDecorator(null,null),this._scanRegionOverlayContainer&&this._scanRegionOverlayContainer.remove(),this._arrScanRegionOverlays.length=0,e&&this.UIElement&&this.UIElement.remove(),this.__proto__=null;for(let e in this)delete this[e];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"isDisposed",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}ue._jsVersion="3.3.1",ue._jsEditVersion="20230217",ue._version="JS "+ue._jsVersion+"."+ue._jsEditVersion,ue.browserInfo=Y,ue._hasEngineResourceLoaded=!1,ue._engineResourcePath=J,ue._defaultUIElementURL="@engineResourcePath/dce.ui.html";const de={DT_Arc:class extends q{constructor(e,t,i,r,n,s){super(new j.Circle({left:e,top:t,radius:i,startAngle:r,endAngle:n}),s),this._mediaType="arc"}},DT_Polygon:ie,DT_Rect:class extends q{constructor(e,t,i,r,n){super(new j.Rect({left:e,top:t,width:i,height:r}),n)}},DT_Image:class extends q{constructor(e,t,i,r){super(new j.Image(e,{left:t,top:i}),r),this.image=e}_extendSet(e,t){if("image"===e){if(t instanceof HTMLImageElement)return this._fabricObject.setElement(t),this.image=t,!0;if(t instanceof HTMLCanvasElement){const e=new Image;return e.src=t.toDataURL(),this._fabricObject.setElement(e),this.image=t,!0}throw new Error("Unsupported value.")}}_extendGet(e){if("image"===e)return this.image}},DT_Text:ne,DT_Line:class extends ie{constructor(e,t,i){super([e,t],i),this._mediaType="line"}_extendSet(e,t){if("startPoint"===e||"endPoint"===e){t="startPoint"===e?[t,this.get("endPoint")]:[this.get("startPoint"),t];const i=this._fabricObject;if(i.group){const e=i.group;i.points=t.map((t=>({x:t.x-e.left-e.width/2,y:t.y-e.top-e.height/2}))),e.addWithUpdate()}else i.points=t;const r=i.points.length-1;return i.controls=i.points.reduce((function(e,t,i){return e["p"+i]=new j.Control({positionHandler:Q,actionHandler:te(i>0?i-1:r,ee),actionName:"modifyPolygon",pointIndex:i}),e}),{}),i._setPositionDimensions({}),!0}}_extendGet(e){if("startPoint"===e||"endPoint"===e){const t=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let e in i.oCoords)t.push({x:i.oCoords[e].x,y:i.oCoords[e].y});else for(let e of i.points){let r=e.x-i.pathOffset.x,n=e.y-i.pathOffset.y;const s=j.util.transformPoint({x:r,y:n},i.calcTransformMatrix());t.push({x:s.x,y:s.y})}return"startPoint"===e?t[0]:t[1]}}},DT_Group:class extends q{constructor(e){super(new j.Group(e.map((e=>e._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.styleSelector="selected";const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.styleSelector="default";const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)}))}getChildItems(){return this._fabricObject._objects.map((e=>e.getDrawingItem()))}addChildItem(e){if(!e||!e.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"add"):this._fabricObject.addWithUpdate(e._getFabricObject())}removeChildItem(e){e&&e.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"remove"):this._fabricObject.removeWithUpdate(e._getFabricObject()))}}};function fe(e,t,i){return(i.x-e.x)*(t.y-e.y)==(t.x-e.x)*(i.y-e.y)&&Math.min(e.x,t.x)<=i.x&&i.x<=Math.max(e.x,t.x)&&Math.min(e.y,t.y)<=i.y&&i.y<=Math.max(e.y,t.y)}function ge(e){return Math.abs(e)<1e-6?0:e<0?-1:1}function _e(e,t,i,r){let n=e[0]*(i[1]-t[1])+t[0]*(e[1]-i[1])+i[0]*(t[1]-e[1]),s=e[0]*(r[1]-t[1])+t[0]*(e[1]-r[1])+r[0]*(t[1]-e[1]);return!((n^s)>=0&&0!==n&&0!==s)&&(n=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),s=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),!((n^s)>=0&&0!==n&&0!==s))}class pe extends L{constructor(){super(),this._barcodeFillStyle="rgba(254,180,32,0.3)",this._barcodeStrokeStyle="rgba(254,180,32,0.9)",this._barcodeLineWidth=1,this._barcodeFillStyleBeforeVerification="rgba(248,252,0,0.2)",this._barcodeStrokeStyleBeforeVerification="transparent",this._barcodeLineWidthBeforeVerification=2,this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${ue.getVersion()})`}static _fireHTTPSWarnning(){pe.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{pe.onWarning&&pe.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return ue.testCameraAccess()}_fireResolutionWarning(){if(!this.singleFrameMode&&this.onWarning&&this.dce.isOpen()){const e=this.dce.getConstraints();e&&e.width<1280&&e.height<720&&setTimeout((()=>{this.onWarning&&this.onWarning({id:3,message:"Camera resolution too low, please use a higher resolution (720P or better)."})}),0)}}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}get video(){return this.dce&&this.dce.video}set videoSrc(e){this.dce&&(this.dce.videoSrc=e)}get videoSrc(){return this.dce&&this.dce.videoSrc}set onTipSuggested(e){this.dce&&(this.dce.onTipSuggested=e)}get onTipSuggested(){return this.dce&&this.dce.onTipSuggested}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set barcodeFillStyle(e){this._barcodeFillStyle=e,this.dce&&this.dce.updateDrawingStyle(3,{fillStyle:e})}get barcodeFillStyle(){return this._barcodeFillStyle}set barcodeStrokeStyle(e){this._barcodeStrokeStyle=e,this.dce&&this.dce.updateDrawingStyle(3,{strokeStyle:e})}get barcodeStrokeStyle(){return this._barcodeStrokeStyle}set barcodeLineWidth(e){this._barcodeLineWidth=e,this.dce&&this.dce.updateDrawingStyle(3,{lineWidth:e})}get barcodeLineWidth(){return this._barcodeLineWidth}set barcodeFillStyleBeforeVerification(e){this._barcodeFillStyleBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{fillStyle:e})}get barcodeFillStyleBeforeVerification(){return this._barcodeFillStyleBeforeVerification}set barcodeStrokeStyleBeforeVerification(e){this._barcodeStrokeStyleBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{strokeStyle:e})}get barcodeStrokeStyleBeforeVerification(){return this._barcodeStrokeStyleBeforeVerification}set barcodeLineWidthBeforeVerification(e){this._barcodeLineWidthBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{lineWidth:e})}get barcodeLineWidthBeforeVerification(){return this._barcodeLineWidthBeforeVerification}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.framePixelFormat=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(L._onLog&&L._onLog("createDCEInstance()"),ue.defaultUIElementURL=null,this.dce=await ue.createInstance(),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=de,["iPhone","iPad","Android","HarmonyOS"].includes(L.browserInfo.OS)||this.dce.setResolution(1920,1080),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"}),this.barcodeLineWidth=this._barcodeLineWidth,this.dce.on("cameraChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async t=>{if(!t)return;if(!t.data)return;let i;this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:r,sx:n,sy:s,width:o,height:a,stride:h,pixelFormat:l,timeStamp:c,_sWidth:u,_sHeight:d}=t,f={timeStamp:c};if("grey"===l)i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_GrayScaled,0,f);else if("rgba"===l)i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_ABGR_8888,0,f);else{if("bgra"!==l)throw new Error(`Pixel format '${l}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_ARGB_8888,0,f)}if(await this.clearMapDecodeRecord(),L.recalculateResultLocation(i,n,s,u,d,o,a),this._drawResults(i),this.onFrameRead&&this.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(i);this.onFrameRead(e)}if(this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of i)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))})))}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new pe;t._instanceID=await pe.createInstanceInWorker(!0),await t.createDCEInstance(),"string"==typeof e&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return await t.dce.setUIElement(pe.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),pe._fireHTTPSWarnning(),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const i=this.dce._getVideoData(null,{region:t});return this._decode_DCEFrame(i)}async updateRuntimeSettings(t){let i;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=0,i.localizationModes=[2,0,0,0,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=9}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=512,i.deblurLevel=3,i.localizationModes=[2,16,0,0,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=9,i.timeout=1e5}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=512,i.deblurLevel=5,i.scaleDownThreshold=1e5,i.localizationModes=[2,16,4,8,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=9,i.timeout=1e5}else if("single"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region)}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=0,i.deblurLevel=7,i.scaleDownThreshold=1e5,i.localizationModes=[2,8,0,0,0,0,0,0],i.minResultConfidence=0,i.barcodeZoneMinDistanceToImageBorders=9,i.timeout=1e5}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,i=await this.getRuntimeSettings(),i.barcodeFormatIds=e.barcodeFormatIds,i.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(i.region=e.region),i.expectedBarcodesCount=0,i.scaleDownThreshold=1e5,i.localizationModes=[2,8,0,0,0,0,0,0],i.barcodeZoneMinDistanceToImageBorders=9,i.timeout=1e5}else i=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(i=JSON.parse(JSON.stringify(t)),i.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(i.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!L._bUseFullFeature){if(0!=(i.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=i.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=i.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=i.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(i=>{if(i.success){try{this._handleRetJsonString(i.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(i)}})})),"string"==typeof t&&["speed","balance","coverage","dense","distance"].includes(t)&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","1"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","0"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","0"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){const t=await this.dce.selectCamera(e);return this._fireResolutionWarning(),t}getResolution(){return this.dce.getResolution()}async setResolution(e,t){const i=await this.dce.setResolution(e,t);return this._fireResolutionWarning(),i}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}getVideoFit(){return this.dce&&this.dce.getVideoFit()}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}set ifSaveLastUsedCamera(e){this.dce&&(this.dce.ifSaveLastUsedCamera=e)}get ifSaveLastUsedCamera(){return this.dce&&this.dce.ifSaveLastUsedCamera}set ifSkipCameraInspection(e){this.dce&&(this.dce.ifSkipCameraInspection=e)}get ifSkipCameraInspection(){return this.dce&&this.dce.ifSkipCameraInspection}stop(){this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.dce.stop(),this.dce.ifShowScanRegionLaser=!1,this.dce.hideViewDecorator(),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this.dce.pause()}async play(e,t,i){this.dce.ifShowScanRegionLaser=!0;const r=await this.dce.play(e,t,i);return this._fireResolutionWarning(),r}pauseScan(e){this._assertOpen(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}getColorTemperature(){return this.dce.getColorTemperature()}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}getExposureCompensation(){return this.dce.getExposureCompensation()}async setZoom(e){return this.dce.setZoom(e)}getZoomSettings(){return this.dce.getZoomSettings()}resetZoom(){return this.dce.resetZoom()}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}getFocusSettings(){return this.dce.getFocusSettings()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(!this.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return L._onLog&&L._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));L._onLog&&L._onLog("======= once read ======="),L._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return L._onLog&&L._onLog("Get invalid frame."),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{t._bUseWebGL||"grey"!==t.pixelFormat||(this.dce.framePixelFormat="rgba");let i=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:r,sx:n,sy:s,width:o,height:a,stride:h,pixelFormat:l,timeStamp:c,_sWidth:u,_sHeight:d}=t,f={timeStamp:c};if("grey"===l)i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_GrayScaled,0,f);else if("rgba"===l)i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_ABGR_8888,0,f);else{if("bgra"!==l)throw new Error(`Pixel format '${l}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,o,a,h,e.EnumImagePixelFormat.IPF_ARGB_8888,0,f)}if(L.recalculateResultLocation(i,n,s,u,d,o,a),0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(i),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration)),this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan&&(this.autoZoom||this.autoFocus||this.autoSuggestTip))if(i.length)this.autoZoomInFrameArray.length=0,this.autoZoomOutFrameCount=0,this.frameArrayInIdealZoom.length=0,this.suggestTipFrameArray.length=0,this.autoZoom&&this.autoFocus&&(this.nextActionInIdealZoom="focus"),this.autoFocusFrameArray.length=0,this.noIntermediateResultsCount=0;else{const t=await this.getIntermediateResults(),i=(e,t,i,r,n,s,o)=>{let a=s/r,h=o/n;e.x1=e.x1/a+t,e.x2=e.x2/a+t,e.x3=e.x3/a+t,e.x4=e.x4/a+t,e.y1=e.y1/h+i,e.y2=e.y2/h+i,e.y3=e.y3/h+i,e.y4=e.y4/h+i},r=t=>{if(!t)return null;const r={};let h,l,c,f,g;{const e=this.video.videoWidth*(1-this.autoZoomDetectionArea)/2,t=this.video.videoWidth*(1+this.autoZoomDetectionArea)/2,i=t,r=e,n=this.video.videoHeight*(1-this.autoZoomDetectionArea)/2,s=n,o=this.video.videoHeight*(1+this.autoZoomDetectionArea)/2;g={x1:e,x2:t,x3:i,x4:r,y1:n,y2:s,y3:o,y4:o}}const _=(e,t)=>{const i=(e,t)=>{if(!e&&!t)throw new Error("Invalid arguments.");return function(e,t,i){let r=!1;const n=e.length;if(n<=2)return!1;for(let s=0;s0!=ge(a.y-i)>0&&ge(t-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}([{x:t.x1,y:t.y1},{x:t.x2,y:t.y2},{x:t.x3,y:t.y3},{x:t.x4,y:t.y4}],e.x,e.y)},r=(e,t)=>!!(_e([e[0],e[1]],[e[2],e[3]],[t.x1,t.y1],[t.x2,t.y2])||_e([e[0],e[1]],[e[2],e[3]],[t.x2,t.y2],[t.x3,t.y3])||_e([e[0],e[1]],[e[2],e[3]],[t.x3,t.y3],[t.x4,t.y4])||_e([e[0],e[1]],[e[2],e[3]],[t.x4,t.y4],[t.x1,t.y1]));return!!(i({x:e.x1,y:e.y1},t)||i({x:e.x2,y:e.y2},t)||i({x:e.x3,y:e.y3},t)||i({x:e.x4,y:e.y4},t))||(!!(i({x:t.x1,y:t.y1},e)||i({x:t.x2,y:t.y2},e)||i({x:t.x3,y:t.y3},e)||i({x:t.x4,y:t.y4},e))||!!(r([t.x1,t.y1,t.x2,t.y2],e)||r([t.x2,t.y2,t.x3,t.y3],e)||r([t.x3,t.y3,t.x4,t.y4],e)||r([t.x4,t.y4,t.x1,t.y1],e)))},p=[];for(let r of t){if(r.resultType!==e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE)continue;const t=r.scaleDownRatio;for(let e of r.results){if(!e)continue;const r={x1:e.x1=e.x1*t,x2:e.x2=e.x2*t,x3:e.x3=e.x3*t,x4:e.x4=e.x4*t,y1:e.y1=e.y1*t,y2:e.y2=e.y2*t,y3:e.y4=e.y3*t,y4:e.y4=e.y4*t};i(r,n,s,u,d,o,a),_(g,r)&&p.push(e)}}const m=(t=>{if(!t||!t.length)return null;const i=e=>{const t=(e.x1+e.x2+e.x3+e.x4)/4,i=(e.y1+e.y2+e.y3+e.y4)/4;return(t-o/2)*(t-o/2)+(i-a/2)*(i-a/2)};let r,n=t.filter((t=>t.barcodeFormat==e.EnumBarcodeFormat.BF_QR_CODE||t.barcodeFormat==e.EnumBarcodeFormat.BF_DATAMATRIX));if(n.length||(n=t.filter((t=>t.barcodeFormat==e.EnumBarcodeFormat.BF_ONED)),n.length||(n=t)),!n.length)return null;r=n[0];let s=i(r);if(1!=n.length)for(let e=1;e1.1*r.confidence?(r=n[e],s=t):n[e].confidence>.9*r.confidence&&t!0===e)).length>=this.suggestTipFrameLimit[1]){this.suggestTipFrameArray.length=0;const e=h.x3-h.x1,t=h.y3-h.y1;h.result.moduleSizet?e>o*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):e>.6*o&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."):e<=t&&(t>a*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):t>.6*a&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."))}if(this.autoZoom){const e=this.autoZoomIdealArea[1];let t=(1-this.autoZoomTargetBorder)/2;const r=h.x1/u,l=(u-h.x3)/u,c=h.y1/d,f=(d-h.y3)/d;if(r>e&&l>e&&c>e&&f>e&&h.result.moduleSize{}))),this.autoZoomInFrameArray.filter((e=>!0===e)).length>=this.autoZoomInFrameLimit[1]){this.autoZoomInFrameArray.length=0;const e=[(.5-t)/(.5-r),(.5-t)/(.5-l),(.5-t)/(.5-c),(.5-t)/(.5-f)].filter((e=>e>0)),i=Math.min(...e,this.autoZoomInIdealModuleSize/h.result.moduleSize),n=this.dce.getZoomSettings().factor;let s=Math.max(Math.pow(n*i,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);s=Math.min(s,i);const o=n*s;await this.setZoom({factor:o}),this.dce.clearFrameBuffer()}}else if(this.autoZoomInFrameArray.length=0,this.frameArrayInIdealZoom.push(!0),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.frameArrayInIdealZoom.filter((e=>!0===e)).length>=this.frameLimitInIdealZoom[1])if(this.frameArrayInIdealZoom.length=0,"focus"===this.nextActionInIdealZoom&&this.autoFocus){i(h,n,s,u,d,o,a);try{await this.setFocus({mode:"manual",area:{centerPoint:{x:(h.x1+h.x3)/2+"px",y:(h.y1+h.y3)/2+"px"},width:h.x3-h.x1+"px",height:h.y3-h.y1+"px"}})}catch(e){}this.dce.clearFrameBuffer(),this.nextActionInIdealZoom="zoomOut"}else{if("zoomOut"!==this.nextActionInIdealZoom&&this.autoFocus)throw new Error("Invalid action.");if(this.enableZoomOutInIdealZoom){t=this.autoZoomIdealArea[1]+this.autoZoomOutStepRate_2;const e=[(.5-t)/(.5-r),(.5-t)/(.5-l),(.5-t)/(.5-c),(.5-t)/(.5-f)].filter((e=>e>0));let i=Math.min(...e)*this.dce.getZoomSettings().factor;await this.setZoom({factor:i}),this.dce.clearFrameBuffer(),this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((e=>{})))}}}else if(this.autoFocus&&(this.autoFocusFrameArray.push(!0),this.autoFocusFrameArray.splice(0,this.autoFocusFrameArray.length-this.autoFocusFrameLimit[0]),this.autoFocusFrameArray.filter((e=>!0===e)).length>=this.autoFocusFrameLimit[1])){this.autoFocusFrameArray.length=0;try{i(h,n,s,u,d,o,a),await this.setFocus({mode:"manual",area:{centerPoint:{x:(h.x1+h.x3)/2+"px",y:(h.y1+h.y3)/2+"px"},width:h.x3-h.x1+"px",height:h.y3-h.y1+"px"}})}catch(e){}this.dce.clearFrameBuffer()}}else if(this.noIntermediateResultsCount++,this.suggestTipFrameArray.push(!1),this.autoZoom){if(this.autoZoomInFrameArray.push(!1),this.autoZoomInFrameArray.splice(0,this.autoZoomInFrameArray.length-this.autoZoomInFrameLimit[0]),this.autoZoomOutFrameCount++,this.frameArrayInIdealZoom.push(!1),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.autoZoomOutFrameCount>=this.autoZoomOutFrameLimit){this.autoZoomOutFrameCount=0;const e=this.getZoomSettings().factor;if(e>this.autoZoomOutMinValue){const t=Math.max((e-1)*this.autoZoomOutStepRate,this.autoZoomOutMinStep),i=Math.max(e-t,this.autoZoomOutMinValue);await this.setZoom({factor:i}),this.dce.clearFrameBuffer()}}this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((e=>{})))}else this.autoFocus&&(this.autoFocusFrameArray.length=0,this.setFocus({mode:"continuous"}).catch((e=>{})))}return i})().then((e=>{if(L._onLog&&L._onLog(e),this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;const r=()=>{let r=0;if(this.region instanceof Array){let n=0,s=0;n=i+1>=this.region.length?0:i+1,s=n+1>=this.region.length?0:n+1,r=e[n]&&e[n].length&&t[s]&&t[s].length?Math.min(...e[n])-Math.max(...t[s]):0}else if(t&&t.length){let i=Math.min(...e),n=Math.max(...t);i&&n&&(r=i-n)}else r=0;return r>0?r:0};(()=>{if(this.region instanceof Array){for(e[i]&&e[i]instanceof Array||(e[i]=[]);e[i].length>=5;)e[i].shift();e[i].push(this._lastInnerDecodeDuration)}else{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=r()+this.intervalTime,L._onLog&&L._onLog("Next fetching frame loop interval: "+this._intervalGetVideoFrame)}if(this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onFrameRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){L._onLog&&L._onLog("Get frame in parallel.");let t=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,t||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;e=this.dce.getFrameFromBuffer();const i=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};i(e)}else L._onLog&&L._onLog("Get frame in serial."),this.dce.stopFetchingLoop(),e=this.dce.getFrame();return e}async open(){this._bindUI();const e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}close(){this.dce.close(),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}hide(){this.dce.close(!0),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}showTip(e,t,i,r,n=3e3,s=!0){this.dce&&this.dce.showTip(e,t,i,r,n,s)}hideTip(){this.dce&&this.dce.hideTip()}updateTipMessage(e){this.dce&&this.dce.updateTipMessage(e)}async enableTapToFocus(){this.dce&&this.dce.enableTapToFocus()}disableTapToFocus(){this.dce&&this.dce.disableTapToFocus()}isTapToFocusEnabled(){return this.dce.isTapToFocusEnabled()}transformCoord(e){if(!this.isOpen())throw new Error("Unavailable when the camera is not open.");if(this.singleFrameMode&&!this.dce._cvsSingleFrameMode)throw new Error("No image is selected. ");const t=this.dce._elContainer.getBoundingClientRect();let i,r,n,s,o,a=t.left,h=t.top,l=a+window.scrollX,c=h+window.scrollY;this.singleFrameMode?(i=this.dce._cvsSingleFrameMode.width,r=this.dce._cvsSingleFrameMode.height,n=parseFloat(window.getComputedStyle(this.dce._cvsSingleFrameMode).width),s=parseFloat(window.getComputedStyle(this.dce._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,r=this.video.videoHeight,n=parseFloat(window.getComputedStyle(this.dce._elContainer).width),s=parseFloat(window.getComputedStyle(this.dce._elContainer).height),o=this.getVideoFit());const u=n/s,d=i/r;let f,g,_,p,m=1;if("contain"===o)u{let e=!1;if(h)try{(await n.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===s.browser&&s.version>66||"Safari"===s.browser&&s.version>13||"OPR"===s.browser&&s.version>43||"Edge"===s.browser&&s.version;const c=(()=>{if(!e&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),u=" is not allowed to change after `createInstance` or `loadWasm` is called.",d=!e&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",f=!e&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",g=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let i=0;ie&&"object"==typeof e&&"function"==typeof e.then;class w extends Promise{constructor(e){let t,i;super(((e,r)=>{t=e,i=r})),this._s="pending",this.resolve=e=>{this.isPending&&(S(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,S(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}var b=function(){this.init()};b.prototype={init:function(){var e=this||C;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||C;if(e=parseFloat(e),t.ctx||R(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,C.ctx.currentTime);for(var i=0;i=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,R()),e},codecs:function(e){return(this||C)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||C;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||C,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var i=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",n=r.match(/OPR\/([0-6].)/g),s=n&&parseInt(n[0].split("/")[1],10)<33,o=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),a=r.match(/Version\/(.*?) /),h=o&&a&&parseInt(a[1],10)<15;return e._codecs={mp3:!(s||!i&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!i,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(h||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(h||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||C;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(i){for(;e._html5AudioPool.length0?o._seek:i._sprite[e][0]/1e3),l=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-h),c=1e3*l/Math.abs(o._rate),u=i._sprite[e][0]/1e3,d=(i._sprite[e][0]+i._sprite[e][1])/1e3;o._sprite=e,o._ended=!1;var f=function(){o._paused=!1,o._seek=h,o._start=u,o._stop=d,o._loop=!(!o._loop&&!i._sprite[e][2])};if(!(h>=d)){var g=o._node;if(i._webAudio){var _=function(){i._playLock=!1,f(),i._refreshBuffer(o);var e=o._muted||i._muted?0:o._volume;g.gain.setValueAtTime(e,C.ctx.currentTime),o._playStart=C.ctx.currentTime,void 0===g.bufferSource.start?o._loop?g.bufferSource.noteGrainOn(0,h,86400):g.bufferSource.noteGrainOn(0,h,l):o._loop?g.bufferSource.start(0,h,86400):g.bufferSource.start(0,h,l),c!==1/0&&(i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c)),t||setTimeout((function(){i._emit("play",o._id),i._loadQueue()}),0)};"running"===C.state&&"interrupted"!==C.ctx.state?_():(i._playLock=!0,i.once("resume",_),i._clearTimer(o._id))}else{var p=function(){g.currentTime=h,g.muted=o._muted||i._muted||C._muted||g.muted,g.volume=o._volume*C.volume(),g.playbackRate=o._rate;try{var r=g.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(i._playLock=!0,f(),r.then((function(){i._playLock=!1,g._unlocked=!0,t?i._loadQueue():i._emit("play",o._id)})).catch((function(){i._playLock=!1,i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),o._ended=!0,o._paused=!0}))):t||(i._playLock=!1,f(),i._emit("play",o._id)),g.playbackRate=o._rate,g.paused)return void i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||o._loop?i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c):(i._endTimers[o._id]=function(){i._ended(o),g.removeEventListener("ended",i._endTimers[o._id],!1)},g.addEventListener("ended",i._endTimers[o._id],!1))}catch(e){i._emit("playerror",o._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=i._src,g.load());var m=window&&window.ejecta||!g.readyState&&C._navigator.isCocoonJS;if(g.readyState>=3||m)p();else{i._playLock=!0,i._state="loading";var v=function(){i._state="loaded",p(),g.removeEventListener(C._canPlayEvent,v,!1)};g.addEventListener(C._canPlayEvent,v,!1),i._clearTimer(o._id)}}return o._id}i._ended(o)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),r=0;r=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(i=t?r._soundById(t):r._sounds[0])?i._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,n)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var a=0;a0?r/l:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=h*n,a=Math.round(100*a)/100,a=h<0?Math.max(i,a):Math.min(i,a),o._webAudio?e._volume=a:o.volume(a,e._id,!0),s&&(o._volume=a),(it&&a>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,o.volume(i,e._id),o._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,i=t._soundById(e);return i&&i._interval&&(t._webAudio&&i._node.gain.cancelScheduledValues(C.ctx.currentTime),clearInterval(i._interval),i._interval=null,t.volume(i._fadeTo,e),i._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,i,r=this,n=arguments;if(0===n.length)return r._loop;if(1===n.length){if("boolean"!=typeof n[0])return!!(i=r._soundById(parseInt(n[0],10)))&&i._loop;e=n[0],r._loop=e}else 2===n.length&&(e=n[0],t=parseInt(n[1],10));for(var s=r._getSoundIds(t),o=0;o=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else 2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if("number"!=typeof e)return(i=r._soundById(t))?i._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,n)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var a=0;a=0?t=parseInt(r[0],10):i._sounds.length&&(t=i._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==i._state||i._playLock))return i._queue.push({event:"seek",action:function(){i.seek.apply(i,r)}}),i;var o=i._soundById(t);if(o){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var a=i.playing(t)?C.ctx.currentTime-o._playStart:0,h=o._rateSeek?o._rateSeek-o._seek:0;return o._seek+(h+a*Math.abs(o._rate))}return o._node.currentTime}var l=i.playing(t);l&&i.pause(t,!0),o._seek=e,o._ended=!1,i._clearTimer(t),i._webAudio||!o._node||isNaN(o._node.duration)||(o._node.currentTime=e);var c=function(){l&&i.play(t,!0),i._emit("seek",t)};if(l&&!i._webAudio){var u=function(){i._playLock?setTimeout(u,0):c()};setTimeout(u,0)}else c()}return i},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var r=0;r=0&&C._howls.splice(r,1);var n=!0;for(i=0;i=0){n=!1;break}return I&&n&&delete I[e._src],C.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,r){var n=this["_on"+e];return"function"==typeof t&&n.push(r?{id:i,fn:t,once:r}:{id:i,fn:t}),this},off:function(e,t,i){var r=this,n=r["_on"+e],s=0;if("number"==typeof t&&(i=t,t=null),t||i)for(s=0;s=0;s--)n[s].id&&n[s].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(r,n[s].fn),0),n[s].once&&r.off(e,n[s].fn,n[s].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var t=this,i=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(i<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i=0;if(!e.bufferSource)return this;if(C._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=C._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(C._navigator&&C._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var T=function(e){this._parent=e,this.init()};T.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++C._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=C._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===C.ctx.createGain?C.ctx.createGainNode():C.ctx.createGain(),e._node.gain.setValueAtTime(i,C.ctx.currentTime),e._node.paused=!0,e._node.connect(C.masterGain)):C.noAudio||(e._node=C._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(C._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*C.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++C._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(C._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var I={},A=function(e){var t=e._src;if(I[t])return e._duration=I[t].duration,void D(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(I[t._src]=e,D(t,e)):i()};"undefined"!=typeof Promise&&1===C.ctx.decodeAudioData.length?C.ctx.decodeAudioData(e).then(r).catch(i):C.ctx.decodeAudioData(e,r,i)},D=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},R=function(){if(C.usingWebAudio){try{"undefined"!=typeof AudioContext?C.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?C.ctx=new webkitAudioContext:C.usingWebAudio=!1}catch(e){C.usingWebAudio=!1}C.ctx||(C.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(C._navigator&&C._navigator.platform),t=C._navigator&&C._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var r=/safari/.test(C._navigator&&C._navigator.userAgent.toLowerCase());C._navigator&&!r&&(C.usingWebAudio=!1)}C.usingWebAudio&&(C.masterGain=void 0===C.ctx.createGain?C.ctx.createGainNode():C.ctx.createGain(),C.masterGain.gain.setValueAtTime(C._muted?0:C._volume,C.ctx.currentTime),C.masterGain.connect(C.ctx.destination)),C._setup()}};!function(e,t,i,r){var n;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},e.prototype.pos=function(e,i,r){var n=this;return n.ctx&&n.ctx.listener?(i="number"!=typeof i?n._pos[1]:i,r="number"!=typeof r?n._pos[2]:r,"number"!=typeof e?n._pos:(n._pos=[e,i,r],void 0!==n.ctx.listener.positionX?(n.ctx.listener.positionX.setTargetAtTime(n._pos[0],t.ctx.currentTime,.1),n.ctx.listener.positionY.setTargetAtTime(n._pos[1],t.ctx.currentTime,.1),n.ctx.listener.positionZ.setTargetAtTime(n._pos[2],t.ctx.currentTime,.1)):n.ctx.listener.setPosition(n._pos[0],n._pos[1],n._pos[2]),n)):n},e.prototype.orientation=function(e,i,r,n,s,o){var a=this;if(!a.ctx||!a.ctx.listener)return a;var h=a._orientation;return i="number"!=typeof i?h[1]:i,r="number"!=typeof r?h[2]:r,n="number"!=typeof n?h[3]:n,s="number"!=typeof s?h[4]:s,o="number"!=typeof o?h[5]:o,"number"!=typeof e?h:(a._orientation=[e,i,r,n,s,o],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(i,t.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(n,t.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(s,t.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(o,t.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,i,r,n,s,o),a)},i.prototype.init=(n=i.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],n.call(this,e)}),i.prototype.stereo=function(e,i){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,i)}}),r;var n=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var o=r._getSoundIds(i),a=0;a{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=M,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+u);i._license=t})(L,e)}static get productKeys(){return this._license}static set productKeys(e){L.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){L.license=e}static get organizationID(){return this._license}static set organizationID(e){L.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+u);i._sessionPassword=t})(L,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:o,worker:a,getUserMedia:h,camera:await l(),browser:s.browser,version:s.version,OS:s.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(t){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");L._engineResourcePath=(t=>{if(null==t&&(t="./"),!e){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+u);i._licenseServer=g(t)})(L,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+u);i._deviceFriendlyName=t||""})(L,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");L.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&(("colorMode"in e||"pixelFormat"in e)&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=L._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",L.engineResourcePath)}static set defaultUIElementURL(e){L._defaultUIElementURL=e}static _fireHTTPSWarnning(){L.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{L.onWarning&&L.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new x({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;L._onLog&&L._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const i=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else i||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let t=await this._decode_DCEFrame(e,{bCopyData:!1}),i=null;if(t&&t.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:h}=e;i=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(i,r,n,a,h,s,o)}if(this._drawResults(i,t),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(L._onLog&&L._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!L.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:i,sp:r,rmk:n}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,i,r=t._license||"",n=JSON.parse(JSON.stringify(t._licenseServer)),s=t._sessionPassword,o=0;if(r.startsWith("t")||r.startsWith("f"))o=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))o=1;else{o=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t;try{let e=r.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===n.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),n=g(e)}!s&&t.sessionPassword&&(s=t.sessionPassword),e=t.remark}("200001"===r||r.startsWith("200001-"))&&(n&&n.length||(r="")),r||(o=1)}if(o&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==o)throw new Error(i);o=0,console.warn(i),t._lastErrorCode=-1,t._lastErrorString=i}return 1===o&&(r="",console.warn("Applying for a public trial license ...")),{lt:o,l:r,ls:n,sp:s,rmk:e}}throw new Error("Can't preprocess license again"+u)})(L);this._pLoad.task=async(o,a)=>{let h=L.engineResourcePath+L._workerName;L.engineResourcePath.startsWith(location.origin)||(h=await fetch(h).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),L._dbrWorker=new Worker(h),L._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},L._dbrWorker.onmessage=async t=>{let i=t.data?t.data:t;switch(i.type){case"log":L._onLog&&L._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0,i.message||(i.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),i.success?(L._dbrWorker.onerror=null,L._version=i.version+"(JS "+L._jsVersion+"."+L._jsEditVersion+")",L._onLog&&L._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(t=new Error(i.message),t.stack=i.stack+"\n"+t.stack,t.ltsErrorCode=i.ltsErrorCode,r||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&L.showDialog(i.success?"warn":"error",i.message),i.success?o():a(t);break}case"task":{let e=i.id,t=i.body;try{L._taskCallbackMap.get(e)(t),L._taskCallbackMap.delete(e)}catch(t){throw L._taskCallbackMap.delete(e),t}break}default:L._onLog&&L._onLog(t)}},L._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:L.engineResourcePath,bUseFullFeature:L._bUseFullFeature,bd:L._bWasmDebug,v:L._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:s,fn:L.deviceFriendlyName,ls:i,sp:r,rmk:n})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,i)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let e=0;e{if(e==t.target){a.remove();for(let e of o)e.remove()}}));else if(!l&&e.classList.contains("dls-license-icon-close"))l=e,e.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!d&&e.classList.contains("dls-license-msg-content")){d=e;let t=i;for(;t;){let i=t.indexOf("["),r=t.indexOf("]",i),n=t.indexOf("(",r),s=t.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){e.appendChild(new Text(t));break}i>0&&e.appendChild(new Text(t.substring(0,i)));let o=document.createElement("a"),a=t.substring(i+1,r);o.innerText=a;let h=t.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),e.appendChild(o),t=t.substring(s+1)}}document.body.appendChild(a)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await L.loadWasm(),await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new L;return e._instanceID=await L.createInstanceInWorker(),L._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){L._onLog&&L._onLog("decode(source: any)"),L._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):L.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):L.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,i,r,n,s,o){return await new Promise(((a,h)=>{let l=L._nextTaskID++;L._taskCallbackMap.set(l,(e=>{if(e.success){let t,i=L._onLog?Date.now():0;L._onLog&&L._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return h(e)}if(L._onLog){let e=Date.now();L._onLog("DBR getting message from worker timestamp: "+i),L._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),L._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),L._onLog("Handling results from DBR worker costs: "+(e-i)),L._onLog("Total decoding image costs: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}})),this._timeEnterInnerDBR=Date.now(),L._onLog&&L._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),L._dbrWorker.postMessage({type:"decodeBuffer",id:l,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,orientation:s,config:o}},[e.buffer]),L._onLog&&o&&o.timeStamp&&L._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s,o){L._onLog&&L._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,i,r,n,s,o)}async decodeBuffer(e,t,i,r,n,s,o){let a;return L._onLog&&L._onLog("decodeBuffer(buffer,width,height,stride,format)"),L._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,i,r,n,s,o):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,r,n,s,o):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,i,r,n,s,o)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success){let t=JSON.parse(i.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=5,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region}else if("dense"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=9,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!L._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(v.BF_ONED|v.BF_QR_CODE|v.BF_PDF417|v.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=t.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,t.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(t.intermediateResultTypes|=y.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){i(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),L._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=M,await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=M,await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!L._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!L._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){i(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){L._onLog&&L._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(r=await function(e){return new Promise(((t,i)=>{let r=URL.createObjectURL(e),n=new Image;n.dbrObjUrl=r,n.src=r,n.onload=()=>{t(n)},n.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let n=await this._decode_Image(i||r,t);return i&&i.close(),n}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){L._onLog&&L._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let i,r,n=e instanceof HTMLImageElement?e.naturalWidth:e.width,s=e instanceof HTMLImageElement?e.naturalHeight:e.height,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(a,t)}async _decode_Canvas(e,t){if(L._onLog&&L._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if(0===e.width||0===e.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=e,this.oriCanvasData=null);let i=(e.ctx2d||e.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,e.width,e.height).data;return await this._decodeBuffer_Uint8Array(i,e.width,e.height,4*e.width,_.IPF_ABGR_8888,0,t)}async _decode_Video(e,t){if(L._onLog&&L._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let i,r,n=e.videoWidth,s=e.videoHeight,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),await this._decode_Canvas(a,t)}async _decode_DCEFrame(e,t){if(L._onLog&&L._onLog("_decode_DCEFrame(dceFrame)"),!L.isDCEFrame(e))return[];let i=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,pixelFormat:e.pixelFormat,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{width:r,height:n,colorMode:s,pixelFormat:o,stride:a,timeStamp:h}=e;let l;l=t&&t.bCopyData?new Uint8Array(e.data):e.data;let c=null;if(t?(c=JSON.parse(JSON.stringify(t)),c.timeStamp=h):c={timeStamp:h},o&&a)if("grey"===o)i=await this._decodeBuffer_Uint8Array(l,r,n,a,_.IPF_GrayScaled,0,c);else if("rgba"===o)i=await this._decodeBuffer_Uint8Array(l,r,n,a,_.IPF_ABGR_8888,0,c);else{if("bgra"!==o)throw new Error(`Pixel format '${o}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(l,r,n,a,_.IPF_ARGB_8888,0,c)}else if("grey"===s)i=await this._decodeBuffer_Uint8Array(l,r,n,r,_.IPF_GrayScaled,0,c);else if("rgba"===s)i=await this._decodeBuffer_Uint8Array(l,r,n,4*r,_.IPF_ABGR_8888,0,c);else{if("bgra"!==s)throw new Error(`Color mode '${s}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(l,r,n,4*r,_.IPF_ARGB_8888,0,c)}return i}async _decode_DSImage(e,t){if(L._onLog&&L._onLog("_decode_DSImage(dsImage)"),!L.isDSImage(e))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat.toLowerCase(),data:new Uint8Array(e.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,t)}}async _decode_FilePath(e,t){throw L._onLog&&L._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,i,r,n,s,o){if(e.length>0)for(let a of e){let e=a.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*s,e.x2*=.01*s,e.x3*=.01*s,e.x4*=.01*s,e.y1*=.01*o,e.y2*=.01*o,e.y3*=.01*o,e.y4*=.01*o);let h=s/r,l=o/n;e.x1=e.x1/h+t,e.x2=e.x2/h+t,e.x3=e.x3/h+t,e.x4=e.x4/h+t,e.y1=e.y1/l+i,e.y2=e.y2/l+i,e.y3=e.y3/l+i,e.y4=e.y4/l+i,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/n,e.y2*=100/n,e.y3*=100/n,e.y4*=100/n)}}static BarcodeReaderException(e,t){let i,r=p.DBR_UNKNOWN;return"number"==typeof e?(r=e,i=new Error(t)):i=new Error(e),i.code=r,i}_handleRetJsonString(e){let t=p;if(e.textResults){for(let t=0;t{let i=t.indexOf(":");e[t.substring(0,i)]=t.substring(i+1)})),i.exception=e}}return e.decodeRecords?this.decodeRecords=e.decodeRecords:this.decodeRecords={},this._lastErrorCode=e.exception,this._lastErrorString=e.description,e.exception&&!L._setWarnnedEx.has(e.description)&&(L._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw L.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=L._nextTaskID++;L._taskCallbackMap.set(o,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return s(e)}return n()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),L._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:r}})}))}async getModeArgument(e,t,i){return await new Promise(((r,n)=>{let s=L._nextTaskID++;L._taskCallbackMap.set(s,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return n(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),L._dbrWorker.postMessage({type:"getModeArgument",id:s,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let i of e)if(i.dataType==m.IMRDT_IMAGE)for(let e of i.results){const i=e.bytes;let r;switch(L._onLog&&L._onLog(" "+i.length+" "+i.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case _.IPF_ABGR_8888:r=new Uint8ClampedArray(i);break;case _.IPF_RGB_888:{const e=i.length/3;r=new Uint8ClampedArray(4*e);for(let t=0;t=n)break;r[o]=r[o+1]=r[o+2]=(128&t)/128*255,r[o+3]=255,t<<=1}}break}default:console.warn("unknow intermediate image",e)}if(!r)continue;let n=new ImageData(r,e.width,e.height),s=document.createElement("canvas");s.width=e.width,s.height=e.height,s.getContext("2d").putImageData(n,0,0),t.push(s)}return t}async getScanSettings(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success){let t=i.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t.autoZoom=this.autoZoom,t.autoFocus=this.autoFocus,t.autoSuggestTip=this.autoSuggestTip,e(t)}{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),L._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));if(t.autoZoom||t.autoFocus||t.autoSuggestTip){if(!L._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const e=await this.getRuntimeSettings();e.intermediateResultTypes|=y.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(e)}return t.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(t.intervalTime,0),delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),t.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=t.captureAndDecodeInParallel,delete t.captureAndDecodeInParallel),t.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=t.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=t.autoZoom,delete t.autoZoom),t.hasOwnProperty("autoFocus")&&(this.autoFocus=t.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete t.autoFocus),t.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=t.autoSuggestTip,delete t.autoFocus),await new Promise(((e,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,i(e)}})),L._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let i of e)t.push(this._cloneDecodeResults(i));return t}{let t=e,i=JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return L._onLog&&L._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));L._onLog&&L._onLog("======= once read ======="),L._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!L.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return L._onLog&&L._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(e){i=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(i&&i.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:h}=e;t=i.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(t,r,n,a,h,s,o)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t,i),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else t&&(i=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return i})().then((e=>{if(L._onLog&&L._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const i=()=>{let i=0;if(t&&t.length){let r=Math.min(...e),n=Math.max(...t);r&&n&&(i=r-n)}else i=0;return i>0?i:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),L._onLog&&L._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(L._onLog&&L._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};t(e)}else L._onLog&&L._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e,t){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const i=this._dbrDrawingLayer;e||(e=[]);let r=this._arrPolygons;for(let n=0;n{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(t),t}stopScanning(e){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[e]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(e){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(L._onLog&&L._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let e=L._nextTaskID++;L._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),L._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}L._jsVersion="9.6.10",L._jsEditVersion="20230213",L._version=`loading...(JS ${L._jsVersion}.${L._jsEditVersion})`,L._license=d,L._sessionPassword=f,L.browserInfo=s,L._workerName=`dbr-${L._jsVersion}.browser.worker.js`,L._engineResourcePath=c,L._licenseServer=[],L._deviceFriendlyName="",L._isShowRelDecodeTimeInResults=!1,L._bWasmDebug=!1,L._bNeverShowDialog=!1,L.__bUseFullFeature=!0,L._nextTaskID=0,L._taskCallbackMap=new Map,L._pLoad=new w,L._lastErrorCode=0,L._lastErrorString="",L._setWarnnedEx=new Set,L._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var F={653:(e,t,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,_,p,m,v,y,S,w,b,C,x=x||{version:"5.2.1"};if(t.fabric=x,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?x.document=document:x.document=document.implementation.createHTMLDocument(""),x.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;x.document=T.document,x.jsdomImplForWrapper=i(898).implForWrapper,x.nodeCanvas=i(245).Canvas,x.window=T,DOMParser=x.window.DOMParser}function I(e,t){var i=e.canvas,r=t.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function A(e,t){var i=t.targetCanvas.getContext("2d"),r=t.destinationWidth,n=t.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}x.isTouchSupported="ontouchstart"in x.window||"ontouchstart"in x.document||x.window&&x.window.navigator&&x.window.navigator.maxTouchPoints>0,x.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,x.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],x.DPI=96,x.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",x.commaWsp="(?:\\s+,?\\s*|,\\s*)",x.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,x.reNonWord=/[ \n\.,;!\?\-]/,x.fontPaths={},x.iMatrix=[1,0,0,1,0,0],x.svgNS="http://www.w3.org/2000/svg",x.perfLimitSizeTotal=2097152,x.maxCacheSideLimit=4096,x.minCacheSideLimit=256,x.charWidthsCache={},x.textureSize=2048,x.disableStyleCopyPaste=!1,x.enableGLFiltering=!0,x.devicePixelRatio=x.window.devicePixelRatio||x.window.webkitDevicePixelRatio||x.window.mozDevicePixelRatio||1,x.browserShadowBlurConstant=1,x.arcToSegmentsCache={},x.boundsOfCurveCache={},x.cachesBoundsOfCurve=!0,x.forceGLPutImageData=!1,x.initFilterBackend=function(){return x.enableGLFiltering&&x.isWebglSupported&&x.isWebglSupported(x.textureSize)?(console.log("max texture size: "+x.maxTextureSize),new x.WebglFilterBackend({tileSize:x.textureSize})):x.Canvas2dFilterBackend?new x.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=x),function(){function e(e,t){if(this.__eventListeners[e]){var i=this.__eventListeners[e];t?i[i.indexOf(t)]=!1:x.util.array.fill(i,!1)}}function t(e,t){var i=function(){t.apply(this,arguments),this.off(e,i)}.bind(this);this.on(e,i)}x.Observable={fire:function(e,t){if(!this.__eventListeners)return this;var i=this.__eventListeners[e];if(!i)return this;for(var r=0,n=i.length;r-1||!!t&&this._objects.some((function(t){return"function"==typeof t.contains&&t.contains(e,!0)}))},complexity:function(){return this._objects.reduce((function(e,t){return e+(t.complexity?t.complexity():0)}),0)}},x.CommonMethods={_setOptions:function(e){for(var t in e)this.set(t,e[t])},_initGradient:function(e,t){!e||!e.colorStops||e instanceof x.Gradient||this.set(t,new x.Gradient(e))},_initPattern:function(e,t,i){!e||!e.source||e instanceof x.Pattern?i&&i():this.set(t,new x.Pattern(e,i))},_setObject:function(e){for(var t in e)this._set(t,e[t])},set:function(e,t){return"object"==typeof e?this._setObject(e):this._set(e,t),this},_set:function(e,t){this[e]=t},toggle:function(e){var t=this.get(e);return"boolean"==typeof t&&this.set(e,!t),this},get:function(e){return this[e]}},r=t,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,x.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},sin:function(e){if(0===e)return 0;var t=1;switch(e<0&&(t=-1),e/h){case 1:return t;case 2:return 0;case 3:return-t}return Math.sin(e)},removeFromArray:function(e,t){var i=e.indexOf(t);return-1!==i&&e.splice(i,1),e},getRandomInt:function(e,t){return Math.floor(Math.random()*(t-e+1))+e},degreesToRadians:function(e){return e*a},radiansToDegrees:function(e){return e/a},rotatePoint:function(e,t,i){var r=new x.Point(e.x-t.x,e.y-t.y),n=x.util.rotateVector(r,i);return new x.Point(n.x,n.y).addEquals(t)},rotateVector:function(e,t){var i=x.util.sin(t),r=x.util.cos(t);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}},createVector:function(e,t){return new x.Point(t.x-e.x,t.y-e.y)},calcAngleBetweenVectors:function(e,t){return Math.acos((e.x*t.x+e.y*t.y)/(Math.hypot(e.x,e.y)*Math.hypot(t.x,t.y)))},getHatVector:function(e){return new x.Point(e.x,e.y).multiply(1/Math.hypot(e.x,e.y))},getBisector:function(e,t,i){var r=x.util.createVector(e,t),n=x.util.createVector(e,i),s=x.util.calcAngleBetweenVectors(r,n),o=s*(0===x.util.calcAngleBetweenVectors(x.util.rotateVector(r,s),n)?1:-1)/2;return{vector:x.util.getHatVector(x.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(e,t,i){var r=[],n=t.strokeWidth/2,s=t.strokeUniform?new x.Point(1/t.scaleX,1/t.scaleY):new x.Point(1,1),o=function(e){var t=n/Math.hypot(e.x,e.y);return new x.Point(e.x*t*s.x,e.y*t*s.y)};return e.length<=1||e.forEach((function(a,h){var l,c,u=new x.Point(a.x,a.y);0===h?(c=e[h+1],l=i?o(x.util.createVector(c,u)).addEquals(u):e[e.length-1]):h===e.length-1?(l=e[h-1],c=i?o(x.util.createVector(l,u)).addEquals(u):e[0]):(l=e[h-1],c=e[h+1]);var d,f,g=x.util.getBisector(u,l,c),_=g.vector,p=g.angle;if("miter"===t.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new x.Point(_.x*d*s.x,_.y*d*s.y),Math.hypot(f.x,f.y)/n<=t.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new x.Point(_.x*d*s.x,_.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(e,t,i){return i?new x.Point(t[0]*e.x+t[2]*e.y,t[1]*e.x+t[3]*e.y):new x.Point(t[0]*e.x+t[2]*e.y+t[4],t[1]*e.x+t[3]*e.y+t[5])},makeBoundingBoxFromPoints:function(e,t){if(t)for(var i=0;i0&&(t>r?t-=r:t=0,i>r?i-=r:i=0);var n,s=!0,o=e.getImageData(t,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(e,t,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(e,t,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=x.util.sin(c),d=x.util.cos(c),f=0,g=0,_=-d*e*.5-u*t*.5,p=-d*t*.5+u*e*.5,m=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,S=_*_,w=m*v-m*y-v*S,b=0;if(w<0){var C=Math.sqrt(1-w/(m*v));i*=C,s*=C}else b=(o===a?-1:1)*Math.sqrt(w/(m*y+v*S));var T=b*i*p/s,I=-b*s*_/i,A=d*T-u*I+.5*e,E=u*T+d*I+.5*t,O=n(1,0,(_-T)/i,(p-I)/s),D=n((_-T)/i,(p-I)/s,(-_-T)/i,(-p-I)/s);0===a&&D>0?D-=2*l:1===a&&D<0&&(D+=2*l);for(var R=Math.ceil(Math.abs(D/l*2)),M=[],L=D/R,F=8/3*Math.sin(L/4)*Math.sin(L/4)/Math.sin(L/2),P=O+L,k=0;kb)for(var T=1,I=_.length;T2;for(t=t||0,l&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,h=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+h*t]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(t,i,r,n,s,o,a,h){var l;if(x.cachesBoundsOfCurve&&(l=e.call(arguments),x.boundsOfCurveCache[l]))return x.boundsOfCurveCache[l];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,w=Math.abs,b=[],C=[[],[]];u=6*t-12*r+6*s,c=-3*t+9*r-9*s+3*a,d=3*r-3*t;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),w(c)<1e-12){if(w(u)<1e-12)continue;0<(f=-d/u)&&f<1&&b.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&b.push(g),0<(_=(-u-m)/(2*c))&&_<1&&b.push(_));for(var I,A,E,O=b.length,D=O;O--;)I=(E=1-(f=b[O]))*E*E*t+3*E*E*f*r+3*E*f*f*s+f*f*f*a,C[0][O]=I,A=E*E*E*i+3*E*E*f*n+3*E*f*f*o+f*f*f*h,C[1][O]=A;C[0][D]=t,C[1][D]=i,C[0][D+1]=a,C[1][D+1]=h;var R=[{x:y.apply(null,C[0]),y:y.apply(null,C[1])},{x:S.apply(null,C[0]),y:S.apply(null,C[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=R),R},x.util.getPointOnPath=function(e,t,i){i||(i=d(e));for(var r=0;t-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>t?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,t)}},x.util.transformPath=function(e,t,i){return i&&(t=x.util.multiplyTransformMatrices(t,[1,0,0,1,-i.x,-i.y])),e.map((function(e){for(var i=e.slice(0),r={},n=1;n=t}))}}}(),function(){function e(t,i,r){if(r)if(!x.isLikelyNode&&i instanceof Element)t=i;else if(i instanceof Array){t=[];for(var n=0,s=i.length;n57343)return e.charAt(t);if(55296<=i&&i<=56319){if(e.length<=t+1)throw"High surrogate without following low surrogate";var r=e.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return e.charAt(t)+e.charAt(t+1)}if(0===t)throw"Low surrogate without preceding high surrogate";var n=e.charCodeAt(t-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}x.util.string={camelize:function(e){return e.replace(/-+(.)?/g,(function(e,t){return t?t.toUpperCase():""}))},capitalize:function(e,t){return e.charAt(0).toUpperCase()+(t?e.slice(1):e.slice(1).toLowerCase())},escapeXml:function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(t){var i,r=0,n=[];for(r=0;r-1?e.prototype[n]=function(e){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=t[e].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==e)return n}}(n):e.prototype[n]=t[n],i&&(t.toString!==Object.prototype.toString&&(e.prototype.toString=t.toString),t.valueOf!==Object.prototype.valueOf&&(e.prototype.valueOf=t.valueOf))};function n(){}function s(t){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[t];if(r[t]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,e.call(arguments,1)):i.call(this):console.log("tried to callSuper "+t+", method not found in prototype chain",this)}x.util.createClass=function(){var i=null,o=e.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===e.pointerType},d="string"==typeof(u=x.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(e){return e},d?_=function(e,t){return e.style.opacity=t,e}:f&&(_=function(e,t){var i=e.style;return e.currentStyle&&!e.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(t=t>=.9999?"":"alpha(opacity="+100*t+")",i.filter=i.filter.replace(g,t)):i.filter+=" alpha(opacity="+100*t+")",e}),x.util.setStyle=function(e,t){var i=e.style;if(!i)return e;if("string"==typeof t)return e.style.cssText+=";"+t,t.indexOf("opacity")>-1?_(e,t.match(/opacity:\s*(\d?\.?\d*)/)[1]):e;for(var r in t)"opacity"===r?_(e,t[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=t[r];return e},function(){var e,t,i,r,n=Array.prototype.slice,s=function(e){return n.call(e,0)};try{e=s(x.document.childNodes)instanceof Array}catch(e){}function o(e,t){var i=x.document.createElement(e);for(var r in t)"class"===r?i.className=t[r]:"for"===r?i.htmlFor=t[r]:i.setAttribute(r,t[r]);return i}function a(e){for(var t=0,i=0,r=x.document.documentElement,n=x.document.body||{scrollLeft:0,scrollTop:0};e&&(e.parentNode||e.host)&&((e=e.parentNode||e.host)===x.document?(t=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(t+=e.scrollLeft||0,i+=e.scrollTop||0),1!==e.nodeType||"fixed"!==e.style.position););return{left:t,top:i}}e||(s=function(e){for(var t=new Array(e.length),i=e.length;i--;)t[i]=e[i];return t}),t=x.document.defaultView&&x.document.defaultView.getComputedStyle?function(e,t){var i=x.document.defaultView.getComputedStyle(e,null);return i?i[t]:void 0}:function(e,t){var i=e.style[t];return!i&&e.currentStyle&&(i=e.currentStyle[t]),i},i=x.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",x.util.makeElementUnselectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=x.util.falseFunction),r?e.style[r]="none":"string"==typeof e.unselectable&&(e.unselectable="on"),e},x.util.makeElementSelectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=null),r?e.style[r]="":"string"==typeof e.unselectable&&(e.unselectable=""),e},x.util.setImageSmoothing=function(e,t){e.imageSmoothingEnabled=e.imageSmoothingEnabled||e.webkitImageSmoothingEnabled||e.mozImageSmoothingEnabled||e.msImageSmoothingEnabled||e.oImageSmoothingEnabled,e.imageSmoothingEnabled=t},x.util.getById=function(e){return"string"==typeof e?x.document.getElementById(e):e},x.util.toArray=s,x.util.addClass=function(e,t){e&&-1===(" "+e.className+" ").indexOf(" "+t+" ")&&(e.className+=(e.className?" ":"")+t)},x.util.makeElement=o,x.util.wrapElement=function(e,t,i){return"string"==typeof t&&(t=o(t,i)),e.parentNode&&e.parentNode.replaceChild(t,e),t.appendChild(e),t},x.util.getScrollLeftTop=a,x.util.getElementOffset=function(e){var i,r,n=e&&e.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(t(e,l),10)||0;return i=n.documentElement,void 0!==e.getBoundingClientRect&&(s=e.getBoundingClientRect()),r=a(e),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},x.util.getNodeCanvas=function(e){var t=x.jsdomImplForWrapper(e);return t._canvas||t._image},x.util.cleanUpJsdomNode=function(e){if(x.isLikelyNode){var t=x.jsdomImplForWrapper(e);t&&(t._image=null,t._canvas=null,t._currentSrc=null,t._attributes=null,t._classList=null)}}}(),function(){function e(){}x.util.request=function(t,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new x.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=e)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(t=function(e,t){return e+(/\?/.test(e)?"&":"?")+t}(t,i.parameters))),s.open(r,t,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),x.log=console.log,x.warn=console.warn,function(){var e=x.util.object.extend,t=x.util.object.clone,i=[];function r(){return!1}function n(e,t,i,r){return-i*Math.cos(e/r*(Math.PI/2))+i+t}x.util.object.extend(i,{cancelAll:function(){var e=this.splice(0);return e.forEach((function(e){e.cancel()})),e},cancelByCanvas:function(e){if(!e)return[];var t=this.filter((function(t){return"object"==typeof t.target&&t.target.canvas===e}));return t.forEach((function(e){e.cancel()})),t},cancelByTarget:function(e){var t=this.findAnimationsByTarget(e);return t.forEach((function(e){e.cancel()})),t},findAnimationIndex:function(e){return this.indexOf(this.findAnimation(e))},findAnimation:function(e){return this.find((function(t){return t.cancel===e}))},findAnimationsByTarget:function(e){return e?this.filter((function(t){return t.target===e})):[]}});var s=x.window.requestAnimationFrame||x.window.webkitRequestAnimationFrame||x.window.mozRequestAnimationFrame||x.window.oRequestAnimationFrame||x.window.msRequestAnimationFrame||function(e){return x.window.setTimeout(e,1e3/60)},o=x.window.cancelAnimationFrame||x.window.clearTimeout;function a(){return s.apply(x.window,arguments)}x.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var e=x.runningAnimations.indexOf(s);return e>-1&&x.runningAnimations.splice(e,1)[0]};return s=e(t(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(s),a((function(e){var t,l=e||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||n,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(e,t){return v[t]-m[t]})):v-m);i.onStart&&i.onStart(),function e(i){var r=(t=i||+new Date)>u?c:t-l,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),w=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=w,s.durationRate=n,!o){if(!f(S,w,n))return t>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(S,w,n),void a(e));h()}}(l)})),s.cancel},x.util.requestAnimFrame=a,x.util.cancelAnimFrame=function(){return o.apply(x.window,arguments)},x.runningAnimations=i}(),function(){function e(e,t,i){var r="rgba("+parseInt(e[0]+i*(t[0]-e[0]),10)+","+parseInt(e[1]+i*(t[1]-e[1]),10)+","+parseInt(e[2]+i*(t[2]-e[2]),10);return(r+=","+(e&&t?parseFloat(e[3]+i*(t[3]-e[3])):1))+")"}x.util.animateColor=function(t,i,r,n){var s=new x.Color(t).getSource(),o=new x.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},x.util.animate(x.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(t,i,r,s){return e(i,r,n.colorEasing?n.colorEasing(t,s):1-Math.cos(t/s*(Math.PI/2)))},onComplete:function(t,i,r){if(a)return a(e(o,o,0),i,r)},onChange:function(t,i,r){if(h){if(Array.isArray(t))return h(e(t,t,0),i,r);h(t,i,r)}}}))}}(),function(){function e(e,t,i,r){return e-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===e||"xlink:href"===e||"font"===e)return i;if("imageSmoothing"===e)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(e){return new RegExp("^("+e.join("|")+")\\b","i")}function g(e,t){var i,r,n,s,o=[];for(n=0,s=t.length;n1;)h.shift(),l=t.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*$");function y(e){if(!t.svgViewBoxElementsRegEx.test(e.nodeName))return{};var i,r,n,o,a,h,l=e.getAttribute("viewBox"),c=1,u=1,d=e.getAttribute("width"),f=e.getAttribute("height"),g=e.getAttribute("x")||0,_=e.getAttribute("y")||0,p=e.getAttribute("preserveAspectRatio")||"",m=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,w={},b="",C=0,x=0;if(w.width=0,w.height=0,w.toBeParsed=S,m&&(g||_)&&e.parentNode&&"#document"!==e.parentNode.nodeName&&(b=" translate("+s(g)+" "+s(_)+") ",a=(e.getAttribute("transform")||"")+b,e.setAttribute("transform",a),e.removeAttribute("x"),e.removeAttribute("y")),S)return w;if(m)return w.width=s(d),w.height=s(f),w;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),w.minX=i,w.minY=r,w.viewBoxWidth=n,w.viewBoxHeight=o,y?(w.width=n,w.height=o):(w.width=s(d),w.height=s(f),c=w.width/n,u=w.height/o),"none"!==(p=t.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),C=w.width-n*c,x=w.height-o*c,"Mid"===p.alignX&&(C/=2),"Mid"===p.alignY&&(x/=2),"Min"===p.alignX&&(C=0),"Min"===p.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return w;if((g||_)&&"#document"!==e.parentNode.nodeName&&(b=" translate("+s(g)+" "+s(_)+") "),a=b+" matrix("+c+" 0 0 "+u+" "+(i*c+C)+" "+(r*u+x)+") ","svg"===e.nodeName){for(h=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)h.appendChild(e.firstChild);e.appendChild(h)}else(h=e).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),w}function S(e,t){var i="xlink:href",r=m(e,t.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(e,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(e){r&&!t.hasAttribute(e)&&r.hasAttribute(e)&&t.setAttribute(e,r.getAttribute(e))})),!t.children.length)for(var n=r.cloneNode(!0);n.firstChild;)t.appendChild(n.firstChild);t.removeAttribute(i)}t.parseSVGDocument=function(e,i,n,s){if(e){!function(e){for(var i=g(e,["use","svg:use"]),r=0;i.length&&re.x&&this.y>e.y},gte:function(e){return this.x>=e.x&&this.y>=e.y},lerp:function(e,t){return void 0===t&&(t=.5),t=Math.max(Math.min(1,t),0),new i(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)},distanceFrom:function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},midPointFrom:function(e){return this.lerp(e)},min:function(e){return new i(Math.min(this.x,e.x),Math.min(this.y,e.y))},max:function(e){return new i(Math.max(this.x,e.x),Math.max(this.y,e.y))},toString:function(){return this.x+","+this.y},setXY:function(e,t){return this.x=e,this.y=t,this},setX:function(e){return this.x=e,this},setY:function(e){return this.y=e,this},setFromPoint:function(e){return this.x=e.x,this.y=e.y,this},swap:function(e){var t=this.x,i=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=i},clone:function(){return new i(this.x,this.y)}})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){this.status=e,this.points=[]}t.Intersection?t.warn("fabric.Intersection is already defined"):(t.Intersection=i,t.Intersection.prototype={constructor:i,appendPoint:function(e){return this.points.push(e),this},appendPoints:function(e){return this.points=this.points.concat(e),this}},t.Intersection.intersectLineLine=function(e,r,n,s){var o,a=(s.x-n.x)*(e.y-n.y)-(s.y-n.y)*(e.x-n.x),h=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),l=(s.y-n.y)*(r.x-e.x)-(s.x-n.x)*(r.y-e.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new t.Point(e.x+c*(r.x-e.x),e.y+c*(r.y-e.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},t.Intersection.intersectLinePolygon=function(e,t,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},t.Intersection.intersectPolygonPolygon=function(e,t){var r,n=new i,s=e.length;for(r=0;r0&&(n.status="Intersection"),n},t.Intersection.intersectPolygonRectangle=function(e,r,n){var s=r.min(n),o=r.max(n),a=new t.Point(o.x,s.y),h=new t.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,e),c=i.intersectLinePolygon(a,o,e),u=i.intersectLinePolygon(o,h,e),d=i.intersectLinePolygon(h,s,e),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){e?this._tryParsingColor(e):this.setSource([0,0,0,1])}function r(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}t.Color?t.warn("fabric.Color is already defined."):(t.Color=i,t.Color.prototype={_tryParsingColor:function(e){var t;e in i.colorNameMap&&(e=i.colorNameMap[e]),"transparent"===e&&(t=[255,255,255,0]),t||(t=i.sourceFromHex(e)),t||(t=i.sourceFromRgb(e)),t||(t=i.sourceFromHsl(e)),t||(t=[0,0,0,1]),t&&this.setSource(t)},_rgbToHsl:function(e,i,r){e/=255,i/=255,r/=255;var n,s,o,a=t.util.array.max([e,i,r]),h=t.util.array.min([e,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case e:n=(i-r)/l+(i0)-(e<0)||+e};function f(e,t){var i=e.angle+u(Math.atan2(t.y,t.x))+360;return Math.round(i%360/45)}function g(e,i){var r=i.transform.target,n=r.canvas,s=t.util.object.clone(i);s.target=r,n&&n.fire("object:"+e,s),r.fire(e,i)}function _(e,t){var i=t.canvas,r=e[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(e){return e.originX===l&&e.originY===l}function m(e,t,i){var r=e.lockScalingX,n=e.lockScalingY;return!((!r||!n)&&(t||!r&&!n||!i)&&(!r||"x"!==t)&&(!n||"y"!==t))}function v(e,t,i,r){return{e,transform:t,pointer:{x:i,y:r}}}function y(e){return function(t,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=e(t,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function S(e,t){return function(i,r,n,s){var o=t(i,r,n,s);return o&&g(e,v(i,r,n,s)),o}}function w(e,i,r,n,s){var o=e.target,a=o.controls[e.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new t.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function b(e){return e.flipX!==e.flipY}function C(e,t,i,r,n){if(0!==e[t]){var s=n/e._getTransformedDimensions()[r]*e[i];e.set(i,s)}}function x(e,t,i,r){var n,l=t.target,c=l._getTransformedDimensions(0,l.skewY),d=w(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),t.originX===s&&t.originY===h&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),b(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().y;l.set("skewX",n),C(l,"skewY","scaleY","y",p)}return _}function T(e,t,i,r){var n,l=t.target,c=l._getTransformedDimensions(l.skewX,0),d=w(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),t.originX===s&&t.originY===h&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),b(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().x;l.set("skewY",n),C(l,"skewX","scaleX","x",p)}return _}function I(e,t,i,r,n){n=n||{};var s,o,a,h,l,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),b=m(f,y,S),C=t.gestureScale;if(b)return!1;if(C)o=t.scaleX*C,a=t.scaleY*C;else{if(s=w(t,t.originX,t.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,t.signX||(t.signX=l),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==l||t.signY!==u))return!1;if(h=f._getTransformedDimensions(),S&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=t.original,I=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(t)&&(o*=2,a*=2),t.signX!==l&&"y"!==y&&(t.originX=c[t.originX],o*=-1,t.signX=l),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.signY=u)}var A=f.scaleX,E=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),A!==f.scaleX||E!==f.scaleY}n.scaleCursorStyleHandler=function(e,t,r){var n=_(e,r),s="";if(0!==t.x&&0===t.y?s="x":0===t.x&&0!==t.y&&(s="y"),m(r,s,n))return"not-allowed";var o=f(r,t);return i[o]+"-resize"},n.skewCursorStyleHandler=function(e,t,i){var n="not-allowed";if(0!==t.x&&i.lockSkewingY)return n;if(0!==t.y&&i.lockSkewingX)return n;var s=f(i,t)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(e,t,i){return e[i.canvas.altActionKey]?n.skewCursorStyleHandler(e,t,i):n.scaleCursorStyleHandler(e,t,i)},n.rotationWithSnapping=S("rotating",y((function(e,t,i,r){var n=t,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),b(h)&&(n=n===s?a:s)),t.originX=n,S("skewing",y(x))(e,t,i,r))},n.skewHandlerY=function(e,t,i,r){var n,a=t.target,c=a.skewY,u=t.originX;return!a.lockSkewingY&&(0===c?n=w(t,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),b(a)&&(n=n===o?h:o)),t.originY=n,S("skewing",y(T))(e,t,i,r))},n.dragHandler=function(e,t,i,r){var n=t.target,s=i-t.offsetX,o=r-t.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(e,t,i,r)),a||h},n.scaleOrSkewActionName=function(e,t,i){var r=e[i.canvas.altActionKey];return 0===t.x?r?"skewX":"scaleY":0===t.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(e,t,i){return i.lockRotation?"not-allowed":t.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=S,n.getLocalPoint=w,t.controlsUtils=n}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians,r=t.controlsUtils;r.renderCircleControl=function(e,t,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=t,d=i;e.save(),e.fillStyle=r.cornerColor||n.cornerColor,e.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,e.scale(1,a/o),d=i*o/a):a>o?(s=a,e.scale(o/a,1),u=t*a/o):s=o,e.lineWidth=1,e.beginPath(),e.arc(u,d,s/2,0,2*Math.PI,!1),e[l](),c&&e.stroke(),e.restore()},r.renderSquareControl=function(e,t,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;e.save(),e.fillStyle=n.cornerColor||s.cornerColor,e.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,e.lineWidth=1,e.translate(t,r),e.rotate(i(s.angle)),e[l+"Rect"](-u,-d,o,a),c&&e.strokeRect(-u,-d,o,a),e.restore()}}(t),function(e){var t=e.fabric||(e.fabric={});t.Control=function(e){for(var t in e)this[t]=e[t]},t.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(e,t){return t.cursorStyle},getActionName:function(e,t){return t.actionName},getVisibility:function(e,t){var i=e._controlsVisibility;return i&&void 0!==i[t]?i[t]:this.visible},setVisibility:function(e){this.visible=e},positionHandler:function(e,i){return t.util.transformPoint({x:this.x*e.x+this.offsetX,y:this.y*e.y+this.offsetY},i)},calcCornerCoords:function(e,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-t.util.degreesToRadians(e),_=Math.PI/2-d-t.util.degreesToRadians(e);o=f*t.util.cos(g),a=f*t.util.sin(g),h=f*t.util.cos(_),l=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),o=h=f*t.util.cos(g),a=l=f*t.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(e,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?t.controlsUtils.renderCircleControl.call(this,e,i,r,n,s):t.controlsUtils.renderSquareControl.call(this,e,i,r,n,s)}}}(t),function(){function e(e,t){var i,r,n,s,o=e.getAttribute("style"),a=e.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=e.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=e.getAttribute("stop-opacity")),r=(i=new x.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*t,{offset:a,color:i.toRgb(),opacity:n}}var t=x.util.object.clone;x.Gradient=x.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(e){e||(e={}),e.coords||(e.coords={});var t,i=this;Object.keys(e).forEach((function(t){i[t]=e[t]})),this.id?this.id+="_"+x.Object.__uid++:this.id=x.Object.__uid++,t={x1:e.coords.x1||0,y1:e.coords.y1||0,x2:e.coords.x2||0,y2:e.coords.y2||0},"radial"===this.type&&(t.r1=e.coords.r1||0,t.r2=e.coords.r2||0),this.coords=t,this.colorStops=e.colorStops.slice()},addColorStop:function(e){for(var t in e){var i=new x.Color(e[t]);this.colorStops.push({offset:parseFloat(t),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(e){var t={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return x.util.populateWithProperties(this,t,e),t},toSVG:function(e,i){var r,n,s,o,a=t(this.coords,!0),h=(i=i||{},t(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():x.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(e,t){return e.offset-t.offset})),"objectBoundingBox"===g?(u/=e.width,d/=e.height):(u+=e.width/2,d+=e.height/2),"path"===e.type&&"percentage"!==this.gradientUnits&&(u-=e.pathOffset.x,d-=e.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+x.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(e){var t,i,r,n=x.util.object.clone(this.coords);if(this.type){for("linear"===this.type?t=e.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(t=e.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=t.getElementsByTagName("stop"),u="userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage",d=t.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?(o="linear",a=function(e){return{x1:e.getAttribute("x1")||0,y1:e.getAttribute("y1")||0,x2:e.getAttribute("x2")||"100%",y2:e.getAttribute("y2")||0}}(t)):(o="radial",a=function(e){return{x1:e.getAttribute("fx")||e.getAttribute("cx")||"50%",y1:e.getAttribute("fy")||e.getAttribute("cy")||"50%",r1:0,x2:e.getAttribute("cx")||"50%",y2:e.getAttribute("cy")||"50%",r2:e.getAttribute("r")||"50%"}}(t)),h=c.length;h--;)f.push(e(c[h],s));return l=x.parseTransformAttribute(d),function(e,t,i,r){var n,s;Object.keys(t).forEach((function(e){"Infinity"===(n=t[e])?s=1:"-Infinity"===n?s=0:(s=parseFloat(t[e],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==e&&"x2"!==e&&"r2"!==e||(s*=i.viewBoxWidth||i.width),"y1"!==e&&"y2"!==e||(s*=i.viewBoxHeight||i.height)))),t[e]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,_=-i.top),new x.Gradient({id:t.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:_})}})}(),m=x.util.toFixed,x.Pattern=x.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(e,t){if(e||(e={}),this.id=x.Object.__uid++,this.setOptions(e),!e.source||e.source&&"string"!=typeof e.source)t&&t(this);else{var i=this;this.source=x.util.createImage(),x.util.loadImage(e.source,(function(e,r){i.source=e,t&&t(i,r)}),null,this.crossOrigin)}},toObject:function(e){var t,i,r=x.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?t=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(t=this.source.toDataURL()),i={type:"pattern",source:t,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},x.util.populateWithProperties(this,i,e),i},toSVG:function(e){var t="function"==typeof this.source?this.source():this.source,i=t.width/e.width,r=t.height/e.height,n=this.offsetX/e.width,s=this.offsetY/e.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),t.src?o=t.src:t.toDataURL&&(o=t.toDataURL()),'\n\n\n'},setOptions:function(e){for(var t in e)this[t]=e[t]},toLive:function(e){var t=this.source;if(!t)return"";if(void 0!==t.src){if(!t.complete)return"";if(0===t.naturalWidth||0===t.naturalHeight)return""}return e.createPattern(t,this.repeat)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.toFixed;t.Shadow?t.warn("fabric.Shadow is already defined."):(t.Shadow=t.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(e){for(var i in"string"==typeof e&&(e=this._parseShadow(e)),e)this[i]=e[i];this.id=t.Object.__uid++},_parseShadow:function(e){var i=e.trim(),r=t.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(t.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(e){var r=40,n=40,s=t.Object.NUM_FRACTION_DIGITS,o=t.util.rotateVector({x:this.offsetX,y:this.offsetY},t.util.degreesToRadians(-e.angle)),a=new t.Color(this.color);return e.width&&e.height&&(r=100*i((Math.abs(o.x)+this.blur)/e.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/e.height,s)+20),e.flipX&&(o.x*=-1),e.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var e={},i=t.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(t){this[t]!==i[t]&&(e[t]=this[t])}),this),e}}),t.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(t),function(){if(x.StaticCanvas)x.warn("fabric.StaticCanvas is already defined.");else{var e=x.util.object.extend,t=x.util.getElementOffset,i=x.util.removeFromArray,r=x.util.toFixed,n=x.util.transformPoint,s=x.util.invertTransform,o=x.util.getNodeCanvas,a=x.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");x.StaticCanvas=x.util.createClass(x.CommonMethods,{initialize:function(e,t){t||(t={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(e,t)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:x.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(e,t){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(e),this._initOptions(t),this.interactive||this._initRetinaScaling(),t.overlayImage&&this.setOverlayImage(t.overlayImage,i),t.backgroundImage&&this.setBackgroundImage(t.backgroundImage,i),t.backgroundColor&&this.setBackgroundColor(t.backgroundColor,i),t.overlayColor&&this.setOverlayColor(t.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return x.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,x.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var e=x.devicePixelRatio;this.__initRetinaScaling(e,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(e,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(e,t,i){t.setAttribute("width",this.width*e),t.setAttribute("height",this.height*e),i.scale(e,e)},calcOffset:function(){return this._offset=t(this.lowerCanvasEl),this},setOverlayImage:function(e,t,i){return this.__setBgOverlayImage("overlayImage",e,t,i)},setBackgroundImage:function(e,t,i){return this.__setBgOverlayImage("backgroundImage",e,t,i)},setOverlayColor:function(e,t){return this.__setBgOverlayColor("overlayColor",e,t)},setBackgroundColor:function(e,t){return this.__setBgOverlayColor("backgroundColor",e,t)},__setBgOverlayImage:function(e,t,i,r){return"string"==typeof t?x.util.loadImage(t,(function(t,n){if(t){var s=new x.Image(t,r);this[e]=s,s.canvas=this}i&&i(t,n)}),this,r&&r.crossOrigin):(r&&t.setOptions(r),this[e]=t,t&&(t.canvas=this),i&&i(t,!1)),this},__setBgOverlayColor:function(e,t,i){return this[e]=t,this._initGradient(t,e),this._initPattern(t,e,i),this},_createCanvasElement:function(){var e=a();if(!e)throw h;if(e.style||(e.style={}),void 0===e.getContext)throw h;return e},_initOptions:function(e){var t=this.lowerCanvasEl;this._setOptions(e),this.width=this.width||parseInt(t.width,10)||0,this.height=this.height||parseInt(t.height,10)||0,this.lowerCanvasEl.style&&(t.width=this.width,t.height=this.height,t.style.width=this.width+"px",t.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(e){e&&e.getContext?this.lowerCanvasEl=e:this.lowerCanvasEl=x.util.getById(e)||this._createCanvasElement(),x.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(e,t){return this.setDimensions({width:e},t)},setHeight:function(e,t){return this.setDimensions({height:e},t)},setDimensions:function(e,t){var i;for(var r in t=t||{},e)i=e[r],t.cssOnly||(this._setBackstoreDimension(r,e[r]),i+="px",this.hasLostContext=!0),t.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),t.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(e,t){return this.lowerCanvasEl[e]=t,this.upperCanvasEl&&(this.upperCanvasEl[e]=t),this.cacheCanvasEl&&(this.cacheCanvasEl[e]=t),this[e]=t,this},_setCssDimension:function(e,t){return this.lowerCanvasEl.style[e]=t,this.upperCanvasEl&&(this.upperCanvasEl.style[e]=t),this.wrapperEl&&(this.wrapperEl.style[e]=t),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(e){var t,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=e,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",t),this._setSVGObjects(i,t),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",t),i.push(""),i.join("")},_setSVGPreamble:function(e,t){t.suppressPreamble||e.push('\n','\n')},_setSVGHeader:function(e,t){var i,n=t.width||this.width,s=t.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=x.Object.NUM_FRACTION_DIGITS;t.viewBox?o='viewBox="'+t.viewBox.x+" "+t.viewBox.y+" "+t.viewBox.width+" "+t.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),e.push("\n',"Created with Fabric.js ",x.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(t),"\n")},createSVGClipPathMarkup:function(e){var t=this.clipPath;return t?(t.clipPathId="CLIPPATH_"+x.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(e.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var e=this;return["background","overlay"].map((function(t){var i=e[t+"Color"];if(i&&i.toLive){var r=e[t+"Vpt"],n=e.viewportTransform,s={width:e.width/(r?n[0]:1),height:e.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?x.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var e,t,i,r,n,s,o,a,h="",l={},c=x.fontPaths,u=[];for(this._objects.forEach((function e(t){u.push(t),t._objects&&t._objects.forEach(e)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(e,t){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else e.push('\n")},sendToBack:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(t=(n=s._objects).length;t--;)r=n[t],i(this._objects,r),this._objects.unshift(r);else i(this._objects,e),this._objects.unshift(e);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(n=s._objects,t=0;t0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(e))&&(o=this._findNewLowerIndex(e,s,t),i(this._objects,e),this._objects.splice(o,0,e));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(e,t,i){var r,n;if(i){for(r=t,n=t-1;n>=0;--n)if(e.intersectsWithObject(this._objects[n])||e.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(e)){r=n;break}}else r=t-1;return r},bringForward:function(e,t){if(!e)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(e===h&&"activeSelection"===e.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),e(x.StaticCanvas.prototype,x.Observable),e(x.StaticCanvas.prototype,x.Collection),e(x.StaticCanvas.prototype,x.DataURLExporter),e(x.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(e){var t=a();if(!t||!t.getContext)return null;var i=t.getContext("2d");return i&&"setLineDash"===e?void 0!==i.setLineDash:null}}),x.StaticCanvas.prototype.toJSON=x.StaticCanvas.prototype.toObject,x.isLikelyNode&&(x.StaticCanvas.prototype.createPNGStream=function(){var e=o(this.lowerCanvasEl);return e&&e.createPNGStream()},x.StaticCanvas.prototype.createJPEGStream=function(e){var t=o(this.lowerCanvasEl);return t&&t.createJPEGStream(e)})}}(),x.BaseBrush=x.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(e){e.strokeStyle=this.color,e.lineWidth=this.width,e.lineCap=this.strokeLineCap,e.miterLimit=this.strokeMiterLimit,e.lineJoin=this.strokeLineJoin,e.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(e){var t=this.canvas.viewportTransform;e.save(),e.transform(t[0],t[1],t[2],t[3],t[4],t[5])},_setShadow:function(){if(this.shadow){var e=this.canvas,t=this.shadow,i=e.contextTop,r=e.getZoom();e&&e._isRetinaScaling()&&(r*=x.devicePixelRatio),i.shadowColor=t.color,i.shadowBlur=t.blur*r,i.shadowOffsetX=t.offsetX*r,i.shadowOffsetY=t.offsetY*r}},needsFullRender:function(){return new x.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var e=this.canvas.contextTop;e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0},_isOutSideCanvas:function(e){return e.x<0||e.x>this.canvas.getWidth()||e.y<0||e.y>this.canvas.getHeight()}}),x.PencilBrush=x.util.createClass(x.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(e){this.canvas=e,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(e,t,i){var r=t.midPointFrom(i);return e.quadraticCurveTo(t.x,t.y,r.x,r.y),r},onMouseDown:function(e,t){this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],this._prepareForDrawing(e),this._captureDrawingPath(e),this._render())},onMouseMove:function(e,t){if(this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(e))&&this._captureDrawingPath(e)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(e){return!this.canvas._isMainEvent(e.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(e){var t=new x.Point(e.x,e.y);this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)},_addPoint:function(e){return!(this._points.length>1&&e.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(e),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(e){var t=new x.Point(e.x,e.y);return this._addPoint(t)},_render:function(e){var t,i,r=this._points[0],n=this._points[1];if(e=e||this.canvas.contextTop,this._saveAndTransform(e),e.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new x.Point(r.x,r.y),n=new x.Point(n.x,n.y),r.x-=s,n.x+=s}for(e.moveTo(r.x,r.y),t=1,i=this._points.length;t=n&&(o=e[i],a.push(o));return a.push(e[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var e=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(e))this.canvas.requestRenderAll();else{var t=this.createPath(e);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:t}),this.canvas.add(t),this.canvas.requestRenderAll(),t.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:t})}}}),x.CircleBrush=x.util.createClass(x.BaseBrush,{width:10,initialize:function(e){this.canvas=e,this.points=[]},drawDot:function(e){var t=this.addPoint(e),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,t),i.restore()},dot:function(e,t){e.fillStyle=t.fill,e.beginPath(),e.arc(t.x,t.y,t.radius,0,2*Math.PI,!1),e.closePath(),e.fill()},onMouseDown:function(e){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(e)},_render:function(){var e,t,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),e=0,t=r.length;e0&&!this.preserveObjectStacking){t=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),t.push.apply(t,i)}else t=this._objects;return t},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var e=this.contextContainer;return this.renderCanvas(e,this._chooseObjectsToRender()),this},renderTopLayer:function(e){e.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(e),this.contextTopDirty=!0),e.restore()},renderTop:function(){var e=this.contextTop;return this.clearContext(e),this.renderTopLayer(e),this.fire("after:render"),this},_normalizePointer:function(e,t){var i=e.calcTransformMatrix(),r=x.util.invertTransform(i),n=this.restorePointerVpt(t);return x.util.transformPoint(n,r)},isTargetTransparent:function(e,t,i){if(e.shouldCache()&&e._cacheCanvas&&e!==this._activeObject){var r=this._normalizePointer(e,{x:t,y:i}),n=Math.max(e.cacheTranslationX+r.x*e.zoomX,0),s=Math.max(e.cacheTranslationY+r.y*e.zoomY,0);return x.util.isTransparent(e._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=e.selectionBackgroundColor,h=this.viewportTransform;return e.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),e.render(o),o.restore(),e.selectionBackgroundColor=a,x.util.isTransparent(o,t,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(e){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(t){return!0===e[t]})):e[this.selectionKey]},_shouldClearSelection:function(e,t){var i=this.getActiveObjects(),r=this._activeObject;return!t||t&&r&&i.length>1&&-1===i.indexOf(t)&&r!==t&&!this._isSelectionKeyPressed(e)||t&&!t.evented||t&&!t.selectable&&r&&r!==t},_shouldCenterTransform:function(e,t,i){var r;if(e)return"scale"===t||"scaleX"===t||"scaleY"===t||"resizing"===t?r=this.centeredScaling||e.centeredScaling:"rotate"===t&&(r=this.centeredRotation||e.centeredRotation),r?!i:i},_getOriginFromCorner:function(e,t){var i={x:e.originX,y:e.originY};return"ml"===t||"tl"===t||"bl"===t?i.x="right":"mr"!==t&&"tr"!==t&&"br"!==t||(i.x="left"),"tl"===t||"mt"===t||"tr"===t?i.y="bottom":"bl"!==t&&"mb"!==t&&"br"!==t||(i.y="top"),i},_getActionFromCorner:function(e,t,i,r){if(!t||!e)return"drag";var n=r.controls[t];return n.getActionName(i,n,r)},_setupCurrentTransform:function(e,i,r){if(i){var n=this.getPointer(e),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(e,i,o):x.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,e,i),l=this._getOriginFromCorner(i,s),c=e[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:t(i.angle),width:i.width*i.scaleX,shiftKey:e.shiftKey,altKey:c,original:x.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(e)}},setCursor:function(e){this.upperCanvasEl.style.cursor=e},_drawSelection:function(e){var t=this._groupSelector,i=new x.Point(t.ex,t.ey),r=x.util.transformPoint(i,this.viewportTransform),n=new x.Point(t.ex+t.left,t.ey+t.top),s=x.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,x.Object.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(o,a,h-o,l-a))},findTarget:function(e,t){if(!this.skipTargetFind){var r,n,s=this.getPointer(e,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(e),l=a.length>1&&!t||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!t&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return e[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(e,t,i){if(t&&t.visible&&t.evented&&t.containsPoint(e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;if(!this.isTargetTransparent(t,i.x,i.y))return!0}},_searchPossibleTargets:function(e,t){for(var i,r,n=e.length;n--;){var s=e[n],o=s.group?this._normalizePointer(s.group,t):t;if(this._checkTarget(o,s,t)){(i=e[n]).subTargetCheck&&i instanceof x.Group&&(r=this._searchPossibleTargets(i._objects,t))&&this.targets.push(r);break}}return i},restorePointerVpt:function(e){return x.util.transformPoint(e,x.util.invertTransform(this.viewportTransform))},getPointer:function(t,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=e(t),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var e=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),t=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),x.util.addClass(i,"upper-canvas "+e),this.wrapperEl.appendChild(i),this._copyCanvasStyle(t,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=x.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),x.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),x.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(e){var t=this.width||e.width,i=this.height||e.height;x.util.setStyle(e,{position:"absolute",width:t+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),e.width=t,e.height=i,x.util.makeElementUnselectable(e)},_copyCanvasStyle:function(e,t){t.style.cssText=e.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var e=this._activeObject;return e?"activeSelection"===e.type&&e._objects?e._objects.slice(0):[e]:[]},_onObjectRemoved:function(e){e===this._activeObject&&(this.fire("before:selection:cleared",{target:e}),this._discardActiveObject(),this.fire("selection:cleared",{target:e}),e.fire("deselected")),e===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",e)},_fireSelectionEvents:function(e,t){var i=!1,r=this.getActiveObjects(),n=[],s=[];e.forEach((function(e){-1===r.indexOf(e)&&(i=!0,e.fire("deselected",{e:t,target:e}),s.push(e))})),r.forEach((function(r){-1===e.indexOf(r)&&(i=!0,r.fire("selected",{e:t,target:r}),n.push(r))})),e.length>0&&r.length>0?i&&this.fire("selection:updated",{e:t,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:t,selected:n}):e.length>0&&this.fire("selection:cleared",{e:t,deselected:s})},setActiveObject:function(e,t){var i=this.getActiveObjects();return this._setActiveObject(e,t),this._fireSelectionEvents(i,t),this},_setActiveObject:function(e,t){return this._activeObject!==e&&!!this._discardActiveObject(t,e)&&!e.onSelect({e:t})&&(this._activeObject=e,!0)},_discardActiveObject:function(e,t){var i=this._activeObject;if(i){if(i.onDeselect({e,object:t}))return!1;this._activeObject=null}return!0},discardActiveObject:function(e){var t=this.getActiveObjects(),i=this.getActiveObject();return t.length&&this.fire("before:selection:cleared",{target:i,e}),this._discardActiveObject(e),this._fireSelectionEvents(t,e),this},dispose:function(){var e=this.wrapperEl;return this.removeListeners(),e.removeChild(this.upperCanvasEl),e.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(e){x.util.cleanUpJsdomNode(this[e]),this[e]=void 0}.bind(this)),e.parentNode&&e.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,x.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(e){var t=this._activeObject;t&&t._renderControls(e)},_toObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(e),n=this.callSuper("_toObject",e,t,i);return this._unwindGroupTransformOnObject(e,r),n},_realizeGroupTransformOnObject:function(e){if(e.group&&"activeSelection"===e.group.type&&this._activeObject===e.group){var t={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){t[i]=e[i]})),x.util.addTransformToObject(e,this._activeObject.calcOwnMatrix()),t}return null},_unwindGroupTransformOnObject:function(e,t){t&&e.set(t)},_setSVGObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(t);this.callSuper("_setSVGObject",e,t,i),this._unwindGroupTransformOnObject(t,r)},setViewportTransform:function(e){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),x.StaticCanvas.prototype.setViewportTransform.call(this,e)}}),x.StaticCanvas)"prototype"!==r&&(x.Canvas[r]=x.StaticCanvas[r])}(),function(){var e=x.util.addListener,t=x.util.removeListener,i={passive:!1};function r(e,t){return e.button&&e.button===t-1}x.util.object.extend(x.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(e,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(e,t){var r=this.upperCanvasEl,n=this._getEventPrefix();e(x.window,"resize",this._onResize),e(r,n+"down",this._onMouseDown),e(r,n+"move",this._onMouseMove,i),e(r,n+"out",this._onMouseOut),e(r,n+"enter",this._onMouseEnter),e(r,"wheel",this._onMouseWheel),e(r,"contextmenu",this._onContextMenu),e(r,"dblclick",this._onDoubleClick),e(r,"dragover",this._onDragOver),e(r,"dragenter",this._onDragEnter),e(r,"dragleave",this._onDragLeave),e(r,"drop",this._onDrop),this.enablePointerEvents||e(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&t in eventjs&&(eventjs[t](r,"gesture",this._onGesture),eventjs[t](r,"drag",this._onDrag),eventjs[t](r,"orientation",this._onOrientationChange),eventjs[t](r,"shake",this._onShake),eventjs[t](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(t,"remove");var e=this._getEventPrefix();t(x.document,e+"up",this._onMouseUp),t(x.document,"touchend",this._onTouchEnd,i),t(x.document,e+"move",this._onMouseMove,i),t(x.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(e,t){this.__onTransformGesture&&this.__onTransformGesture(e,t)},_onDrag:function(e,t){this.__onDrag&&this.__onDrag(e,t)},_onMouseWheel:function(e){this.__onMouseWheel(e)},_onMouseOut:function(e){var t=this._hoveredTarget;this.fire("mouse:out",{target:t,e}),this._hoveredTarget=null,t&&t.fire("mouseout",{e});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:t,e}),r&&t.fire("mouseout",{e})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(e){e.isEditing&&e.hiddenTextarea.focus()}))},_onMouseEnter:function(e){this._currentTransform||this.findTarget(e)||(this.fire("mouse:over",{target:null,e}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(e,t){this.__onOrientationChange&&this.__onOrientationChange(e,t)},_onShake:function(e,t){this.__onShake&&this.__onShake(e,t)},_onLongPress:function(e,t){this.__onLongPress&&this.__onLongPress(e,t)},_onDragOver:function(e){e.preventDefault();var t=this._simpleEventHandler("dragover",e);this._fireEnterLeaveEvents(t,e)},_onDrop:function(e){return this._simpleEventHandler("drop:before",e),this._simpleEventHandler("drop",e)},_onContextMenu:function(e){return this.stopContextMenu&&(e.stopPropagation(),e.preventDefault()),!1},_onDoubleClick:function(e){this._cacheTransformEventData(e),this._handleEvent(e,"dblclick"),this._resetTransformEventData(e)},getPointerId:function(e){var t=e.changedTouches;return t?t[0]&&t[0].identifier:this.enablePointerEvents?e.pointerId:-1},_isMainEvent:function(e){return!0===e.isPrimary||!1!==e.isPrimary&&("touchend"===e.type&&0===e.touches.length||!e.changedTouches||e.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(x.document,"touchend",this._onTouchEnd,i),e(x.document,"touchmove",this._onMouseMove,i),t(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(n,s+"move",this._onMouseMove,i),e(x.document,s+"up",this._onMouseUp),e(x.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();t(x.document,"touchend",this._onTouchEnd,i),t(x.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){e(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(t(x.document,s+"up",this._onMouseUp),t(x.document,s+"move",this._onMouseMove,i),e(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(e){!this.allowTouchScrolling&&e.preventDefault&&e.preventDefault(),this.__onMouseMove(e)},_onResize:function(){this.calcOffset()},_shouldRender:function(e){var t=this._activeObject;return!!(!!t!=!!e||t&&e&&t!==e)||(t&&t.isEditing,!1)},__onMouseUp:function(e){var t,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(e),t=this._target,this._handleEvent(e,"up:before"),r(e,3))this.fireRightClick&&this._handleEvent(e,"up",3,o);else{if(r(e,2))return this.fireMiddleClick&&this._handleEvent(e,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(e);else if(this._isMainEvent(e)){if(i&&(this._finalizeCurrentTransform(e),s=i.actionPerformed),!o){var a=t===this._activeObject;this._maybeGroupObjects(e),s||(s=this._shouldRender(t)||!a&&t===this._activeObject)}var h,l;if(t){if(h=t._findTargetCorner(this.getPointer(e,!0),x.util.isTouchEvent(e)),t.selectable&&t!==this._activeObject&&"up"===t.activeOn)this.setActiveObject(t,e),s=!0;else{var c=t.controls[h],u=c&&c.getMouseUpHandler(e,t,c);u&&u(e,i,(l=this.getPointer(e)).x,l.y)}t.isMoving=!1}if(i&&(i.target!==t||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(e,t,c);l=l||this.getPointer(e),f&&f(e,i,l.x,l.y)}this._setCursorFromEvent(e,t),this._handleEvent(e,"up",1,o),this._groupSelector=null,this._currentTransform=null,t&&(t.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(e,t){var i=this.findTarget(t),r=this.targets,n={e:t,target:i,subTargets:r};if(this.fire(e,n),i&&i.fire(e,n),!r)return i;for(var s=0;s1&&(t=new x.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(t,e))},_collectObjects:function(e){for(var t,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new x.Point(v(r,s),v(n,o)),h=new x.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((t=this._objects[u])&&t.selectable&&t.visible&&(l&&t.intersectsWithRect(a,h,!0)||t.isContainedWithinRect(a,h,!0)||l&&t.containsPoint(a,null,!0)||l&&t.containsPoint(h,null,!0))&&(i.push(t),c)););return i.length>1&&(i=i.filter((function(t){return!t.onSelect({e})}))),i},_maybeGroupObjects:function(e){this.selection&&this._groupSelector&&this._groupSelectedObjects(e),this.setCursor(this.defaultCursor),this._groupSelector=null}}),x.util.object.extend(x.StaticCanvas.prototype,{toDataURL:function(e){e||(e={});var t=e.format||"png",i=e.quality||1,r=(e.multiplier||1)*(e.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,e);return x.util.toDataURL(n,t,i)},toCanvasElement:function(e,t){e=e||1;var i=((t=t||{}).width||this.width)*e,r=(t.height||this.height)*e,n=this.getZoom(),s=this.width,o=this.height,a=n*e,h=this.viewportTransform,l=(h[4]-(t.left||0))*e,c=(h[5]-(t.top||0))*e,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=x.util.createCanvasElement(),_=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=_,g}}),x.util.object.extend(x.StaticCanvas.prototype,{loadFromJSON:function(e,t,i){if(e){var r="string"==typeof e?JSON.parse(e):x.util.object.clone(e),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(e){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,e,o,t)})):n.__setupCanvas.call(n,r,e,o,t)}))}),i),this}},__setupCanvas:function(e,t,i,r){var n=this;t.forEach((function(e,t){n.insertAt(e,t)})),this.renderOnAddRemove=i,delete e.objects,delete e.backgroundImage,delete e.overlayImage,delete e.background,delete e.overlay,this._setOptions(e),this.renderAll(),r&&r()},_setBgOverlay:function(e,t){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(e.backgroundImage||e.overlayImage||e.background||e.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&t&&t()};this.__setBgOverlay("backgroundImage",e.backgroundImage,i,r),this.__setBgOverlay("overlayImage",e.overlayImage,i,r),this.__setBgOverlay("backgroundColor",e.background,i,r),this.__setBgOverlay("overlayColor",e.overlay,i,r)}else t&&t()},__setBgOverlay:function(e,t,i,r){var n=this;if(!t)return i[e]=!0,void(r&&r());"backgroundImage"===e||"overlayImage"===e?x.util.enlivenObjects([t],(function(t){n[e]=t[0],i[e]=!0,r&&r()})):this["set"+x.util.string.capitalize(e,!0)](t,(function(){i[e]=!0,r&&r()}))},_enlivenObjects:function(e,t,i){e&&0!==e.length?x.util.enlivenObjects(e,(function(e){t&&t(e)}),null,i):t&&t([])},_toDataURL:function(e,t){this.clone((function(i){t(i.toDataURL(e))}))},_toDataURLWithMultiplier:function(e,t,i){this.clone((function(r){i(r.toDataURLWithMultiplier(e,t))}))},clone:function(e,t){var i=JSON.stringify(this.toJSON(t));this.cloneWithoutData((function(t){t.loadFromJSON(i,(function(){e&&e(t)}))}))},cloneWithoutData:function(e){var t=x.util.createCanvasElement();t.width=this.width,t.height=this.height;var i=new x.Canvas(t);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),e&&e(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):e&&e(i)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n=t.util.toFixed,s=t.util.string.capitalize,o=t.util.degreesToRadians,a=!t.isLikelyNode;t.Object||(t.Object=t.util.createClass(t.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(e){e&&this.setOptions(e)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=t.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(e){var i=t.perfLimitSizeTotal,r=e.width,n=e.height,s=t.maxCacheSideLimit,o=t.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(e.zoomX/=r/c,e.width=c,e.capped=!0),n>u&&(e.zoomY/=n/u,e.height=u,e.capped=!0),e},_getCacheCanvasDimensions:function(){var e=this.getTotalObjectScaling(),t=this._getTransformedDimensions(0,0),i=t.x*e.scaleX/this.scaleX,r=t.y*e.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:e.scaleX,zoomY:e.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var e=this.canvas;if(this.noScaleCache&&e&&e._currentTransform){var i=e._currentTransform.target,r=e._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=t.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,_=f||g,p=0,m=0,v=!1;if(f){var y=this._cacheCanvas.width,S=this._cacheCanvas.height,w=l>y||c>S;v=w||(l<.9*y||c<.9*S)&&y>h&&S>h,w&&!a.capped&&(l>h||c>h)&&(p=.1*l,m=.1*c)}return this instanceof t.Text&&this.path&&(_=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!_&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+m)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(e){this._setOptions(e),this._initGradient(e.fill,"fill"),this._initGradient(e.stroke,"stroke"),this._initPattern(e.fill,"fill"),this._initPattern(e.stroke,"stroke")},transform:function(e){var t=this.group&&!this.group._transformDone||this.group&&this.canvas&&e===this.canvas.contextTop,i=this.calcTransformMatrix(!t);e.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(e){var i=t.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:t.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(e),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),t.util.populateWithProperties(this,r,e),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(e){return this.toObject(e)},_removeDefaultValues:function(e){var i=t.util.getKlass(e.type).prototype;return i.stateProperties.forEach((function(t){"left"!==t&&"top"!==t&&(e[t]===i[t]&&delete e[t],Array.isArray(e[t])&&Array.isArray(i[t])&&0===e[t].length&&0===i[t].length&&delete e[t])})),e},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var e=t.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(e.scaleX),scaleY:Math.abs(e.scaleY)}},getTotalObjectScaling:function(){var e=this.getObjectScaling(),t=e.scaleX,i=e.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();t*=r*n,i*=r*n}return{scaleX:t,scaleY:i}},getObjectOpacity:function(){var e=this.opacity;return this.group&&(e*=this.group.getObjectOpacity()),e},_set:function(e,i){var r="scaleX"===e||"scaleY"===e,n=this[e]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===e&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===e&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==e||!i||i instanceof t.Shadow?"dirty"===e&&this.group&&this.group.set("dirty",i):i=new t.Shadow(i),this[e]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(e)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(e)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:t.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(e){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(e.save(),this._setupCompositeOperation(e),this.drawSelectionBackground(e),this.transform(e),this._setOpacity(e),this._setShadow(e,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(e)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(e),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),e.restore())},renderCache:function(e){e=e||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,e.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(e,i){if(e.save(),i.inverted?e.globalCompositeOperation="destination-out":e.globalCompositeOperation="destination-in",i.absolutePositioned){var r=t.util.invertTransform(this.calcTransformMatrix());e.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(e),e.scale(1/i.zoomX,1/i.zoomY),e.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),e.restore()},drawObject:function(e,t){var i=this.fill,r=this.stroke;t?(this.fill="black",this.stroke="",this._setClippingProperties(e)):this._renderBackground(e),this._render(e),this._drawClipPath(e,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(e,t){t&&(t.canvas=this.canvas,t.shouldCache(),t._transformDone=!0,t.renderCache({forClipping:!0}),this.drawClipPathOnCache(e,t))},drawCacheOnCanvas:function(e){e.scale(1/this.zoomX,1/this.zoomY),e.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(e){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!e&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!e){var t=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-t/2,-i/2,t,i)}return!0}return!1},_renderBackground:function(e){if(this.backgroundColor){var t=this._getNonTransformedDimensions();e.fillStyle=this.backgroundColor,e.fillRect(-t.x/2,-t.y/2,t.x,t.y),this._removeShadow(e)}},_setOpacity:function(e){this.group&&!this.group._transformDone?e.globalAlpha=this.getObjectOpacity():e.globalAlpha*=this.opacity},_setStrokeStyles:function(e,t){var i=t.stroke;i&&(e.lineWidth=t.strokeWidth,e.lineCap=t.strokeLineCap,e.lineDashOffset=t.strokeDashOffset,e.lineJoin=t.strokeLineJoin,e.miterLimit=t.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(e,i):(e.strokeStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,i)):e.strokeStyle=t.stroke)},_setFillStyles:function(e,t){var i=t.fill;i&&(i.toLive?(e.fillStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,t.fill)):e.fillStyle=i)},_setClippingProperties:function(e){e.globalAlpha=1,e.strokeStyle="transparent",e.fillStyle="#000000"},_setLineDash:function(e,t){t&&0!==t.length&&(1&t.length&&t.push.apply(t,t),e.setLineDash(t))},_renderControls:function(e,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=t.util.multiplyTransformMatrices(a,h),r=t.util.qrDecompose(h),e.save(),e.translate(r.translateX,r.translateY),e.lineWidth=1*this.borderScaleFactor,this.group||(e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),e.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(e,r,i):n&&this.drawBorders(e,i),s&&this.drawControls(e,i),e.restore()},_setShadow:function(e){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=t.devicePixelRatio,o*=t.devicePixelRatio),e.shadowColor=r.color,e.shadowBlur=r.blur*t.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,e.shadowOffsetX=r.offsetX*s*i.scaleX,e.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(e){this.shadow&&(e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0)},_applyPatternGradientTransform:function(e,t){if(!t||!t.toLive)return{offsetX:0,offsetY:0};var i=t.gradientTransform||t.patternTransform,r=-this.width/2+t.offsetX||0,n=-this.height/2+t.offsetY||0;return"percentage"===t.gradientUnits?e.transform(this.width,0,0,this.height,r,n):e.transform(1,0,0,1,r,n),i&&e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(e){"stroke"===this.paintFirst?(this._renderStroke(e),this._renderFill(e)):(this._renderFill(e),this._renderStroke(e))},_render:function(){},_renderFill:function(e){this.fill&&(e.save(),this._setFillStyles(e,this),"evenodd"===this.fillRule?e.fill("evenodd"):e.fill(),e.restore())},_renderStroke:function(e){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this.strokeUniform&&this.group){var t=this.getObjectScaling();e.scale(1/t.scaleX,1/t.scaleY)}else this.strokeUniform&&e.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(e,this.strokeDashArray),this._setStrokeStyles(e,this),e.stroke(),e.restore()}},_applyPatternForTransformedGradient:function(e,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=t.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(e),r.fill(),e.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),e.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),e.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var e=t.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",e.scaleX),this.set("scaleY",e.scaleY),this.angle=e.angle,this.skewX=e.skewX,this.skewY=0}},_removeTransformMatrix:function(e){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=t.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,e&&(this.scaleX*=e.scaleX,this.scaleY*=e.scaleY,this.cropX=e.cropX,this.cropY=e.cropY,i.x+=e.offsetLeft,i.y+=e.offsetTop,this.width=e.width,this.height=e.height),this.setPositionByOrigin(i,"center","center")},clone:function(e,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,e):t.Object._fromObject("Object",r,e)},cloneAsImage:function(e,i){var r=this.toCanvasElement(i);return e&&e(new t.Image(r)),this},toCanvasElement:function(e){e||(e={});var i=t.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(e.multiplier||1)*(e.enableRetinaScaling?t.devicePixelRatio:1);delete this.group,e.withoutTransform&&i.resetObjectTransform(this),e.withoutShadow&&(this.shadow=null);var h,l,c,u,d=t.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),_.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+_.x,u=f.height+_.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new t.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===e.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new t.Point(p.width/2,p.height/2),"center","center");var m=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,e);return this.shadow=s,this.set("canvas",m),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(e){return e||(e={}),t.util.toDataURL(this.toCanvasElement(e),e.format||"png",e.quality||1)},isType:function(e){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===e},complexity:function(){return 1},toJSON:function(e){return this.toObject(e)},rotate:function(e){var t=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return t&&this._setOriginToCenter(),this.set("angle",e),t&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(e,i){i=i||this.canvas.getPointer(e);var r=new t.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=t.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(e){this.globalCompositeOperation&&(e.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){t.runningAnimations&&t.runningAnimations.cancelByTarget(this)}}),t.util.createAccessors&&t.util.createAccessors(t.Object),i(t.Object.prototype,t.Observable),t.Object.NUM_FRACTION_DIGITS=2,t.Object.ENLIVEN_PROPS=["clipPath"],t.Object._fromObject=function(e,i,n,s){var o=t[e];i=r(i,!0),t.util.enlivenPatterns([i.fill,i.stroke],(function(e){void 0!==e[0]&&(i.fill=e[0]),void 0!==e[1]&&(i.stroke=e[1]),t.util.enlivenObjectEnlivables(i,i,(function(){var e=s?new o(i[s],i):new o(i);n&&n(e)}))}))},t.Object.__uid=0)}(t),S=x.util.degreesToRadians,w={left:-.5,center:0,right:.5},b={top:-.5,center:0,bottom:.5},x.util.object.extend(x.Object.prototype,{translateToGivenOrigin:function(e,t,i,r,n){var s,o,a,h=e.x,l=e.y;return"string"==typeof t?t=w[t]:t-=.5,"string"==typeof r?r=w[r]:r-=.5,"string"==typeof i?i=b[i]:i-=.5,"string"==typeof n?n=b[n]:n-=.5,o=n-i,((s=r-t)||o)&&(a=this._getTransformedDimensions(),h=e.x+s*a.x,l=e.y+o*a.y),new x.Point(h,l)},translateToCenterPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,t,i,"center","center");return this.angle?x.util.rotatePoint(r,e,S(this.angle)):r},translateToOriginPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,"center","center",t,i);return this.angle?x.util.rotatePoint(r,e,S(this.angle)):r},getCenterPoint:function(){var e=new x.Point(this.left,this.top);return this.translateToCenterPoint(e,this.originX,this.originY)},getPointByOrigin:function(e,t){var i=this.getCenterPoint();return this.translateToOriginPoint(i,e,t)},toLocalPoint:function(e,t,i){var r,n,s=this.getCenterPoint();return r=void 0!==t&&void 0!==i?this.translateToGivenOrigin(s,"center","center",t,i):new x.Point(this.left,this.top),n=new x.Point(e.x,e.y),this.angle&&(n=x.util.rotatePoint(n,s,-S(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(e,t,i){var r=this.translateToCenterPoint(e,t,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(e){var t,i,r=S(this.angle),n=this.getScaledWidth(),s=x.util.cos(r)*n,o=x.util.sin(r)*n;t="string"==typeof this.originX?w[this.originX]:this.originX-.5,i="string"==typeof e?w[e]:e-.5,this.left+=s*(i-t),this.top+=o*(i-t),this.setCoords(),this.originX=e},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var e=this.getCenterPoint();this.originX="center",this.originY="center",this.left=e.x,this.top=e.y},_resetOrigin:function(){var e=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=e.x,this.top=e.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var e=x.util,t=e.degreesToRadians,i=e.multiplyTransformMatrices,r=e.transformPoint;e.object.extend(x.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(e,t){return t?e?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),e?this.aCoords:this.lineCoords)},getCoords:function(e,t){return i=this._getCoords(e,t),[new x.Point(i.tl.x,i.tl.y),new x.Point(i.tr.x,i.tr.y),new x.Point(i.br.x,i.br.y),new x.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(e,t,i,r){var n=this.getCoords(i,r);return"Intersection"===x.Intersection.intersectPolygonRectangle(n,e,t).status},intersectsWithObject:function(e,t,i){return"Intersection"===x.Intersection.intersectPolygonPolygon(this.getCoords(t,i),e.getCoords(t,i)).status||e.isContainedWithinObject(this,t,i)||this.isContainedWithinObject(e,t,i)},isContainedWithinObject:function(e,t,i){for(var r=this.getCoords(t,i),n=t?e.aCoords:e.lineCoords,s=0,o=e._getImageLines(n);s<4;s++)if(!e.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(e,t,i,r){var n=this.getBoundingRect(i,r);return n.left>=e.x&&n.left+n.width<=t.x&&n.top>=e.y&&n.top+n.height<=t.y},containsPoint:function(e,t,i,r){var n=this._getCoords(i,r),s=(t=t||this._getImageLines(n),this._findCrossPoints(e,t));return 0!==s&&s%2==1},isOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,e).some((function(e){return e.x<=i.x&&e.x>=t.x&&e.y<=i.y&&e.y>=t.y}))||!!this.intersectsWithRect(t,i,!0,e)||this._containsCenterOfCanvas(t,i,e)},_containsCenterOfCanvas:function(e,t,i){var r={x:(e.x+t.x)/2,y:(e.y+t.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(t,i,!0,e)||this.getCoords(!0,e).every((function(e){return(e.x>=i.x||e.x<=t.x)&&(e.y>=i.y||e.y<=t.y)}))&&this._containsCenterOfCanvas(t,i,e)},_getImageLines:function(e){return{topline:{o:e.tl,d:e.tr},rightline:{o:e.tr,d:e.br},bottomline:{o:e.br,d:e.bl},leftline:{o:e.bl,d:e.tl}}},_findCrossPoints:function(e,t){var i,r,n,s=0;for(var o in t)if(!((n=t[o]).o.y=e.y&&n.d.y>=e.y||(n.o.x===n.d.x&&n.o.x>=e.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(e.y-0*e.x-(n.o.y-i*n.o.x))/(0-i)),r>=e.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(t,i){var r=this.getCoords(t,i);return e.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(e){return Math.abs(e)\n')}},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(e),{reviver:e})},toClipPathSVG:function(e){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(e),{reviver:e})},_createBaseClipPathSVGMarkup:function(e,t){var i=(t=t||{}).reviver,r=t.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=e.indexOf("COMMON_PARTS");return e[s]=n,i?i(e.join("")):e.join("")},_createBaseSVGMarkup:function(e,t){var i,r,n=(t=t||{}).noStyle,s=t.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=t.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=e.indexOf("COMMON_PARTS"),p=t.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+x.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),e[_]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(e.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var e=x.util.object.extend,t="stateProperties";function i(t,i,r){var n={};r.forEach((function(e){n[e]=t[e]})),e(t[i],n,!0)}function r(e,t,i){if(e===t)return!0;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(var n=0,s=e.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(t?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(e){for(var t in this.controls)e(this.controls[t],t,this)},_setCornerCoords:function(){var e=this.oCoords;for(var t in e){var i=this.controls[t];e[t].corner=i.calcCornerCoords(this.angle,this.cornerSize,e[t].x,e[t].y,!1),e[t].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,e[t].x,e[t].y,!0)}},drawSelectionBackground:function(t){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;t.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return t.translate(i.x,i.y),t.scale(1/n[0],1/n[3]),t.rotate(e(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-r.x/2,-r.y/2,r.x,r.y),t.restore(),this},drawBorders:function(e,t){t=t||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==t.hasControls?t.hasControls:this.hasControls,a=!1;return e.save(),e.strokeStyle=t.borderColor||this.borderColor,this._setLineDash(e,t.borderDashArray||this.borderDashArray),e.strokeRect(-n/2,-s/2,n,s),o&&(e.beginPath(),this.forEachControl((function(t,i,r){t.withConnection&&t.getVisibility(r,i)&&(a=!0,e.moveTo(t.x*n,t.y*s),e.lineTo(t.x*n+t.offsetX,t.y*s+t.offsetY))})),a&&e.stroke()),e.restore(),this},drawBordersInGroup:function(e,t,i){i=i||{};var r=x.util.sizeAfterTransform(this.width,this.height,t),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():t.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():t.scaleY)+o;return e.save(),this._setLineDash(e,i.borderDashArray||this.borderDashArray),e.strokeStyle=i.borderColor||this.borderColor,e.strokeRect(-a/2,-h/2,a,h),e.restore(),this},drawControls:function(e,t){t=t||{},e.save();var i,r,n=this.canvas.getRetinaScaling();return e.setTransform(n,0,0,n,0,0),e.strokeStyle=e.fillStyle=t.cornerColor||this.cornerColor,this.transparentCorners||(e.strokeStyle=t.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(e,t.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=x.util.transformPoint(r,i)),n.render(e,r.x,r.y,t,o))})),e.restore(),this},isControlVisible:function(e){return this.controls[e]&&this.controls[e].getVisibility(this,e)},setControlVisible:function(e,t){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[e]=t,this},setControlsVisibility:function(e){for(var t in e||(e={}),e)this.setControlVisible(t,e[t]);return this},onDeselect:function(){},onSelect:function(){}})}(),x.util.object.extend(x.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(t){e.set("left",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxCenterObjectV:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(t){e.set("top",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxRemove:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(t){e.set("opacity",t),s.requestRenderAll(),n()},onComplete:function(){s.remove(e),r()}})}}),x.util.object.extend(x.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var e,t,i=[],r=[];for(e in arguments[0])i.push(e);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(e);"from"in i||(i.from=a),o||(t=~t.indexOf("=")?a+parseFloat(t.replace("=","")):parseFloat(t));var h={target:this,startValue:i.from,endValue:t,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(e,t,r){return i.abort.call(s,e,t,r)},onChange:function(t,o,a){n?s[n[0]][n[1]]=t:s.set(e,t),r||i.onChange&&i.onChange(t,o,a)},onComplete:function(e,t,n){r||(s.setCoords(),i.onComplete&&i.onComplete(e,t,n))}};return o?x.util.animateColor(h.startValue,h.endValue,h.duration,h):x.util.animate(h)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(e,t){var i=e.origin,r=e.axis1,n=e.axis2,s=e.dimension,o=t.nearest,a=t.center,h=t.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}t.Line?t.warn("fabric.Line is already defined"):(t.Line=t.util.createClass(t.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:t.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(e,t){e||(e=[0,0,0,0]),this.callSuper("initialize",t),this.set("x1",e[0]),this.set("y1",e[1]),this.set("x2",e[2]),this.set("y2",e[3]),this._setWidthHeight(t)},_setWidthHeight:function(e){e||(e={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in e?e.left:this._getLeftToOriginX(),this.top="top"in e?e.top:this._getTopToOriginY()},_set:function(e,t){return this.callSuper("_set",e,t),void 0!==n[e]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(e){e.beginPath();var t=this.calcLinePoints();e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineWidth=this.strokeWidth;var i=e.strokeStyle;e.strokeStyle=this.stroke||e.fillStyle,this.stroke&&this._renderStroke(e),e.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(e){return i(this.callSuper("toObject",e),this.calcLinePoints())},_getNonTransformedDimensions:function(){var e=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(e.y-=this.strokeWidth),0===this.height&&(e.x-=this.strokeWidth)),e},calcLinePoints:function(){var e=this.x1<=this.x2?-1:1,t=this.y1<=this.y2?-1:1,i=e*this.width*.5,r=t*this.height*.5;return{x1:i,x2:e*this.width*-.5,y1:r,y2:t*this.height*-.5}},_toSVG:function(){var e=this.calcLinePoints();return["\n']}}),t.Line.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),t.Line.fromElement=function(e,r,n){n=n||{};var s=t.parseAttributes(e,t.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new t.Line(o,i(s,n)))},t.Line.fromObject=function(e,i){var n=r(e,!0);n.points=[e.x1,e.y1,e.x2,e.y2],t.Object._fromObject("Line",n,(function(e){delete e.points,i&&i(e)}),"points")})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians;t.Circle?t.warn("fabric.Circle is already defined."):(t.Circle=t.util.createClass(t.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:t.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(e,t){return this.callSuper("_set",e,t),"radius"===e&&this.setRadius(t),this},toObject:function(e){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(e))},_toSVG:function(){var e,r=(this.endAngle-this.startAngle)%360;if(0===r)e=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;e=['180?"1":"0")+" 1"," "+t.util.cos(s)*o+" "+t.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return e},_render:function(e){e.beginPath(),e.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(e)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(e){return this.radius=e,this.set("width",2*e).set("height",2*e)}}),t.Circle.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),t.Circle.fromElement=function(e,i){var r,n=t.parseAttributes(e,t.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new t.Circle(n))},t.Circle.fromObject=function(e,i){t.Object._fromObject("Circle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={});t.Triangle?t.warn("fabric.Triangle is already defined"):(t.Triangle=t.util.createClass(t.Object,{type:"triangle",width:100,height:100,_render:function(e){var t=this.width/2,i=this.height/2;e.beginPath(),e.moveTo(-t,i),e.lineTo(0,-i),e.lineTo(t,i),e.closePath(),this._renderPaintInOrder(e)},_toSVG:function(){var e=this.width/2,t=this.height/2;return["']}}),t.Triangle.fromObject=function(e,i){return t.Object._fromObject("Triangle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=2*Math.PI;t.Ellipse?t.warn("fabric.Ellipse is already defined."):(t.Ellipse=t.util.createClass(t.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this.set("rx",e&&e.rx||0),this.set("ry",e&&e.ry||0)},_set:function(e,t){switch(this.callSuper("_set",e,t),e){case"rx":this.rx=t,this.set("width",2*t);break;case"ry":this.ry=t,this.set("height",2*t)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']},_render:function(e){e.beginPath(),e.save(),e.transform(1,0,0,this.ry/this.rx,0,0),e.arc(0,0,this.rx,0,i,!1),e.restore(),this._renderPaintInOrder(e)}}),t.Ellipse.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),t.Ellipse.fromElement=function(e,i){var r=t.parseAttributes(e,t.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new t.Ellipse(r))},t.Ellipse.fromObject=function(e,i){t.Object._fromObject("Ellipse",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend;t.Rect?t.warn("fabric.Rect is already defined"):(t.Rect=t.util.createClass(t.Object,{stateProperties:t.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(e){var t=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==t||0!==i,h=.4477152502;e.beginPath(),e.moveTo(s+t,o),e.lineTo(s+r-t,o),a&&e.bezierCurveTo(s+r-h*t,o,s+r,o+h*i,s+r,o+i),e.lineTo(s+r,o+n-i),a&&e.bezierCurveTo(s+r,o+n-h*i,s+r-h*t,o+n,s+r-t,o+n),e.lineTo(s+t,o+n),a&&e.bezierCurveTo(s+h*t,o+n,s,o+n-h*i,s,o+n-i),e.lineTo(s,o+i),a&&e.bezierCurveTo(s,o+h*i,s+h*t,o,s+t,o),e.closePath(),this._renderPaintInOrder(e)},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']}}),t.Rect.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),t.Rect.fromElement=function(e,r,n){if(!e)return r(null);n=n||{};var s=t.parseAttributes(e,t.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new t.Rect(i(n?t.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},t.Rect.fromObject=function(e,i){return t.Object._fromObject("Rect",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.array.min,n=t.util.array.max,s=t.util.toFixed,o=t.util.projectStrokeOnPoints;t.Polyline?t.warn("fabric.Polyline is already defined"):(t.Polyline=t.util.createClass(t.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:t.Object.prototype.cacheProperties.concat("points"),initialize:function(e,t){t=t||{},this.points=e||[],this.callSuper("initialize",t),this._setPositionDimensions(t)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(e){var t,i=this._calcDimensions(e),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,e.fromSVG||(t=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===e.left&&(this.left=e.fromSVG?i.left:t.x),void 0===e.top&&(this.top=e.fromSVG?i.top:t.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var e=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,t=r(e,"x")||0,i=r(e,"y")||0;return{left:t,top:i,width:(n(e,"x")||0)-t,height:(n(e,"y")||0)-i}},toObject:function(e){return i(this.callSuper("toObject",e),{points:this.points.concat()})},_toSVG:function(){for(var e=[],i=this.pathOffset.x,r=this.pathOffset.y,n=t.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(e){var t,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;e.beginPath(),e.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(e){return n(this.callSuper("toObject",e),{path:this.path.map((function(e){return e.slice()}))})},toDatalessObject:function(e){var t=this.toObject(["sourcePath"].concat(e));return t.sourcePath&&delete t.path,t},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var e=t.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,e)+", "+o(-this.pathOffset.y,e)+")"},toClipPathSVG:function(e){var t=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},toSVG:function(e){var t=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var e,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(e){var i=!!this.group;return this._restoreObjectsState(),t.util.resetObjectTransform(this),e&&(i&&t.util.removeTransformFromObject(e,this.group.calcTransformMatrix()),this._objects.push(e),e.group=this,e._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(e){return this._restoreObjectsState(),t.util.resetObjectTransform(this),this.remove(e),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(e){this.dirty=!0,e.group=this,e._set("canvas",this.canvas)},_onObjectRemoved:function(e){this.dirty=!0,delete e.group},_set:function(e,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(e,i);if("canvas"===e)for(;r--;)this._objects[r]._set(e,i);t.Object.prototype._set.call(this,e,i)},toObject:function(e){var i=this.includeDefaultValues,r=this._objects.filter((function(e){return!e.excludeFromExport})).map((function(t){var r=t.includeDefaultValues;t.includeDefaultValues=i;var n=t.toObject(e);return t.includeDefaultValues=r,n})),n=t.Object.prototype.toObject.call(this,e);return n.objects=r,n},toDatalessObject:function(e){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(t){var i=t.includeDefaultValues;t.includeDefaultValues=n;var r=t.toDatalessObject(e);return t.includeDefaultValues=i,r}))}var s=t.Object.prototype.toDatalessObject.call(this,e);return s.objects=i,s},render:function(e){this._transformDone=!0,this.callSuper("render",e),this._transformDone=!1},shouldCache:function(){var e=t.Object.prototype.shouldCache.call(this);if(e)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),t},getSvgStyles:function(){var e=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",t=this.visible?"":" visibility: hidden;";return[e,this.getSvgFilter(),t].join("")},toClipPathSVG:function(e){for(var t=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(e,t,i){e.save(),e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",e,t),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,e=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?t.concat(e,i):t.concat(i,e)},getSrc:function(e){var t=e?this._element:this._originalElement;return t?t.toDataURL?t.toDataURL():this.srcFromAttribute?t.getAttribute("src"):t.src:this.src||""},setSrc:function(e,t,i){return x.util.loadImage(e,(function(e,r){this.setElement(e,i),this._setWidthHeight(),t&&t(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var e=this.resizeFilter,t=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!e||r>t&&n>t)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);x.filterBackend||(x.filterBackend=x.initFilterBackend());var o=x.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=n,x.filterBackend.applyFilters([e],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(e){if(e=(e=e||this.filters||[]).filter((function(e){return e&&!e.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===e.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var t=this._originalElement,i=t.naturalWidth||t.width,r=t.naturalHeight||t.height;if(this._element===this._originalElement){var n=x.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return x.filterBackend||(x.filterBackend=x.initFilterBackend()),x.filterBackend.applyFilters(e,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(e){x.util.setImageSmoothing(e,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(e),this._renderPaintInOrder(e)},drawCacheOnCanvas:function(e){x.util.setImageSmoothing(e,this.imageSmoothing),x.Object.prototype.drawCacheOnCanvas.call(this,e)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(e){var t=this._element;if(t){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=t.naturalWidth||t.width,u=t.naturalHeight||t.height,d=h*i,f=l*r,g=o(n*i,c-d),_=o(s*r,u-f),p=-n/2,m=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);t&&e.drawImage(t,d,f,g,_,p,m,v,y)}},_needsResize:function(){var e=this.getTotalObjectScaling();return e.scaleX!==this._lastScaleX||e.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(e,t){this.setElement(x.util.getById(e),t),x.util.addClass(this.getElement(),x.Image.CSS_CANVAS)},_initConfig:function(e){e||(e={}),this.setOptions(e),this._setWidthHeight(e)},_initFilters:function(e,t){e&&e.length?x.util.enlivenObjects(e,(function(e){t&&t(e)}),"fabric.Image.filters"):t&&t()},_setWidthHeight:function(e){e||(e={});var t=this.getElement();this.width=e.width||t.naturalWidth||t.width||0,this.height=e.height||t.naturalHeight||t.height||0},parsePreserveAspectRatioAttribute:function(){var e,t=x.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!t||"none"===t.alignX&&"none"===t.alignY?(n=c/i,s=u/r):("meet"===t.meetOrSlice&&(e=(c-i*(n=s=x.util.findScaleToFit(this._element,d)))/2,"Min"===t.alignX&&(o=-e),"Max"===t.alignX&&(o=e),e=(u-r*s)/2,"Min"===t.alignY&&(a=-e),"Max"===t.alignY&&(a=e)),"slice"===t.meetOrSlice&&(e=i-c/(n=s=x.util.findScaleToCover(this._element,d)),"Mid"===t.alignX&&(h=e/2),"Max"===t.alignX&&(h=e),e=r-u/s,"Mid"===t.alignY&&(l=e/2),"Max"===t.alignY&&(l=e),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),x.Image.CSS_CANVAS="canvas-img",x.Image.prototype.getSvgSrc=x.Image.prototype.getSrc,x.Image.fromObject=function(e,t){var i=x.util.object.clone(e);x.util.loadImage(i.src,(function(e,r){r?t&&t(null,!0):x.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],x.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],x.util.enlivenObjectEnlivables(i,i,(function(){var r=new x.Image(e,i);t(r,!1)}))}))}))}),null,i.crossOrigin)},x.Image.fromURL=function(e,t,i){x.util.loadImage(e,(function(e,r){t&&t(new x.Image(e,i),r)}),null,i&&i.crossOrigin)},x.Image.ATTRIBUTE_NAMES=x.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),x.Image.fromElement=function(e,i,r){var n=x.parseAttributes(e,x.Image.ATTRIBUTE_NAMES);x.Image.fromURL(n["xlink:href"],i,t(r?x.util.object.clone(r):{},n))})}(t),x.util.object.extend(x.Object.prototype,{_getAngleValueForStraighten:function(){var e=this.angle%360;return e>0?90*Math.round((e-1)/90):90*Math.round(e/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(e){var t=function(){},i=(e=e||{}).onComplete||t,r=e.onChange||t,n=this;return x.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(e){n.rotate(e),r()},onComplete:function(){n.setCoords(),i()}})}}),x.util.object.extend(x.StaticCanvas.prototype,{straightenObject:function(e){return e.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(e){return e.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function e(e,t){var i="precision "+t+" float;\nvoid main(){}",r=e.createShader(e.FRAGMENT_SHADER);return e.shaderSource(r,i),e.compileShader(r),!!e.getShaderParameter(r,e.COMPILE_STATUS)}function t(e){e&&e.tileSize&&(this.tileSize=e.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}x.isWebglSupported=function(t){if(x.isLikelyNode)return!1;t=t||x.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){x.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=x.maxTextureSize>=t;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(e(r,s[o])){x.webGlPrecision=s[o];break}}return this.isSupported=n,n},x.WebglFilterBackend=t,t.prototype={tileSize:2048,resources:{},setupGLContext:function(e,t){this.dispose(),this.createWebGLCanvas(e,t),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(e,t)},chooseFastestCopyGLTo2DMethod:function(e,t){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(e){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=x.util.createCanvasElement(),a=new ArrayBuffer(e*t*4);if(x.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=A);var h,l,c={imageBuffer:a,destinationWidth:e,destinationHeight:t,targetCanvas:o};o.width=e,o.height=t,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),A.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=A):this.copyGLTo2D=I}},createWebGLCanvas:function(e,t){var i=x.util.createCanvasElement();i.width=e,i.height=t;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(e,t,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,t));var h={originalWidth:t.width||t.originalWidth,originalHeight:t.height||t.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&t),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&t),passes:e.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),e.forEach((function(e){e&&e.applyTo(h)})),function(e){var t=e.targetCanvas,i=t.width,r=t.height,n=e.destinationWidth,s=e.destinationHeight;i===n&&r===s||(t.width=n,t.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(e,t,i,r){var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),r?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,i,0,e.RGBA,e.UNSIGNED_BYTE,null),n},getCachedTexture:function(e,t){if(this.textureCache[e])return this.textureCache[e];var i=this.createTexture(this.gl,t.width,t.height,t);return this.textureCache[e]=i,i},evictCachesForKey:function(e){this.textureCache[e]&&(this.gl.deleteTexture(this.textureCache[e]),delete this.textureCache[e])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var e=this.gl,t={renderer:"",vendor:""};if(!e)return t;var i=e.getExtension("WEBGL_debug_renderer_info");if(i){var r=e.getParameter(i.UNMASKED_RENDERER_WEBGL),n=e.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(t.renderer=r.toLowerCase()),n&&(t.vendor=n.toLowerCase())}return this.gpuInfo=t,t}}}(),function(){var e=function(){};function t(){}x.Canvas2dFilterBackend=t,t.prototype={evictCachesForKey:e,dispose:e,clearWebGLCaches:e,resources:{},applyFilters:function(e,t,i,r,n){var s=n.getContext("2d");s.drawImage(t,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:t,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return e.forEach((function(e){e.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),x.Image=x.Image||{},x.Image.filters=x.Image.filters||{},x.Image.filters.BaseFilter=x.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(e){e&&this.setOptions(e)},setOptions:function(e){for(var t in e)this[t]=e[t]},createProgram:function(e,t,i){t=t||this.fragmentSource,i=i||this.vertexSource,"highp"!==x.webGlPrecision&&(t=t.replace(/precision highp float/g,"precision "+x.webGlPrecision+" float"));var r=e.createShader(e.VERTEX_SHADER);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+e.getShaderInfoLog(r));var n=e.createShader(e.FRAGMENT_SHADER);if(e.shaderSource(n,t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+e.getShaderInfoLog(n));var s=e.createProgram();if(e.attachShader(s,r),e.attachShader(s,n),e.linkProgram(s),!e.getProgramParameter(s,e.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+e.getProgramInfoLog(s));var o=this.getAttributeLocations(e,s),a=this.getUniformLocations(e,s)||{};return a.uStepW=e.getUniformLocation(s,"uStepW"),a.uStepH=e.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(e,t){return{aPosition:e.getAttribLocation(t,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(e,t,i){var r=t.aPosition,n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW)},_setupFrameBuffer:function(e){var t,i,r=e.context;e.passes>1?(t=e.destinationWidth,i=e.destinationHeight,e.sourceWidth===t&&e.sourceHeight===i||(r.deleteTexture(e.targetTexture),e.targetTexture=e.filterBackend.createTexture(r,t,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(e){e.passes--,e.pass++;var t=e.targetTexture;e.targetTexture=e.sourceTexture,e.sourceTexture=t},isNeutralState:function(){var e=this.mainParameter,t=x.Image.filters[this.type].prototype;if(e){if(Array.isArray(t[e])){for(var i=t[e].length;i--;)if(this[e][i]!==t[e][i])return!1;return!0}return t[e]===this[e]}return!1},applyTo:function(e){e.webgl?(this._setupFrameBuffer(e),this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)},retrieveShader:function(e){return e.programCache.hasOwnProperty(this.type)||(e.programCache[this.type]=this.createProgram(e.context)),e.programCache[this.type]},applyToWebGL:function(e){var t=e.context,i=this.retrieveShader(e);0===e.pass&&e.originalTexture?t.bindTexture(t.TEXTURE_2D,e.originalTexture):t.bindTexture(t.TEXTURE_2D,e.sourceTexture),t.useProgram(i.program),this.sendAttributeData(t,i.attributeLocations,e.aPosition),t.uniform1f(i.uniformLocations.uStepW,1/e.sourceWidth),t.uniform1f(i.uniformLocations.uStepH,1/e.sourceHeight),this.sendUniformData(t,i.uniformLocations),t.viewport(0,0,e.destinationWidth,e.destinationHeight),t.drawArrays(t.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(e,t,i){e.activeTexture(i),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE0)},unbindAdditionalTexture:function(e,t){e.activeTexture(t),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(e){this[this.mainParameter]=e},sendUniformData:function(){},createHelpLayer:function(e){if(!e.helpLayer){var t=document.createElement("canvas");t.width=e.sourceWidth,t.height=e.sourceHeight,e.helpLayer=t}},toObject:function(){var e={type:this.type},t=this.mainParameter;return t&&(e[t]=this[t]),e},toJSON:function(){return this.toObject()}}),x.Image.filters.BaseFilter.fromObject=function(e,t){var i=new x.Image.filters[e.type](e);return t&&t(i),i},function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(e){this.callSuper("initialize",e),this.matrix=this.matrix.slice(0)},applyTo2d:function(e){var t,i,r,n,s,o=e.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=S||o<0||o>=y||(h=4*(a*y+o),l=p[f*m+d],t+=_[h]*l,i+=_[h+1]*l,r+=_[h+2]*l,C||(n+=_[h+3]*l));b[s]=t,b[s+1]=i,b[s+2]=r,b[s+3]=C?_[s+3]:n}e.imageData=w},getUniformLocations:function(e,t){return{uMatrix:e.getUniformLocation(t,"uMatrix"),uOpaque:e.getUniformLocation(t,"uOpaque"),uHalfSize:e.getUniformLocation(t,"uHalfSize"),uSize:e.getUniformLocation(t,"uSize")}},sendUniformData:function(e,t){e.uniform1fv(t.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),t.Image.filters.Convolute.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(e){var t,i,r=e.imageData.data,n=r.length,s=this.mode;for(t=0;tl[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[e]+"}\n}"},retrieveShader:function(e){var t,i=this.type+"_"+this.mode;return e.programCache.hasOwnProperty(i)||(t=this.buildSource(this.mode),e.programCache[i]=this.createProgram(e.context,t)),e.programCache[i]},applyTo2d:function(e){var i,r,n,s,o,a,h,l=e.imageData.data,c=l.length,u=1-this.alpha;i=(h=new t.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=e||t<=-e)return 0;if(t<1.1920929e-7&&t>-1.1920929e-7)return 1;var i=(t*=Math.PI)/e;return a(t)/t*a(i)/i}},applyTo2d:function(e){var t=e.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=t.width,a=t.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(e,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(e,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(e,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(e,s,a,h,l)),e.imageData=n},sliceByTwo:function(e,i,n,s,o){var a,h,l=e.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,_=t.filterBackend.resources,p=0,m=0,v=i,y=0;for(_.sliceByTwo||(_.sliceByTwo=document.createElement("canvas")),((a=_.sliceByTwo).width<1.5*i||a.height=t)){M=r(1e3*s(x-w.x)),S[M]||(S[M]={});for(var F=b.y-y;F<=b.y+y;F++)F<0||F>=o||(L=r(1e3*s(F-w.y)),S[M][L]||(S[M][L]=f(n(i(M*p,2)+i(L*m,2))/1e3)),(T=S[M][L])>0&&(A+=T,E+=T*c[I=4*(F*t+x)],O+=T*c[I+1],D+=T*c[I+2],R+=T*c[I+3]))}d[I=4*(C*a+h)]=E/A,d[I+1]=O/A,d[I+2]=D/A,d[I+3]=R/A}return++h1&&L<-1||(y=2*L*L*L-3*L*L+1)>0&&(T+=y*f[3+(M=4*(R+A*t))],w+=y,f[M+3]<255&&(y=y*f[M+3]/250),b+=y*f[M],C+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=b/S,_[v+1]=C/S,_[v+2]=x/S,_[v+3]=T/w}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),t.Image.filters.Resize.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(e){if(0!==this.contrast){var t,i=e.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(t=0;t1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio),e=t*this.blur*.12,this.horizontal?i[0]=e:i[1]=e,i}}),i.Blur.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(e){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,e)},applyTo2d:function(e){var t,i=e.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),t=0,n=256;t'},_getCacheCanvasDimensions:function(){var e=this.callSuper("_getCacheCanvasDimensions"),t=this.fontSize;return e.width+=t*e.zoomX,e.height+=t*e.zoomY,e},_render:function(e){var t=this.path;t&&!t.isNotVisible()&&t._render(e),this._setTextStyles(e),this._renderTextLinesBackground(e),this._renderTextDecoration(e,"underline"),this._renderText(e),this._renderTextDecoration(e,"overline"),this._renderTextDecoration(e,"linethrough")},_renderText:function(e){"stroke"===this.paintFirst?(this._renderTextStroke(e),this._renderTextFill(e)):(this._renderTextFill(e),this._renderTextStroke(e))},_setTextStyles:function(e,t,i){if(e.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":e.textBaseline="middle";break;case"ascender":e.textBaseline="top";break;case"descender":e.textBaseline="bottom"}e.font=this._getFontDeclaration(t,i)},calcTextWidth:function(){for(var e=this.getLineWidth(0),t=1,i=this._textLines.length;te&&(e=r)}return e},_renderTextLine:function(e,t,i,r,n,s){this._renderChars(e,t,i,r,n,s)},_renderTextLinesBackground:function(e){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var t,i,r,n,s,o,a,h=e.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,_=this._textLines.length;g<_;g++)if(t=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){r=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,n=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,m=r.length;p=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(e,i,r){var n=e+i.kernedWidth/2,s=this.path,o=t.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(e,t,i,r,n){var s,o=this.getCompleteStyleDeclaration(t,i),a=r?this.getCompleteStyleDeclaration(t,i-1):{},h=this._measureChar(e,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[t][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(e){if(this.__lineHeights[e])return this.__lineHeights[e];for(var t=this._textLines[e],i=this.getHeightOfChar(e,0),r=1,n=t.length;r0){var A=v+s+u;"rtl"===this.direction&&(A=this.width-A-d),l&&m&&(e.fillStyle=m,e.fillRect(A,c+b*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,m=p,r=n,o=a}else d+=f.kernedWidth;A=v+s+u,"rtl"===this.direction&&(A=this.width-A-d),e.fillStyle=p,g&&p&&e.fillRect(A,c+b*r+o,d-w,this.fontSize/15),y+=i}else y+=i;this._removeShadow(e)}},_getFontDeclaration:function(e,i){var r=e||this,n=this.fontFamily,s=t.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[t.isLikelyNode?r.fontWeight:r.fontStyle,t.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(e){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",e)))},_splitTextIntoLines:function(e){for(var i=e.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(e.underline=!0),e.textDecoration.indexOf("line-through")>-1&&(e.linethrough=!0),e.textDecoration.indexOf("overline")>-1&&(e.overline=!0),delete e.textDecoration)}x.IText=x.util.createClass(x.Text,x.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(e,t){this.callSuper("initialize",e,t),this.initBehavior()},setSelectionStart:function(e){e=Math.max(e,0),this._updateAndFire("selectionStart",e)},setSelectionEnd:function(e){e=Math.min(e,this.text.length),this._updateAndFire("selectionEnd",e)},_updateAndFire:function(e,t){this[e]!==t&&(this._fireSelectionChanged(),this[e]=t),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(e){this.clearContextTop(),this.callSuper("render",e),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(e){this.callSuper("_render",e)},clearContextTop:function(e){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this.canvas.contextTop,i=this.canvas.viewportTransform;t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(t),this._clearTextArea(t),e||t.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this._getCursorBoundaries(),t=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(e,t):this.renderSelection(e,t),t.restore()}},_clearTextArea:function(e){var t=this.width+4,i=this.height+4;e.clearRect(-t/2,-i/2,t,i)},_getCursorBoundaries:function(e){void 0===e&&(e=this.selectionStart);var t=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(e);return{left:t,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(e){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var t,i,r,n,s=0,o=0,a=this.get2DCursorLocation(e);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(e,t){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=e.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(e,t),t.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),t.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,t.fillRect(e.left+e.leftOffset-a/2,h+e.top+l,a,s)},renderSelection:function(e,t){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=e.left+f+_,y=p-_,S=g,w=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,w=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+w,y,S),e.topOffset+=d}},getCurrentCharFontSize:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fontSize")},getCurrentCharColor:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fill")},_getCurrentCharIndex:function(){var e=this.get2DCursorLocation(this.selectionStart,!0),t=e.charIndex>0?e.charIndex-1:0;return{l:e.lineIndex,c:t}}}),x.IText.fromObject=function(t,i){if(e(t),t.styles)for(var r in t.styles)for(var n in t.styles[r])e(t.styles[r][n]);x.Object._fromObject("IText",t,i,"text")}}(),C=x.util.object.clone,x.util.object.extend(x.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var e=this;this.on("added",(function(){var t=e.canvas;t&&(t._hasITextHandlers||(t._hasITextHandlers=!0,e._initCanvasHandlers(t)),t._iTextInstances=t._iTextInstances||[],t._iTextInstances.push(e))}))},initRemovedHandler:function(){var e=this;this.on("removed",(function(){var t=e.canvas;t&&(t._iTextInstances=t._iTextInstances||[],x.util.removeFromArray(t._iTextInstances,e),0===t._iTextInstances.length&&(t._hasITextHandlers=!1,e._removeCanvasHandlers(t)))}))},_initCanvasHandlers:function(e){e._mouseUpITextHandler=function(){e._iTextInstances&&e._iTextInstances.forEach((function(e){e.__isMousedown=!1}))},e.on("mouse:up",e._mouseUpITextHandler)},_removeCanvasHandlers:function(e){e.off("mouse:up",e._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(e,t,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},e.animate("_currentCursorOpacity",t,{duration:i,onComplete:function(){n.isAborted||e[r]()},onChange:function(){e.canvas&&e.selectionStart===e.selectionEnd&&e.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var e=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){e._currentTickCompleteState=e._animateCursor(e,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(e){var t=this,i=e?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){t._tick()}),i)},abortCursorAnimation:function(){var e=this._currentTickState||this._currentTickCompleteState,t=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,e&&t&&t.clearContext(t.contextTop||t.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(e){var t=0,i=e-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i--;for(;/\S/.test(this._text[i])&&i>-1;)t++,i--;return e-t},findWordBoundaryRight:function(e){var t=0,i=e;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i++;for(;/\S/.test(this._text[i])&&i-1;)t++,i--;return e-t},findLineBoundaryRight:function(e){for(var t=0,i=e;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=t):(this.selectionStart=t,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(e,t,i){var r=i.slice(0,e),n=x.util.string.graphemeSplit(r).length;if(e===t)return{selectionStart:n,selectionEnd:n};var s=i.slice(e,t);return{selectionStart:n,selectionEnd:n+x.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(e,t,i){var r=i.slice(0,e).join("").length;return e===t?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(e,t).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var e=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=e.selectionStart,this.hiddenTextarea.selectionEnd=e.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var e=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var e=this._calcTextareaPosition();this.hiddenTextarea.style.left=e.left,this.hiddenTextarea.style.top=e.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var e=this.inCompositionMode?this.compositionStart:this.selectionStart,t=this._getCursorBoundaries(e),i=this.get2DCursorLocation(e),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=t.leftOffset,a=this.calcTransformMatrix(),h={x:t.left+o,y:t.top+t.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,_=c.clientWidth/u,p=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=_,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var e=this._textBeforeEdit!==this.text,t=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),e&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),e&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var e in this.styles)this._textLines[e]||delete this.styles[e]},removeStyleFromTo:function(e,t){var i,r,n=this.get2DCursorLocation(e,!0),s=this.get2DCursorLocation(t,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(e,t){var i=C(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>e&&(this.styles[n+t]=i[n],i[n-t]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(e,t,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[e].length===t;for(var h in i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&(n=this.styles[e][0===t?t:t-1]),this.styles[e]){var l=parseInt(h,10);l>=t&&(o=!0,s[l-t]=this.styles[e][h],a&&0===t||delete this.styles[e][h])}var c=!1;for(o&&!a&&(this.styles[e+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[e+i]={0:C(r[i-1])}:n?this.styles[e+i]={0:C(n)}:delete this.styles[e+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(e,t,i,r){this.styles||(this.styles={});var n=this.styles[e],s=n?C(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=t&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[e]||(this.styles[e]={}),this.styles[e][t+i]=C(r[i]));else if(n)for(var h=n[t?t-1:1];h&&i--;)this.styles[e][t+i]=C(h)},insertNewStyleBlock:function(e,t,i){for(var r=this.get2DCursorLocation(t,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(e,t,i){i<=e?(t===e?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=e),this.selectionStart=i):i>e&&ie?this.selectionStart=e:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>e?this.selectionEnd=e:this.selectionEnd<0&&(this.selectionEnd=0)}}),x.util.object.extend(x.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(e){if(this.canvas){this.__newClickTime=+new Date;var t=e.pointer;this.isTripleClick(t)&&(this.fire("tripleclick",e),this._stopEvent(e.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=t,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(e){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===e.x&&this.__lastPointer.y===e.y},_stopEvent:function(e){e.preventDefault&&e.preventDefault(),e.stopPropagation&&e.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(e){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(e.e))},tripleClickHandler:function(e){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(e.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(e.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(e){if(this.__isMousedown=!1,!(!this.editable||this.group||e.transform&&e.transform.actionPerformed||e.e.button&&1!==e.e.button)){if(this.canvas){var t=this.canvas._activeObject;if(t&&t!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(e.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(e){var t=this.getSelectionStartFromPointer(e),i=this.selectionStart,r=this.selectionEnd;e.shiftKey?this.setSelectionStartEndWithShift(i,r,t):(this.selectionStart=t,this.selectionEnd=t),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(e){for(var t,i=this.getLocalPointer(e),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,t=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=t.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),x.util.object.extend(x.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=x.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var e=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+e.top+"; left: "+e.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+e.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):x.document.body.appendChild(this.hiddenTextarea),x.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),x.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),x.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),x.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(x.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(e){if(this.isEditing){var t="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(e.keyCode in t)this[t[e.keyCode]](e);else{if(!(e.keyCode in this.ctrlKeysMapDown)||!e.ctrlKey&&!e.metaKey)return;this[this.ctrlKeysMapDown[e.keyCode]](e)}e.stopImmediatePropagation(),e.preventDefault(),e.keyCode>=33&&e.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(e){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:e.keyCode in this.ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)&&(this[this.ctrlKeysMapUp[e.keyCode]](e),e.stopImmediatePropagation(),e.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(e){var t=this.fromPaste;if(this.fromPaste=!1,e&&e.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[e][t-1]).left+i.width),r},getDownCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||e.metaKey||34===e.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(e,t){return e.shiftKey&&this.selectionStart!==this.selectionEnd&&t?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||e.metaKey||33===e.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(e,t){for(var i,r,n=this._textLines[e],s=this._getLineLeftOffset(e),o=0,a=0,h=n.length;at){r=!0;var l=s-i,c=s,u=Math.abs(l-t);o=Math.abs(c-t)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",e)},moveCursorUp:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",e)},_moveCursorUpOrDown:function(e,t){var i=this["get"+e+"CursorOffset"](t,"right"===this._selectionDirection);t.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(e){var t="left"===this._selectionDirection?this.selectionStart+e:this.selectionEnd+e;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,t),0!==e},moveCursorWithoutShift:function(e){return e<0?(this.selectionStart+=e,this.selectionEnd=this.selectionStart):(this.selectionEnd+=e,this.selectionStart=this.selectionEnd),0!==e},moveCursorLeft:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",e)},_move:function(e,t,i){var r;if(e.altKey)r=this["findWordBoundary"+i](this[t]);else{if(!e.metaKey&&35!==e.keyCode&&36!==e.keyCode)return this[t]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[t])}if(void 0!==typeof r&&this[t]!==r)return this[t]=r,!0},_moveLeft:function(e,t){return this._move(e,t,"Left")},_moveRight:function(e,t){return this._move(e,t,"Right")},moveCursorLeftWithoutShift:function(e){var t=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(t=this._moveLeft(e,"selectionStart")),this.selectionEnd=this.selectionStart,t},moveCursorLeftWithShift:function(e){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(e,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(e,"selectionStart")):void 0},moveCursorRight:function(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",e)},_moveCursorLeftOrRight:function(e,t){var i="moveCursor"+e+"With";this._currentCursorOpacity=1,t.shiftKey?i+="Shift":i+="outShift",this[i](t)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(e){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(e,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(e,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(e){var t=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(t=this._moveRight(e,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,t},removeChars:function(e,t){void 0===t&&(t=e+1),this.removeStyleFromTo(e,t),this._text.splice(e,t-e),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(e,t,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=x.util.string.graphemeSplit(e);this.insertNewStyleBlock(n,i,t),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var e=x.util.toFixed,t=/ +/g;x.util.object.extend(x.Text.prototype,{_toSVG:function(){var e=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(e.textTop,e.textLeft);return this._wrapSVGTextAndBg(t)},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(e){var t=this.getSvgTextDecoration(this);return[e.textBgRects.join(""),'\t\t",e.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(e,t){var i,r=[],n=[],s=e;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",x.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(e,t,i,r){var n,s,o,a,h,l=this.getHeightOfLine(t),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[t];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)h=g===_||this.charSpacing,u+=f[g],o=this.__charBounds[t][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(t,g),s=this.getCompleteStyleDeclaration(t,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(t,g)||{},e.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(t,i,r,n,s,o){var a=x.Object.NUM_FRACTION_DIGITS;t.push("\t\t\n')},_setSVGTextLineBg:function(e,t,i,r){for(var n,s,o=this._textLines[t],a=this.getHeightOfLine(t)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(e){for(var t=0,i=0,r=0,n={},s=0;s0?(i=0,r++,t++):!this.splitByGrapheme&&this._reSpaceAndTab.test(e.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:t,offset:i},r+=e.graphemeLines[s].length,i+=e.graphemeLines[s].length;return n},styleHas:function(e,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return t.Text.prototype.styleHas.call(this,e,i)},isEmptyStyles:function(e){if(!this.styles)return!0;var t,i,r=0,n=!1,s=this._styleMap[e],o=this._styleMap[e+1];for(var a in s&&(e=s.line,r=s.offset),o&&(n=o.line===e,t=o.offset),i=void 0===e?this.styles:{line:this.styles[e]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=m,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(h),_+n>this.dynamicMinWidth&&(this.dynamicMinWidth=_-m+n),a},isEndOfWrapping:function(e){return!this._styleMap[e+1]||this._styleMap[e+1].line!==this._styleMap[e].line},missingNewlineOffset:function(e){return this.splitByGrapheme?this.isEndOfWrapping(e)?1:0:1},_splitTextIntoLines:function(e){for(var i=t.Text.prototype._splitTextIntoLines.call(this,e),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},P={};function k(e){var t=P[e];if(void 0!==t)return t.exports;var i=P[e]={exports:{}};return F[e](i,i.exports,k),i.exports}k.d=(e,t)=>{for(var i in t)k.o(t,i)&&!k.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},k.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var B={};(()=>{let e;k.d(B,{R:()=>e}),e="undefined"!=typeof document&&"undefined"!=typeof window?k(653).fabric:{version:"5.2.1"}})();var N=B.R; +const e="undefined"==typeof self;let t,i,r,n,s;if("undefined"!=typeof navigator&&(t=navigator,i=t.userAgent,r=t.platform,n=t.mediaDevices),!e){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:t.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},n={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:r,search:"Win"},Mac:{str:r},Linux:{str:r}};let o="unknownBrowser",a=0,h="unknownOS";for(let t in e){const r=e[t]||{};let n=r.str||i,s=r.search||t,h=r.verStr||i,l=r.verSearch||t;if(l instanceof Array||(l=[l]),-1!=n.indexOf(s)){o=t;for(let e of l){let t=h.indexOf(e);if(-1!=t){a=parseFloat(h.substring(t+e.length+1));break}}break}}for(let e in n){const t=n[e]||{};let r=t.str||i,s=t.search||e;if(-1!=r.indexOf(s)){h=e;break}}"Linux"==h&&-1!=i.indexOf("Windows NT")&&(h="HarmonyOS"),s={browser:o,version:a,OS:h}}e&&(s={browser:"ssr",version:0,OS:"ssr"});const o="undefined"!=typeof WebAssembly&&i&&!(/Safari/.test(i)&&!/Chrome/.test(i)&&/\(.+\s11_2_([2-6]).*\)/.test(i)),a=!("undefined"==typeof Worker),h=!(!n||!n.getUserMedia),l=async()=>{let e=!1;if(h)try{(await n.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===s.browser&&s.version>66||"Safari"===s.browser&&s.version>13||"OPR"===s.browser&&s.version>43||"Edge"===s.browser&&s.version;const c=(()=>{if(!e&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),u=" is not allowed to change after `createInstance` or `loadWasm` is called.",d=!e&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",f=!e&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",g=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let i=0;ie&&"object"==typeof e&&"function"==typeof e.then;class w extends Promise{constructor(e){let t,i;super(((e,r)=>{t=e,i=r})),this._s="pending",this.resolve=e=>{this.isPending&&(S(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",i(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,S(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const i=await t;e===this._task&&this.resolve(i)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}var b=function(){this.init()};b.prototype={init:function(){var e=this||C;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||C;if(e=parseFloat(e),t.ctx||R(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,C.ctx.currentTime);for(var i=0;i=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,R()),e},codecs:function(e){return(this||C)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||C;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||C,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var i=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",n=r.match(/OPR\/([0-6].)/g),s=n&&parseInt(n[0].split("/")[1],10)<33,o=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),a=r.match(/Version\/(.*?) /),h=o&&a&&parseInt(a[1],10)<15;return e._codecs={mp3:!(s||!i&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!i,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(h||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(h||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||C;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(i){for(;e._html5AudioPool.length0?o._seek:i._sprite[e][0]/1e3),l=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-h),c=1e3*l/Math.abs(o._rate),u=i._sprite[e][0]/1e3,d=(i._sprite[e][0]+i._sprite[e][1])/1e3;o._sprite=e,o._ended=!1;var f=function(){o._paused=!1,o._seek=h,o._start=u,o._stop=d,o._loop=!(!o._loop&&!i._sprite[e][2])};if(!(h>=d)){var g=o._node;if(i._webAudio){var _=function(){i._playLock=!1,f(),i._refreshBuffer(o);var e=o._muted||i._muted?0:o._volume;g.gain.setValueAtTime(e,C.ctx.currentTime),o._playStart=C.ctx.currentTime,void 0===g.bufferSource.start?o._loop?g.bufferSource.noteGrainOn(0,h,86400):g.bufferSource.noteGrainOn(0,h,l):o._loop?g.bufferSource.start(0,h,86400):g.bufferSource.start(0,h,l),c!==1/0&&(i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c)),t||setTimeout((function(){i._emit("play",o._id),i._loadQueue()}),0)};"running"===C.state&&"interrupted"!==C.ctx.state?_():(i._playLock=!0,i.once("resume",_),i._clearTimer(o._id))}else{var p=function(){g.currentTime=h,g.muted=o._muted||i._muted||C._muted||g.muted,g.volume=o._volume*C.volume(),g.playbackRate=o._rate;try{var r=g.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(i._playLock=!0,f(),r.then((function(){i._playLock=!1,g._unlocked=!0,t?i._loadQueue():i._emit("play",o._id)})).catch((function(){i._playLock=!1,i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),o._ended=!0,o._paused=!0}))):t||(i._playLock=!1,f(),i._emit("play",o._id)),g.playbackRate=o._rate,g.paused)return void i._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||o._loop?i._endTimers[o._id]=setTimeout(i._ended.bind(i,o),c):(i._endTimers[o._id]=function(){i._ended(o),g.removeEventListener("ended",i._endTimers[o._id],!1)},g.addEventListener("ended",i._endTimers[o._id],!1))}catch(e){i._emit("playerror",o._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===g.src&&(g.src=i._src,g.load());var m=window&&window.ejecta||!g.readyState&&C._navigator.isCocoonJS;if(g.readyState>=3||m)p();else{i._playLock=!0,i._state="loading";var v=function(){i._state="loaded",p(),g.removeEventListener(C._canPlayEvent,v,!1)};g.addEventListener(C._canPlayEvent,v,!1),i._clearTimer(o._id)}}return o._id}i._ended(o)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),r=0;r=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(i=t?r._soundById(t):r._sounds[0])?i._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,n)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var a=0;a0?r/l:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=h*n,a=Math.round(100*a)/100,a=h<0?Math.max(i,a):Math.min(i,a),o._webAudio?e._volume=a:o.volume(a,e._id,!0),s&&(o._volume=a),(it&&a>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,o.volume(i,e._id),o._emit("fade",e._id))}),c)},_stopFade:function(e){var t=this,i=t._soundById(e);return i&&i._interval&&(t._webAudio&&i._node.gain.cancelScheduledValues(C.ctx.currentTime),clearInterval(i._interval),i._interval=null,t.volume(i._fadeTo,e),i._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,i,r=this,n=arguments;if(0===n.length)return r._loop;if(1===n.length){if("boolean"!=typeof n[0])return!!(i=r._soundById(parseInt(n[0],10)))&&i._loop;e=n[0],r._loop=e}else 2===n.length&&(e=n[0],t=parseInt(n[1],10));for(var s=r._getSoundIds(t),o=0;o=0?t=parseInt(n[0],10):e=parseFloat(n[0])}else 2===n.length&&(e=parseFloat(n[0]),t=parseInt(n[1],10));if("number"!=typeof e)return(i=r._soundById(t))?i._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,n)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var a=0;a=0?t=parseInt(r[0],10):i._sounds.length&&(t=i._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==i._state||i._playLock))return i._queue.push({event:"seek",action:function(){i.seek.apply(i,r)}}),i;var o=i._soundById(t);if(o){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var a=i.playing(t)?C.ctx.currentTime-o._playStart:0,h=o._rateSeek?o._rateSeek-o._seek:0;return o._seek+(h+a*Math.abs(o._rate))}return o._node.currentTime}var l=i.playing(t);l&&i.pause(t,!0),o._seek=e,o._ended=!1,i._clearTimer(t),i._webAudio||!o._node||isNaN(o._node.duration)||(o._node.currentTime=e);var c=function(){l&&i.play(t,!0),i._emit("seek",t)};if(l&&!i._webAudio){var u=function(){i._playLock?setTimeout(u,0):c()};setTimeout(u,0)}else c()}return i},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var r=0;r=0&&C._howls.splice(r,1);var n=!0;for(i=0;i=0){n=!1;break}return I&&n&&delete I[e._src],C.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,r){var n=this["_on"+e];return"function"==typeof t&&n.push(r?{id:i,fn:t,once:r}:{id:i,fn:t}),this},off:function(e,t,i){var r=this,n=r["_on"+e],s=0;if("number"==typeof t&&(i=t,t=null),t||i)for(s=0;s=0;s--)n[s].id&&n[s].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(r,n[s].fn),0),n[s].once&&r.off(e,n[s].fn,n[s].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var t=this,i=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(i<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i=0;if(!e.bufferSource)return this;if(C._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=C._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(C._navigator&&C._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var T=function(e){this._parent=e,this.init()};T.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++C._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=C._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===C.ctx.createGain?C.ctx.createGainNode():C.ctx.createGain(),e._node.gain.setValueAtTime(i,C.ctx.currentTime),e._node.paused=!0,e._node.connect(C.masterGain)):C.noAudio||(e._node=C._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(C._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*C.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++C._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(C._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var I={},A=function(e){var t=e._src;if(I[t])return e._duration=I[t].duration,void D(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(I[t._src]=e,D(t,e)):i()};"undefined"!=typeof Promise&&1===C.ctx.decodeAudioData.length?C.ctx.decodeAudioData(e).then(r).catch(i):C.ctx.decodeAudioData(e,r,i)},D=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},R=function(){if(C.usingWebAudio){try{"undefined"!=typeof AudioContext?C.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?C.ctx=new webkitAudioContext:C.usingWebAudio=!1}catch(e){C.usingWebAudio=!1}C.ctx||(C.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(C._navigator&&C._navigator.platform),t=C._navigator&&C._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var r=/safari/.test(C._navigator&&C._navigator.userAgent.toLowerCase());C._navigator&&!r&&(C.usingWebAudio=!1)}C.usingWebAudio&&(C.masterGain=void 0===C.ctx.createGain?C.ctx.createGainNode():C.ctx.createGain(),C.masterGain.gain.setValueAtTime(C._muted?0:C._volume,C.ctx.currentTime),C.masterGain.connect(C.ctx.destination)),C._setup()}};!function(e,t,i,r){var n;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},e.prototype.pos=function(e,i,r){var n=this;return n.ctx&&n.ctx.listener?(i="number"!=typeof i?n._pos[1]:i,r="number"!=typeof r?n._pos[2]:r,"number"!=typeof e?n._pos:(n._pos=[e,i,r],void 0!==n.ctx.listener.positionX?(n.ctx.listener.positionX.setTargetAtTime(n._pos[0],t.ctx.currentTime,.1),n.ctx.listener.positionY.setTargetAtTime(n._pos[1],t.ctx.currentTime,.1),n.ctx.listener.positionZ.setTargetAtTime(n._pos[2],t.ctx.currentTime,.1)):n.ctx.listener.setPosition(n._pos[0],n._pos[1],n._pos[2]),n)):n},e.prototype.orientation=function(e,i,r,n,s,o){var a=this;if(!a.ctx||!a.ctx.listener)return a;var h=a._orientation;return i="number"!=typeof i?h[1]:i,r="number"!=typeof r?h[2]:r,n="number"!=typeof n?h[3]:n,s="number"!=typeof s?h[4]:s,o="number"!=typeof o?h[5]:o,"number"!=typeof e?h:(a._orientation=[e,i,r,n,s,o],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(i,t.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(n,t.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(s,t.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(o,t.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,i,r,n,s,o),a)},i.prototype.init=(n=i.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],n.call(this,e)}),i.prototype.stereo=function(e,i){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,i)}}),r;var n=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var o=r._getSoundIds(i),a=0;a{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=M,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+u);i._license=t})(L,e)}static get productKeys(){return this._license}static set productKeys(e){L.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){L.license=e}static get organizationID(){return this._license}static set organizationID(e){L.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+u);i._sessionPassword=t})(L,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:o,worker:a,getUserMedia:h,camera:await l(),browser:s.browser,version:s.version,OS:s.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(t){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");L._engineResourcePath=(t=>{if(null==t&&(t="./"),!e){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+u);i._licenseServer=g(t)})(L,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+u);i._deviceFriendlyName=t||""})(L,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");L.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&(("colorMode"in e||"pixelFormat"in e)&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=L._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",L.engineResourcePath)}static set defaultUIElementURL(e){L._defaultUIElementURL=e}static _fireHTTPSWarnning(){L.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{L.onWarning&&L.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new x({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;L._onLog&&L._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const i=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else i||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let t=await this._decode_DCEFrame(e,{bCopyData:!1}),i=null;if(t&&t.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:h}=e;i=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(i,r,n,a,h,s,o)}if(this._drawResults(i,t),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(L._onLog&&L._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!L.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:i,sp:r,rmk:n}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,i,r=t._license||"",n=JSON.parse(JSON.stringify(t._licenseServer)),s=t._sessionPassword,o=0;if(r.startsWith("t")||r.startsWith("f"))o=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))o=1;else{o=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t;try{let e=r.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===n.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),n=g(e)}!s&&t.sessionPassword&&(s=t.sessionPassword),e=t.remark}("200001"===r||r.startsWith("200001-"))&&(n&&n.length||(r="")),r||(o=1)}if(o&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==o)throw new Error(i);o=0,console.warn(i),t._lastErrorCode=-1,t._lastErrorString=i}return 1===o&&(r="",console.warn("Applying for a public trial license ...")),{lt:o,l:r,ls:n,sp:s,rmk:e}}throw new Error("Can't preprocess license again"+u)})(L);this._pLoad.task=async(o,a)=>{let h=L.engineResourcePath+L._workerName;L.engineResourcePath.startsWith(location.origin)||(h=await fetch(h).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),L._dbrWorker=new Worker(h),L._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},L._dbrWorker.onmessage=async t=>{let i=t.data?t.data:t;switch(i.type){case"log":L._onLog&&L._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0,i.message||(i.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),i.success?(L._dbrWorker.onerror=null,L._version=i.version+"(JS "+L._jsVersion+"."+L._jsEditVersion+")",L._onLog&&L._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(t=new Error(i.message),t.stack=i.stack+"\n"+t.stack,t.ltsErrorCode=i.ltsErrorCode,r||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&L.showDialog(i.success?"warn":"error",i.message),i.success?o():a(t);break}case"task":{let e=i.id,t=i.body;try{L._taskCallbackMap.get(e)(t),L._taskCallbackMap.delete(e)}catch(t){throw L._taskCallbackMap.delete(e),t}break}default:L._onLog&&L._onLog(t)}},L._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:L.engineResourcePath,bUseFullFeature:L._bUseFullFeature,bd:L._bWasmDebug,v:L._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:s,cv:L.authCacheVersion,fn:L.deviceFriendlyName,ls:i,sp:r,rmk:n})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,i)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let n=await r.text();if(!n.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=n;let o=[];for(let e=0;e{if(e==t.target){a.remove();for(let e of o)e.remove()}}));else if(!l&&e.classList.contains("dls-license-icon-close"))l=e,e.addEventListener("click",(()=>{a.remove();for(let e of o)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!d&&e.classList.contains("dls-license-msg-content")){d=e;let t=i;for(;t;){let i=t.indexOf("["),r=t.indexOf("]",i),n=t.indexOf("(",r),s=t.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){e.appendChild(new Text(t));break}i>0&&e.appendChild(new Text(t.substring(0,i)));let o=document.createElement("a"),a=t.substring(i+1,r);o.innerText=a;let h=t.substring(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),e.appendChild(o),t=t.substring(s+1)}}document.body.appendChild(a)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await L.loadWasm(),await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new L;return e._instanceID=await L.createInstanceInWorker(),L._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){L._onLog&&L._onLog("decode(source: any)"),L._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):L.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):L.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,i,r,n,s,o){return await new Promise(((a,h)=>{let l=L._nextTaskID++;L._taskCallbackMap.set(l,(e=>{if(e.success){let t,i=L._onLog?Date.now():0;L._onLog&&L._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return h(e)}if(L._onLog){let e=Date.now();L._onLog("DBR getting message from worker timestamp: "+i),L._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),L._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),L._onLog("Handling results from DBR worker costs: "+(e-i)),L._onLog("Total decoding image costs: "+(e-this._timeStartDecode))}return a(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,h(t)}})),this._timeEnterInnerDBR=Date.now(),L._onLog&&L._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),L._dbrWorker.postMessage({type:"decodeBuffer",id:l,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,orientation:s,config:o}},[e.buffer]),L._onLog&&o&&o.timeStamp&&L._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s,o){L._onLog&&L._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),t,i,r,n,s,o)}async decodeBuffer(e,t,i,r,n,s,o){let a;return L._onLog&&L._onLog("decodeBuffer(buffer,width,height,stride,format)"),L._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(e,t,i,r,n,s,o):e instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,r,n,s,o):e instanceof Blob&&(a=await this._decodeBuffer_Blob(e,t,i,r,n,s,o)),a}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success){let t=JSON.parse(i.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=5,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region}else if("dense"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=9,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!L._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(v.BF_ONED|v.BF_QR_CODE|v.BF_PDF417|v.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=t.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,t.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(t.intermediateResultTypes|=y.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){i(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),L._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=M,await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=M,await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!L._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!L._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){i(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){L._onLog&&L._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(r=await function(e){return new Promise(((t,i)=>{let r=URL.createObjectURL(e),n=new Image;n.dbrObjUrl=r,n.src=r,n.onload=()=>{t(n)},n.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let n=await this._decode_Image(i||r,t);return i&&i.close(),n}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){L._onLog&&L._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let i,r,n=e instanceof HTMLImageElement?e.naturalWidth:e.width,s=e instanceof HTMLImageElement?e.naturalHeight:e.height,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(a,t)}async _decode_Canvas(e,t){if(L._onLog&&L._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if(0===e.width||0===e.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=e,this.oriCanvasData=null);let i=(e.ctx2d||e.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,e.width,e.height).data;return await this._decodeBuffer_Uint8Array(i,e.width,e.height,4*e.width,_.IPF_ABGR_8888,0,t)}async _decode_Video(e,t){if(L._onLog&&L._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let i,r,n=e.videoWidth,s=e.videoHeight,o=Math.max(n,s);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(n*e),r=Math.round(s*e)}else i=n,r=s;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),await this._decode_Canvas(a,t)}async _decode_DCEFrame(e,t){if(L._onLog&&L._onLog("_decode_DCEFrame(dceFrame)"),!L.isDCEFrame(e))return[];let i=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,pixelFormat:e.pixelFormat,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{width:r,height:n,colorMode:s,pixelFormat:o,stride:a,timeStamp:h}=e;let l;l=t&&t.bCopyData?new Uint8Array(e.data):e.data;let c=null;if(t?(c=JSON.parse(JSON.stringify(t)),c.timeStamp=h):c={timeStamp:h},o&&a)if("grey"===o)i=await this._decodeBuffer_Uint8Array(l,r,n,a,_.IPF_GrayScaled,0,c);else if("rgba"===o)i=await this._decodeBuffer_Uint8Array(l,r,n,a,_.IPF_ABGR_8888,0,c);else{if("bgra"!==o)throw new Error(`Pixel format '${o}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(l,r,n,a,_.IPF_ARGB_8888,0,c)}else if("grey"===s)i=await this._decodeBuffer_Uint8Array(l,r,n,r,_.IPF_GrayScaled,0,c);else if("rgba"===s)i=await this._decodeBuffer_Uint8Array(l,r,n,4*r,_.IPF_ABGR_8888,0,c);else{if("bgra"!==s)throw new Error(`Color mode '${s}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(l,r,n,4*r,_.IPF_ARGB_8888,0,c)}return i}async _decode_DSImage(e,t){if(L._onLog&&L._onLog("_decode_DSImage(dsImage)"),!L.isDSImage(e))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat.toLowerCase(),data:new Uint8Array(e.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,t)}}async _decode_FilePath(e,t){throw L._onLog&&L._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,i,r,n,s,o){if(e.length>0)for(let a of e){let e=a.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*s,e.x2*=.01*s,e.x3*=.01*s,e.x4*=.01*s,e.y1*=.01*o,e.y2*=.01*o,e.y3*=.01*o,e.y4*=.01*o);let h=s/r,l=o/n;e.x1=e.x1/h+t,e.x2=e.x2/h+t,e.x3=e.x3/h+t,e.x4=e.x4/h+t,e.y1=e.y1/l+i,e.y2=e.y2/l+i,e.y3=e.y3/l+i,e.y4=e.y4/l+i,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/n,e.y2*=100/n,e.y3*=100/n,e.y4*=100/n)}}static BarcodeReaderException(e,t){let i,r=p.DBR_UNKNOWN;return"number"==typeof e?(r=e,i=new Error(t)):i=new Error(e),i.code=r,i}_handleRetJsonString(e){let t=p;if(e.textResults){for(let t=0;t{let i=t.indexOf(":");e[t.substring(0,i)]=t.substring(i+1)})),i.exception=e}}return e.decodeRecords?this.decodeRecords=e.decodeRecords:this.decodeRecords={},this._lastErrorCode=e.exception,this._lastErrorString=e.description,e.exception&&!L._setWarnnedEx.has(e.description)&&(L._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw L.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=L._nextTaskID++;L._taskCallbackMap.set(o,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return s(e)}return n()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,s(t)}})),L._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:r}})}))}async getModeArgument(e,t,i){return await new Promise(((r,n)=>{let s=L._nextTaskID++;L._taskCallbackMap.set(s,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return n(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),L._dbrWorker.postMessage({type:"getModeArgument",id:s,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success)return e(i.results);{let e=new Error(i.message);return e.stack=i.stack+"\n"+e.stack,t(e)}})),L._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let i of e)if(i.dataType==m.IMRDT_IMAGE)for(let e of i.results){const i=e.bytes;let r;switch(L._onLog&&L._onLog(" "+i.length+" "+i.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case _.IPF_ABGR_8888:r=new Uint8ClampedArray(i);break;case _.IPF_RGB_888:{const e=i.length/3;r=new Uint8ClampedArray(4*e);for(let t=0;t=n)break;r[o]=r[o+1]=r[o+2]=(128&t)/128*255,r[o+3]=255,t<<=1}}break}default:console.warn("unknow intermediate image",e)}if(!r)continue;let n=new ImageData(r,e.width,e.height),s=document.createElement("canvas");s.width=e.width,s.height=e.height,s.getContext("2d").putImageData(n,0,0),t.push(s)}return t}async getScanSettings(){return await new Promise(((e,t)=>{let i=L._nextTaskID++;L._taskCallbackMap.set(i,(i=>{if(i.success){let t=i.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t.autoZoom=this.autoZoom,t.autoFocus=this.autoFocus,t.autoSuggestTip=this.autoSuggestTip,e(t)}{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),L._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));if(t.autoZoom||t.autoFocus||t.autoSuggestTip){if(!L._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const e=await this.getRuntimeSettings();e.intermediateResultTypes|=y.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(e)}return t.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(t.intervalTime,0),delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),t.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=t.captureAndDecodeInParallel,delete t.captureAndDecodeInParallel),t.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=t.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=t.autoZoom,delete t.autoZoom),t.hasOwnProperty("autoFocus")&&(this.autoFocus=t.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete t.autoFocus),t.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=t.autoSuggestTip,delete t.autoFocus),await new Promise(((e,i)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,i(e)}})),L._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let i of e)t.push(this._cloneDecodeResults(i));return t}{let t=e,i=JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return L._onLog&&L._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));L._onLog&&L._onLog("======= once read ======="),L._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!L.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return L._onLog&&L._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(e){i=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(i&&i.length){const{sx:r,sy:n,width:s,height:o,_sWidth:a,_sHeight:h}=e;t=i.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(t,r,n,a,h,s,o)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t,i),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else t&&(i=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return i})().then((e=>{if(L._onLog&&L._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const i=()=>{let i=0;if(t&&t.length){let r=Math.min(...e),n=Math.max(...t);r&&n&&(i=r-n)}else i=0;return i>0?i:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),L._onLog&&L._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(L._onLog&&L._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};t(e)}else L._onLog&&L._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e,t){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const i=this._dbrDrawingLayer;e||(e=[]);let r=this._arrPolygons;for(let n=0;n{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(t),t}stopScanning(e){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[e]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(e){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(L._onLog&&L._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let e=L._nextTaskID++;L._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),L._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}L._jsVersion="9.6.11",L._jsEditVersion="20230310",L._version=`loading...(JS ${L._jsVersion}.${L._jsEditVersion})`,L._license=d,L._sessionPassword=f,L.browserInfo=s,L._workerName=`dbr-${L._jsVersion}.browser.worker.js`,L._engineResourcePath=c,L._licenseServer=[],L._deviceFriendlyName="",L._isShowRelDecodeTimeInResults=!1,L._bWasmDebug=!1,L._bNeverShowDialog=!1,L.__bUseFullFeature=!0,L._nextTaskID=0,L._taskCallbackMap=new Map,L._pLoad=new w,L._lastErrorCode=0,L._lastErrorString="",L._setWarnnedEx=new Set,L._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var F={653:(e,t,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,_,p,m,v,y,S,w,b,C,x=x||{version:"5.2.1"};if(t.fabric=x,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?x.document=document:x.document=document.implementation.createHTMLDocument(""),x.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;x.document=T.document,x.jsdomImplForWrapper=i(898).implForWrapper,x.nodeCanvas=i(245).Canvas,x.window=T,DOMParser=x.window.DOMParser}function I(e,t){var i=e.canvas,r=t.targetCanvas,n=r.getContext("2d");n.translate(0,r.height),n.scale(1,-1);var s=i.height-r.height;n.drawImage(i,0,s,r.width,r.height,0,0,r.width,r.height)}function A(e,t){var i=t.targetCanvas.getContext("2d"),r=t.destinationWidth,n=t.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,o);var h=new ImageData(a,r,n);i.putImageData(h,0,0)}x.isTouchSupported="ontouchstart"in x.window||"ontouchstart"in x.document||x.window&&x.window.navigator&&x.window.navigator.maxTouchPoints>0,x.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,x.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],x.DPI=96,x.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",x.commaWsp="(?:\\s+,?\\s*|,\\s*)",x.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,x.reNonWord=/[ \n\.,;!\?\-]/,x.fontPaths={},x.iMatrix=[1,0,0,1,0,0],x.svgNS="http://www.w3.org/2000/svg",x.perfLimitSizeTotal=2097152,x.maxCacheSideLimit=4096,x.minCacheSideLimit=256,x.charWidthsCache={},x.textureSize=2048,x.disableStyleCopyPaste=!1,x.enableGLFiltering=!0,x.devicePixelRatio=x.window.devicePixelRatio||x.window.webkitDevicePixelRatio||x.window.mozDevicePixelRatio||1,x.browserShadowBlurConstant=1,x.arcToSegmentsCache={},x.boundsOfCurveCache={},x.cachesBoundsOfCurve=!0,x.forceGLPutImageData=!1,x.initFilterBackend=function(){return x.enableGLFiltering&&x.isWebglSupported&&x.isWebglSupported(x.textureSize)?(console.log("max texture size: "+x.maxTextureSize),new x.WebglFilterBackend({tileSize:x.textureSize})):x.Canvas2dFilterBackend?new x.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=x),function(){function e(e,t){if(this.__eventListeners[e]){var i=this.__eventListeners[e];t?i[i.indexOf(t)]=!1:x.util.array.fill(i,!1)}}function t(e,t){var i=function(){t.apply(this,arguments),this.off(e,i)}.bind(this);this.on(e,i)}x.Observable={fire:function(e,t){if(!this.__eventListeners)return this;var i=this.__eventListeners[e];if(!i)return this;for(var r=0,n=i.length;r-1||!!t&&this._objects.some((function(t){return"function"==typeof t.contains&&t.contains(e,!0)}))},complexity:function(){return this._objects.reduce((function(e,t){return e+(t.complexity?t.complexity():0)}),0)}},x.CommonMethods={_setOptions:function(e){for(var t in e)this.set(t,e[t])},_initGradient:function(e,t){!e||!e.colorStops||e instanceof x.Gradient||this.set(t,new x.Gradient(e))},_initPattern:function(e,t,i){!e||!e.source||e instanceof x.Pattern?i&&i():this.set(t,new x.Pattern(e,i))},_setObject:function(e){for(var t in e)this._set(t,e[t])},set:function(e,t){return"object"==typeof e?this._setObject(e):this._set(e,t),this},_set:function(e,t){this[e]=t},toggle:function(e){var t=this.get(e);return"boolean"==typeof t&&this.set(e,!t),this},get:function(e){return this[e]}},r=t,n=Math.sqrt,s=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,x.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},sin:function(e){if(0===e)return 0;var t=1;switch(e<0&&(t=-1),e/h){case 1:return t;case 2:return 0;case 3:return-t}return Math.sin(e)},removeFromArray:function(e,t){var i=e.indexOf(t);return-1!==i&&e.splice(i,1),e},getRandomInt:function(e,t){return Math.floor(Math.random()*(t-e+1))+e},degreesToRadians:function(e){return e*a},radiansToDegrees:function(e){return e/a},rotatePoint:function(e,t,i){var r=new x.Point(e.x-t.x,e.y-t.y),n=x.util.rotateVector(r,i);return new x.Point(n.x,n.y).addEquals(t)},rotateVector:function(e,t){var i=x.util.sin(t),r=x.util.cos(t);return{x:e.x*r-e.y*i,y:e.x*i+e.y*r}},createVector:function(e,t){return new x.Point(t.x-e.x,t.y-e.y)},calcAngleBetweenVectors:function(e,t){return Math.acos((e.x*t.x+e.y*t.y)/(Math.hypot(e.x,e.y)*Math.hypot(t.x,t.y)))},getHatVector:function(e){return new x.Point(e.x,e.y).multiply(1/Math.hypot(e.x,e.y))},getBisector:function(e,t,i){var r=x.util.createVector(e,t),n=x.util.createVector(e,i),s=x.util.calcAngleBetweenVectors(r,n),o=s*(0===x.util.calcAngleBetweenVectors(x.util.rotateVector(r,s),n)?1:-1)/2;return{vector:x.util.getHatVector(x.util.rotateVector(r,o)),angle:s}},projectStrokeOnPoints:function(e,t,i){var r=[],n=t.strokeWidth/2,s=t.strokeUniform?new x.Point(1/t.scaleX,1/t.scaleY):new x.Point(1,1),o=function(e){var t=n/Math.hypot(e.x,e.y);return new x.Point(e.x*t*s.x,e.y*t*s.y)};return e.length<=1||e.forEach((function(a,h){var l,c,u=new x.Point(a.x,a.y);0===h?(c=e[h+1],l=i?o(x.util.createVector(c,u)).addEquals(u):e[e.length-1]):h===e.length-1?(l=e[h-1],c=i?o(x.util.createVector(l,u)).addEquals(u):e[0]):(l=e[h-1],c=e[h+1]);var d,f,g=x.util.getBisector(u,l,c),_=g.vector,p=g.angle;if("miter"===t.strokeLineJoin&&(d=-n/Math.sin(p/2),f=new x.Point(_.x*d*s.x,_.y*d*s.y),Math.hypot(f.x,f.y)/n<=t.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-n*Math.SQRT2,f=new x.Point(_.x*d*s.x,_.y*d*s.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(e,t,i){return i?new x.Point(t[0]*e.x+t[2]*e.y,t[1]*e.x+t[3]*e.y):new x.Point(t[0]*e.x+t[2]*e.y+t[4],t[1]*e.x+t[3]*e.y+t[5])},makeBoundingBoxFromPoints:function(e,t){if(t)for(var i=0;i0&&(t>r?t-=r:t=0,i>r?i-=r:i=0);var n,s=!0,o=e.getImageData(t,i,2*r||1,2*r||1),a=o.data.length;for(n=3;n=n?s-n:2*Math.PI-(n-s)}function s(e,t,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(e,t,i,s,o,a,h){var l=Math.PI,c=h*l/180,u=x.util.sin(c),d=x.util.cos(c),f=0,g=0,_=-d*e*.5-u*t*.5,p=-d*t*.5+u*e*.5,m=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,S=_*_,w=m*v-m*y-v*S,b=0;if(w<0){var C=Math.sqrt(1-w/(m*v));i*=C,s*=C}else b=(o===a?-1:1)*Math.sqrt(w/(m*y+v*S));var T=b*i*p/s,I=-b*s*_/i,A=d*T-u*I+.5*e,E=u*T+d*I+.5*t,O=n(1,0,(_-T)/i,(p-I)/s),D=n((_-T)/i,(p-I)/s,(-_-T)/i,(-p-I)/s);0===a&&D>0?D-=2*l:1===a&&D<0&&(D+=2*l);for(var R=Math.ceil(Math.abs(D/l*2)),M=[],L=D/R,F=8/3*Math.sin(L/4)*Math.sin(L/4)/Math.sin(L/2),P=O+L,k=0;kb)for(var T=1,I=_.length;T2;for(t=t||0,l&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,h=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+h*t]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(t,i,r,n,s,o,a,h){var l;if(x.cachesBoundsOfCurve&&(l=e.call(arguments),x.boundsOfCurveCache[l]))return x.boundsOfCurveCache[l];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,w=Math.abs,b=[],C=[[],[]];u=6*t-12*r+6*s,c=-3*t+9*r-9*s+3*a,d=3*r-3*t;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*n+6*o,c=-3*i+9*n-9*o+3*h,d=3*n-3*i),w(c)<1e-12){if(w(u)<1e-12)continue;0<(f=-d/u)&&f<1&&b.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&b.push(g),0<(_=(-u-m)/(2*c))&&_<1&&b.push(_));for(var I,A,E,O=b.length,D=O;O--;)I=(E=1-(f=b[O]))*E*E*t+3*E*E*f*r+3*E*f*f*s+f*f*f*a,C[0][O]=I,A=E*E*E*i+3*E*E*f*n+3*E*f*f*o+f*f*f*h,C[1][O]=A;C[0][D]=t,C[1][D]=i,C[0][D+1]=a,C[1][D+1]=h;var R=[{x:y.apply(null,C[0]),y:y.apply(null,C[1])},{x:S.apply(null,C[0]),y:S.apply(null,C[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=R),R},x.util.getPointOnPath=function(e,t,i){i||(i=d(e));for(var r=0;t-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>t?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,t)}},x.util.transformPath=function(e,t,i){return i&&(t=x.util.multiplyTransformMatrices(t,[1,0,0,1,-i.x,-i.y])),e.map((function(e){for(var i=e.slice(0),r={},n=1;n=t}))}}}(),function(){function e(t,i,r){if(r)if(!x.isLikelyNode&&i instanceof Element)t=i;else if(i instanceof Array){t=[];for(var n=0,s=i.length;n57343)return e.charAt(t);if(55296<=i&&i<=56319){if(e.length<=t+1)throw"High surrogate without following low surrogate";var r=e.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return e.charAt(t)+e.charAt(t+1)}if(0===t)throw"Low surrogate without preceding high surrogate";var n=e.charCodeAt(t-1);if(55296>n||n>56319)throw"Low surrogate without preceding high surrogate";return!1}x.util.string={camelize:function(e){return e.replace(/-+(.)?/g,(function(e,t){return t?t.toUpperCase():""}))},capitalize:function(e,t){return e.charAt(0).toUpperCase()+(t?e.slice(1):e.slice(1).toLowerCase())},escapeXml:function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(t){var i,r=0,n=[];for(r=0;r-1?e.prototype[n]=function(e){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=t[e].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==e)return n}}(n):e.prototype[n]=t[n],i&&(t.toString!==Object.prototype.toString&&(e.prototype.toString=t.toString),t.valueOf!==Object.prototype.valueOf&&(e.prototype.valueOf=t.valueOf))};function n(){}function s(t){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[t];if(r[t]!==n){i=n;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,e.call(arguments,1)):i.call(this):console.log("tried to callSuper "+t+", method not found in prototype chain",this)}x.util.createClass=function(){var i=null,o=e.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(n.prototype=i.prototype,a.prototype=new n,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===e.pointerType},d="string"==typeof(u=x.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(e){return e},d?_=function(e,t){return e.style.opacity=t,e}:f&&(_=function(e,t){var i=e.style;return e.currentStyle&&!e.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(t=t>=.9999?"":"alpha(opacity="+100*t+")",i.filter=i.filter.replace(g,t)):i.filter+=" alpha(opacity="+100*t+")",e}),x.util.setStyle=function(e,t){var i=e.style;if(!i)return e;if("string"==typeof t)return e.style.cssText+=";"+t,t.indexOf("opacity")>-1?_(e,t.match(/opacity:\s*(\d?\.?\d*)/)[1]):e;for(var r in t)"opacity"===r?_(e,t[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=t[r];return e},function(){var e,t,i,r,n=Array.prototype.slice,s=function(e){return n.call(e,0)};try{e=s(x.document.childNodes)instanceof Array}catch(e){}function o(e,t){var i=x.document.createElement(e);for(var r in t)"class"===r?i.className=t[r]:"for"===r?i.htmlFor=t[r]:i.setAttribute(r,t[r]);return i}function a(e){for(var t=0,i=0,r=x.document.documentElement,n=x.document.body||{scrollLeft:0,scrollTop:0};e&&(e.parentNode||e.host)&&((e=e.parentNode||e.host)===x.document?(t=n.scrollLeft||r.scrollLeft||0,i=n.scrollTop||r.scrollTop||0):(t+=e.scrollLeft||0,i+=e.scrollTop||0),1!==e.nodeType||"fixed"!==e.style.position););return{left:t,top:i}}e||(s=function(e){for(var t=new Array(e.length),i=e.length;i--;)t[i]=e[i];return t}),t=x.document.defaultView&&x.document.defaultView.getComputedStyle?function(e,t){var i=x.document.defaultView.getComputedStyle(e,null);return i?i[t]:void 0}:function(e,t){var i=e.style[t];return!i&&e.currentStyle&&(i=e.currentStyle[t]),i},i=x.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",x.util.makeElementUnselectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=x.util.falseFunction),r?e.style[r]="none":"string"==typeof e.unselectable&&(e.unselectable="on"),e},x.util.makeElementSelectable=function(e){return void 0!==e.onselectstart&&(e.onselectstart=null),r?e.style[r]="":"string"==typeof e.unselectable&&(e.unselectable=""),e},x.util.setImageSmoothing=function(e,t){e.imageSmoothingEnabled=e.imageSmoothingEnabled||e.webkitImageSmoothingEnabled||e.mozImageSmoothingEnabled||e.msImageSmoothingEnabled||e.oImageSmoothingEnabled,e.imageSmoothingEnabled=t},x.util.getById=function(e){return"string"==typeof e?x.document.getElementById(e):e},x.util.toArray=s,x.util.addClass=function(e,t){e&&-1===(" "+e.className+" ").indexOf(" "+t+" ")&&(e.className+=(e.className?" ":"")+t)},x.util.makeElement=o,x.util.wrapElement=function(e,t,i){return"string"==typeof t&&(t=o(t,i)),e.parentNode&&e.parentNode.replaceChild(t,e),t.appendChild(e),t},x.util.getScrollLeftTop=a,x.util.getElementOffset=function(e){var i,r,n=e&&e.ownerDocument,s={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var l in h)o[h[l]]+=parseInt(t(e,l),10)||0;return i=n.documentElement,void 0!==e.getBoundingClientRect&&(s=e.getBoundingClientRect()),r=a(e),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.top+r.top-(i.clientTop||0)+o.top}},x.util.getNodeCanvas=function(e){var t=x.jsdomImplForWrapper(e);return t._canvas||t._image},x.util.cleanUpJsdomNode=function(e){if(x.isLikelyNode){var t=x.jsdomImplForWrapper(e);t&&(t._image=null,t._canvas=null,t._currentSrc=null,t._attributes=null,t._classList=null)}}}(),function(){function e(){}x.util.request=function(t,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",n=i.onComplete||function(){},s=new x.window.XMLHttpRequest,o=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(n(s),s.onreadystatechange=e)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(t=function(e,t){return e+(/\?/.test(e)?"&":"?")+t}(t,i.parameters))),s.open(r,t,!0),"POST"!==r&&"PUT"!==r||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(o),s}}(),x.log=console.log,x.warn=console.warn,function(){var e=x.util.object.extend,t=x.util.object.clone,i=[];function r(){return!1}function n(e,t,i,r){return-i*Math.cos(e/r*(Math.PI/2))+i+t}x.util.object.extend(i,{cancelAll:function(){var e=this.splice(0);return e.forEach((function(e){e.cancel()})),e},cancelByCanvas:function(e){if(!e)return[];var t=this.filter((function(t){return"object"==typeof t.target&&t.target.canvas===e}));return t.forEach((function(e){e.cancel()})),t},cancelByTarget:function(e){var t=this.findAnimationsByTarget(e);return t.forEach((function(e){e.cancel()})),t},findAnimationIndex:function(e){return this.indexOf(this.findAnimation(e))},findAnimation:function(e){return this.find((function(t){return t.cancel===e}))},findAnimationsByTarget:function(e){return e?this.filter((function(t){return t.target===e})):[]}});var s=x.window.requestAnimationFrame||x.window.webkitRequestAnimationFrame||x.window.mozRequestAnimationFrame||x.window.oRequestAnimationFrame||x.window.msRequestAnimationFrame||function(e){return x.window.setTimeout(e,1e3/60)},o=x.window.cancelAnimationFrame||x.window.clearTimeout;function a(){return s.apply(x.window,arguments)}x.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var e=x.runningAnimations.indexOf(s);return e>-1&&x.runningAnimations.splice(e,1)[0]};return s=e(t(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(s),a((function(e){var t,l=e||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||n,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(e,t){return v[t]-m[t]})):v-m);i.onStart&&i.onStart(),function e(i){var r=(t=i||+new Date)>u?c:t-l,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),w=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=w,s.durationRate=n,!o){if(!f(S,w,n))return t>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(S,w,n),void a(e));h()}}(l)})),s.cancel},x.util.requestAnimFrame=a,x.util.cancelAnimFrame=function(){return o.apply(x.window,arguments)},x.runningAnimations=i}(),function(){function e(e,t,i){var r="rgba("+parseInt(e[0]+i*(t[0]-e[0]),10)+","+parseInt(e[1]+i*(t[1]-e[1]),10)+","+parseInt(e[2]+i*(t[2]-e[2]),10);return(r+=","+(e&&t?parseFloat(e[3]+i*(t[3]-e[3])):1))+")"}x.util.animateColor=function(t,i,r,n){var s=new x.Color(t).getSource(),o=new x.Color(i).getSource(),a=n.onComplete,h=n.onChange;return n=n||{},x.util.animate(x.util.object.extend(n,{duration:r||500,startValue:s,endValue:o,byValue:o,easing:function(t,i,r,s){return e(i,r,n.colorEasing?n.colorEasing(t,s):1-Math.cos(t/s*(Math.PI/2)))},onComplete:function(t,i,r){if(a)return a(e(o,o,0),i,r)},onChange:function(t,i,r){if(h){if(Array.isArray(t))return h(e(t,t,0),i,r);h(t,i,r)}}}))}}(),function(){function e(e,t,i,r){return e-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===e||"xlink:href"===e||"font"===e)return i;if("imageSmoothing"===e)return"optimizeQuality"===i;a=h?i.map(s):s(i,n)}}else i="";return!h&&isNaN(a)?i:a}function f(e){return new RegExp("^("+e.join("|")+")\\b","i")}function g(e,t){var i,r,n,s,o=[];for(n=0,s=t.length;n1;)h.shift(),l=t.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*,?\\s*("+t.reNum+"+)\\s*$");function y(e){if(!t.svgViewBoxElementsRegEx.test(e.nodeName))return{};var i,r,n,o,a,h,l=e.getAttribute("viewBox"),c=1,u=1,d=e.getAttribute("width"),f=e.getAttribute("height"),g=e.getAttribute("x")||0,_=e.getAttribute("y")||0,p=e.getAttribute("preserveAspectRatio")||"",m=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,w={},b="",C=0,x=0;if(w.width=0,w.height=0,w.toBeParsed=S,m&&(g||_)&&e.parentNode&&"#document"!==e.parentNode.nodeName&&(b=" translate("+s(g)+" "+s(_)+") ",a=(e.getAttribute("transform")||"")+b,e.setAttribute("transform",a),e.removeAttribute("x"),e.removeAttribute("y")),S)return w;if(m)return w.width=s(d),w.height=s(f),w;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),w.minX=i,w.minY=r,w.viewBoxWidth=n,w.viewBoxHeight=o,y?(w.width=n,w.height=o):(w.width=s(d),w.height=s(f),c=w.width/n,u=w.height/o),"none"!==(p=t.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),C=w.width-n*c,x=w.height-o*c,"Mid"===p.alignX&&(C/=2),"Mid"===p.alignY&&(x/=2),"Min"===p.alignX&&(C=0),"Min"===p.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return w;if((g||_)&&"#document"!==e.parentNode.nodeName&&(b=" translate("+s(g)+" "+s(_)+") "),a=b+" matrix("+c+" 0 0 "+u+" "+(i*c+C)+" "+(r*u+x)+") ","svg"===e.nodeName){for(h=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)h.appendChild(e.firstChild);e.appendChild(h)}else(h=e).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),w}function S(e,t){var i="xlink:href",r=m(e,t.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(e,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(e){r&&!t.hasAttribute(e)&&r.hasAttribute(e)&&t.setAttribute(e,r.getAttribute(e))})),!t.children.length)for(var n=r.cloneNode(!0);n.firstChild;)t.appendChild(n.firstChild);t.removeAttribute(i)}t.parseSVGDocument=function(e,i,n,s){if(e){!function(e){for(var i=g(e,["use","svg:use"]),r=0;i.length&&re.x&&this.y>e.y},gte:function(e){return this.x>=e.x&&this.y>=e.y},lerp:function(e,t){return void 0===t&&(t=.5),t=Math.max(Math.min(1,t),0),new i(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)},distanceFrom:function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},midPointFrom:function(e){return this.lerp(e)},min:function(e){return new i(Math.min(this.x,e.x),Math.min(this.y,e.y))},max:function(e){return new i(Math.max(this.x,e.x),Math.max(this.y,e.y))},toString:function(){return this.x+","+this.y},setXY:function(e,t){return this.x=e,this.y=t,this},setX:function(e){return this.x=e,this},setY:function(e){return this.y=e,this},setFromPoint:function(e){return this.x=e.x,this.y=e.y,this},swap:function(e){var t=this.x,i=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=i},clone:function(){return new i(this.x,this.y)}})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){this.status=e,this.points=[]}t.Intersection?t.warn("fabric.Intersection is already defined"):(t.Intersection=i,t.Intersection.prototype={constructor:i,appendPoint:function(e){return this.points.push(e),this},appendPoints:function(e){return this.points=this.points.concat(e),this}},t.Intersection.intersectLineLine=function(e,r,n,s){var o,a=(s.x-n.x)*(e.y-n.y)-(s.y-n.y)*(e.x-n.x),h=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),l=(s.y-n.y)*(r.x-e.x)-(s.x-n.x)*(r.y-e.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new t.Point(e.x+c*(r.x-e.x),e.y+c*(r.y-e.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},t.Intersection.intersectLinePolygon=function(e,t,r){var n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},t.Intersection.intersectPolygonPolygon=function(e,t){var r,n=new i,s=e.length;for(r=0;r0&&(n.status="Intersection"),n},t.Intersection.intersectPolygonRectangle=function(e,r,n){var s=r.min(n),o=r.max(n),a=new t.Point(o.x,s.y),h=new t.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,e),c=i.intersectLinePolygon(a,o,e),u=i.intersectLinePolygon(o,h,e),d=i.intersectLinePolygon(h,s,e),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(t),function(e){var t=e.fabric||(e.fabric={});function i(e){e?this._tryParsingColor(e):this.setSource([0,0,0,1])}function r(e,t,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}t.Color?t.warn("fabric.Color is already defined."):(t.Color=i,t.Color.prototype={_tryParsingColor:function(e){var t;e in i.colorNameMap&&(e=i.colorNameMap[e]),"transparent"===e&&(t=[255,255,255,0]),t||(t=i.sourceFromHex(e)),t||(t=i.sourceFromRgb(e)),t||(t=i.sourceFromHsl(e)),t||(t=[0,0,0,1]),t&&this.setSource(t)},_rgbToHsl:function(e,i,r){e/=255,i/=255,r/=255;var n,s,o,a=t.util.array.max([e,i,r]),h=t.util.array.min([e,i,r]);if(o=(a+h)/2,a===h)n=s=0;else{var l=a-h;switch(s=o>.5?l/(2-a-h):l/(a+h),a){case e:n=(i-r)/l+(i0)-(e<0)||+e};function f(e,t){var i=e.angle+u(Math.atan2(t.y,t.x))+360;return Math.round(i%360/45)}function g(e,i){var r=i.transform.target,n=r.canvas,s=t.util.object.clone(i);s.target=r,n&&n.fire("object:"+e,s),r.fire(e,i)}function _(e,t){var i=t.canvas,r=e[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(e){return e.originX===l&&e.originY===l}function m(e,t,i){var r=e.lockScalingX,n=e.lockScalingY;return!((!r||!n)&&(t||!r&&!n||!i)&&(!r||"x"!==t)&&(!n||"y"!==t))}function v(e,t,i,r){return{e,transform:t,pointer:{x:i,y:r}}}function y(e){return function(t,i,r,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=e(t,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function S(e,t){return function(i,r,n,s){var o=t(i,r,n,s);return o&&g(e,v(i,r,n,s)),o}}function w(e,i,r,n,s){var o=e.target,a=o.controls[e.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new t.Point(n,s),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function b(e){return e.flipX!==e.flipY}function C(e,t,i,r,n){if(0!==e[t]){var s=n/e._getTransformedDimensions()[r]*e[i];e.set(i,s)}}function x(e,t,i,r){var n,l=t.target,c=l._getTransformedDimensions(0,l.skewY),d=w(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),t.originX===s&&t.originY===h&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),b(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().y;l.set("skewX",n),C(l,"skewY","scaleY","y",p)}return _}function T(e,t,i,r){var n,l=t.target,c=l._getTransformedDimensions(l.skewX,0),d=w(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),t.originX===s&&t.originY===h&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),b(l)&&(n=-n));var _=g!==n;if(_){var p=l._getTransformedDimensions().x;l.set("skewY",n),C(l,"skewX","scaleX","x",p)}return _}function I(e,t,i,r,n){n=n||{};var s,o,a,h,l,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),b=m(f,y,S),C=t.gestureScale;if(b)return!1;if(C)o=t.scaleX*C,a=t.scaleY*C;else{if(s=w(t,t.originX,t.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,t.signX||(t.signX=l),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==l||t.signY!==u))return!1;if(h=f._getTransformedDimensions(),S&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=t.original,I=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);p(t)&&(o*=2,a*=2),t.signX!==l&&"y"!==y&&(t.originX=c[t.originX],o*=-1,t.signX=l),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.signY=u)}var A=f.scaleX,E=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),A!==f.scaleX||E!==f.scaleY}n.scaleCursorStyleHandler=function(e,t,r){var n=_(e,r),s="";if(0!==t.x&&0===t.y?s="x":0===t.x&&0!==t.y&&(s="y"),m(r,s,n))return"not-allowed";var o=f(r,t);return i[o]+"-resize"},n.skewCursorStyleHandler=function(e,t,i){var n="not-allowed";if(0!==t.x&&i.lockSkewingY)return n;if(0!==t.y&&i.lockSkewingX)return n;var s=f(i,t)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(e,t,i){return e[i.canvas.altActionKey]?n.skewCursorStyleHandler(e,t,i):n.scaleCursorStyleHandler(e,t,i)},n.rotationWithSnapping=S("rotating",y((function(e,t,i,r){var n=t,s=n.target,o=s.translateToOriginPoint(s.getCenterPoint(),n.originX,n.originY);if(s.lockRotation)return!1;var a,h=Math.atan2(n.ey-o.y,n.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+n.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),b(h)&&(n=n===s?a:s)),t.originX=n,S("skewing",y(x))(e,t,i,r))},n.skewHandlerY=function(e,t,i,r){var n,a=t.target,c=a.skewY,u=t.originX;return!a.lockSkewingY&&(0===c?n=w(t,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),b(a)&&(n=n===o?h:o)),t.originY=n,S("skewing",y(T))(e,t,i,r))},n.dragHandler=function(e,t,i,r){var n=t.target,s=i-t.offsetX,o=r-t.offsetY,a=!n.get("lockMovementX")&&n.left!==s,h=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),h&&n.set("top",o),(a||h)&&g("moving",v(e,t,i,r)),a||h},n.scaleOrSkewActionName=function(e,t,i){var r=e[i.canvas.altActionKey];return 0===t.x?r?"skewX":"scaleY":0===t.y?r?"skewY":"scaleX":void 0},n.rotationStyleHandler=function(e,t,i){return i.lockRotation?"not-allowed":t.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=S,n.getLocalPoint=w,t.controlsUtils=n}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians,r=t.controlsUtils;r.renderCircleControl=function(e,t,i,r,n){r=r||{};var s,o=this.sizeX||r.cornerSize||n.cornerSize,a=this.sizeY||r.cornerSize||n.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||n.cornerStrokeColor),u=t,d=i;e.save(),e.fillStyle=r.cornerColor||n.cornerColor,e.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,e.scale(1,a/o),d=i*o/a):a>o?(s=a,e.scale(o/a,1),u=t*a/o):s=o,e.lineWidth=1,e.beginPath(),e.arc(u,d,s/2,0,2*Math.PI,!1),e[l](),c&&e.stroke(),e.restore()},r.renderSquareControl=function(e,t,r,n,s){n=n||{};var o=this.sizeX||n.cornerSize||s.cornerSize,a=this.sizeY||n.cornerSize||s.cornerSize,h=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(n.cornerStrokeColor||s.cornerStrokeColor),u=o/2,d=a/2;e.save(),e.fillStyle=n.cornerColor||s.cornerColor,e.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,e.lineWidth=1,e.translate(t,r),e.rotate(i(s.angle)),e[l+"Rect"](-u,-d,o,a),c&&e.strokeRect(-u,-d,o,a),e.restore()}}(t),function(e){var t=e.fabric||(e.fabric={});t.Control=function(e){for(var t in e)this[t]=e[t]},t.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(e,t){return t.cursorStyle},getActionName:function(e,t){return t.actionName},getVisibility:function(e,t){var i=e._controlsVisibility;return i&&void 0!==i[t]?i[t]:this.visible},setVisibility:function(e){this.visible=e},positionHandler:function(e,i){return t.util.transformPoint({x:this.x*e.x+this.offsetX,y:this.y*e.y+this.offsetY},i)},calcCornerCoords:function(e,i,r,n,s){var o,a,h,l,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-t.util.degreesToRadians(e),_=Math.PI/2-d-t.util.degreesToRadians(e);o=f*t.util.cos(g),a=f*t.util.sin(g),h=f*t.util.cos(_),l=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),o=h=f*t.util.cos(g),a=l=f*t.util.sin(g);return{tl:{x:r-l,y:n-h},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+l,y:n+h}}},render:function(e,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?t.controlsUtils.renderCircleControl.call(this,e,i,r,n,s):t.controlsUtils.renderSquareControl.call(this,e,i,r,n,s)}}}(t),function(){function e(e,t){var i,r,n,s,o=e.getAttribute("style"),a=e.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),s=h.length;s--;){var l=h[s].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(n=u)}}return i||(i=e.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=e.getAttribute("stop-opacity")),r=(i=new x.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*t,{offset:a,color:i.toRgb(),opacity:n}}var t=x.util.object.clone;x.Gradient=x.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(e){e||(e={}),e.coords||(e.coords={});var t,i=this;Object.keys(e).forEach((function(t){i[t]=e[t]})),this.id?this.id+="_"+x.Object.__uid++:this.id=x.Object.__uid++,t={x1:e.coords.x1||0,y1:e.coords.y1||0,x2:e.coords.x2||0,y2:e.coords.y2||0},"radial"===this.type&&(t.r1=e.coords.r1||0,t.r2=e.coords.r2||0),this.coords=t,this.colorStops=e.colorStops.slice()},addColorStop:function(e){for(var t in e){var i=new x.Color(e[t]);this.colorStops.push({offset:parseFloat(t),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(e){var t={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return x.util.populateWithProperties(this,t,e),t},toSVG:function(e,i){var r,n,s,o,a=t(this.coords,!0),h=(i=i||{},t(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():x.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(e,t){return e.offset-t.offset})),"objectBoundingBox"===g?(u/=e.width,d/=e.height):(u+=e.width/2,d+=e.height/2),"path"===e.type&&"percentage"!==this.gradientUnits&&(u-=e.pathOffset.x,d-=e.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+x.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,n=h.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=h.length;r\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(e){var t,i,r,n=x.util.object.clone(this.coords);if(this.type){for("linear"===this.type?t=e.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(t=e.createRadialGradient(n.x1,n.y1,n.r1,n.x2,n.y2,n.r2)),i=0,r=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var o,a,h,l,c=t.getElementsByTagName("stop"),u="userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage",d=t.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?(o="linear",a=function(e){return{x1:e.getAttribute("x1")||0,y1:e.getAttribute("y1")||0,x2:e.getAttribute("x2")||"100%",y2:e.getAttribute("y2")||0}}(t)):(o="radial",a=function(e){return{x1:e.getAttribute("fx")||e.getAttribute("cx")||"50%",y1:e.getAttribute("fy")||e.getAttribute("cy")||"50%",r1:0,x2:e.getAttribute("cx")||"50%",y2:e.getAttribute("cy")||"50%",r2:e.getAttribute("r")||"50%"}}(t)),h=c.length;h--;)f.push(e(c[h],s));return l=x.parseTransformAttribute(d),function(e,t,i,r){var n,s;Object.keys(t).forEach((function(e){"Infinity"===(n=t[e])?s=1:"-Infinity"===n?s=0:(s=parseFloat(t[e],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==e&&"x2"!==e&&"r2"!==e||(s*=i.viewBoxWidth||i.width),"y1"!==e&&"y2"!==e||(s*=i.viewBoxHeight||i.height)))),t[e]=s}))}(0,a,n,u),"pixels"===u&&(g=-i.left,_=-i.top),new x.Gradient({id:t.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:_})}})}(),m=x.util.toFixed,x.Pattern=x.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(e,t){if(e||(e={}),this.id=x.Object.__uid++,this.setOptions(e),!e.source||e.source&&"string"!=typeof e.source)t&&t(this);else{var i=this;this.source=x.util.createImage(),x.util.loadImage(e.source,(function(e,r){i.source=e,t&&t(i,r)}),null,this.crossOrigin)}},toObject:function(e){var t,i,r=x.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?t=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(t=this.source.toDataURL()),i={type:"pattern",source:t,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},x.util.populateWithProperties(this,i,e),i},toSVG:function(e){var t="function"==typeof this.source?this.source():this.source,i=t.width/e.width,r=t.height/e.height,n=this.offsetX/e.width,s=this.offsetY/e.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,s&&(r+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,n&&(i+=Math.abs(n))),t.src?o=t.src:t.toDataURL&&(o=t.toDataURL()),'\n\n\n'},setOptions:function(e){for(var t in e)this[t]=e[t]},toLive:function(e){var t=this.source;if(!t)return"";if(void 0!==t.src){if(!t.complete)return"";if(0===t.naturalWidth||0===t.naturalHeight)return""}return e.createPattern(t,this.repeat)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.toFixed;t.Shadow?t.warn("fabric.Shadow is already defined."):(t.Shadow=t.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(e){for(var i in"string"==typeof e&&(e=this._parseShadow(e)),e)this[i]=e[i];this.id=t.Object.__uid++},_parseShadow:function(e){var i=e.trim(),r=t.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(t.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(e){var r=40,n=40,s=t.Object.NUM_FRACTION_DIGITS,o=t.util.rotateVector({x:this.offsetX,y:this.offsetY},t.util.degreesToRadians(-e.angle)),a=new t.Color(this.color);return e.width&&e.height&&(r=100*i((Math.abs(o.x)+this.blur)/e.width,s)+20,n=100*i((Math.abs(o.y)+this.blur)/e.height,s)+20),e.flipX&&(o.x*=-1),e.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var e={},i=t.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(t){this[t]!==i[t]&&(e[t]=this[t])}),this),e}}),t.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(t),function(){if(x.StaticCanvas)x.warn("fabric.StaticCanvas is already defined.");else{var e=x.util.object.extend,t=x.util.getElementOffset,i=x.util.removeFromArray,r=x.util.toFixed,n=x.util.transformPoint,s=x.util.invertTransform,o=x.util.getNodeCanvas,a=x.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");x.StaticCanvas=x.util.createClass(x.CommonMethods,{initialize:function(e,t){t||(t={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(e,t)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:x.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(e,t){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(e),this._initOptions(t),this.interactive||this._initRetinaScaling(),t.overlayImage&&this.setOverlayImage(t.overlayImage,i),t.backgroundImage&&this.setBackgroundImage(t.backgroundImage,i),t.backgroundColor&&this.setBackgroundColor(t.backgroundColor,i),t.overlayColor&&this.setOverlayColor(t.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return x.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,x.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var e=x.devicePixelRatio;this.__initRetinaScaling(e,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(e,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(e,t,i){t.setAttribute("width",this.width*e),t.setAttribute("height",this.height*e),i.scale(e,e)},calcOffset:function(){return this._offset=t(this.lowerCanvasEl),this},setOverlayImage:function(e,t,i){return this.__setBgOverlayImage("overlayImage",e,t,i)},setBackgroundImage:function(e,t,i){return this.__setBgOverlayImage("backgroundImage",e,t,i)},setOverlayColor:function(e,t){return this.__setBgOverlayColor("overlayColor",e,t)},setBackgroundColor:function(e,t){return this.__setBgOverlayColor("backgroundColor",e,t)},__setBgOverlayImage:function(e,t,i,r){return"string"==typeof t?x.util.loadImage(t,(function(t,n){if(t){var s=new x.Image(t,r);this[e]=s,s.canvas=this}i&&i(t,n)}),this,r&&r.crossOrigin):(r&&t.setOptions(r),this[e]=t,t&&(t.canvas=this),i&&i(t,!1)),this},__setBgOverlayColor:function(e,t,i){return this[e]=t,this._initGradient(t,e),this._initPattern(t,e,i),this},_createCanvasElement:function(){var e=a();if(!e)throw h;if(e.style||(e.style={}),void 0===e.getContext)throw h;return e},_initOptions:function(e){var t=this.lowerCanvasEl;this._setOptions(e),this.width=this.width||parseInt(t.width,10)||0,this.height=this.height||parseInt(t.height,10)||0,this.lowerCanvasEl.style&&(t.width=this.width,t.height=this.height,t.style.width=this.width+"px",t.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(e){e&&e.getContext?this.lowerCanvasEl=e:this.lowerCanvasEl=x.util.getById(e)||this._createCanvasElement(),x.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(e,t){return this.setDimensions({width:e},t)},setHeight:function(e,t){return this.setDimensions({height:e},t)},setDimensions:function(e,t){var i;for(var r in t=t||{},e)i=e[r],t.cssOnly||(this._setBackstoreDimension(r,e[r]),i+="px",this.hasLostContext=!0),t.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),t.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(e,t){return this.lowerCanvasEl[e]=t,this.upperCanvasEl&&(this.upperCanvasEl[e]=t),this.cacheCanvasEl&&(this.cacheCanvasEl[e]=t),this[e]=t,this},_setCssDimension:function(e,t){return this.lowerCanvasEl.style[e]=t,this.upperCanvasEl&&(this.upperCanvasEl.style[e]=t),this.wrapperEl&&(this.wrapperEl.style[e]=t),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(e){var t,i,r,n=this._activeObject,s=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=e,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",t),this._setSVGObjects(i,t),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",t),i.push(""),i.join("")},_setSVGPreamble:function(e,t){t.suppressPreamble||e.push('\n','\n')},_setSVGHeader:function(e,t){var i,n=t.width||this.width,s=t.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=x.Object.NUM_FRACTION_DIGITS;t.viewBox?o='viewBox="'+t.viewBox.x+" "+t.viewBox.y+" "+t.viewBox.width+" "+t.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),e.push("\n',"Created with Fabric.js ",x.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(t),"\n")},createSVGClipPathMarkup:function(e){var t=this.clipPath;return t?(t.clipPathId="CLIPPATH_"+x.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(e.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var e=this;return["background","overlay"].map((function(t){var i=e[t+"Color"];if(i&&i.toLive){var r=e[t+"Vpt"],n=e.viewportTransform,s={width:e.width/(r?n[0]:1),height:e.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?x.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var e,t,i,r,n,s,o,a,h="",l={},c=x.fontPaths,u=[];for(this._objects.forEach((function e(t){u.push(t),t._objects&&t._objects.forEach(e)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(e,t){var i,r,n,s=this._objects;for(r=0,n=s.length;r\n")}else e.push('\n")},sendToBack:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(t=(n=s._objects).length;t--;)r=n[t],i(this._objects,r),this._objects.unshift(r);else i(this._objects,e),this._objects.unshift(e);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(e){if(!e)return this;var t,r,n,s=this._activeObject;if(e===s&&"activeSelection"===e.type)for(n=s._objects,t=0;t0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(e))&&(o=this._findNewLowerIndex(e,s,t),i(this._objects,e),this._objects.splice(o,0,e));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(e,t,i){var r,n;if(i){for(r=t,n=t-1;n>=0;--n)if(e.intersectsWithObject(this._objects[n])||e.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(e)){r=n;break}}else r=t-1;return r},bringForward:function(e,t){if(!e)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(e===h&&"activeSelection"===e.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),e(x.StaticCanvas.prototype,x.Observable),e(x.StaticCanvas.prototype,x.Collection),e(x.StaticCanvas.prototype,x.DataURLExporter),e(x.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(e){var t=a();if(!t||!t.getContext)return null;var i=t.getContext("2d");return i&&"setLineDash"===e?void 0!==i.setLineDash:null}}),x.StaticCanvas.prototype.toJSON=x.StaticCanvas.prototype.toObject,x.isLikelyNode&&(x.StaticCanvas.prototype.createPNGStream=function(){var e=o(this.lowerCanvasEl);return e&&e.createPNGStream()},x.StaticCanvas.prototype.createJPEGStream=function(e){var t=o(this.lowerCanvasEl);return t&&t.createJPEGStream(e)})}}(),x.BaseBrush=x.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(e){e.strokeStyle=this.color,e.lineWidth=this.width,e.lineCap=this.strokeLineCap,e.miterLimit=this.strokeMiterLimit,e.lineJoin=this.strokeLineJoin,e.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(e){var t=this.canvas.viewportTransform;e.save(),e.transform(t[0],t[1],t[2],t[3],t[4],t[5])},_setShadow:function(){if(this.shadow){var e=this.canvas,t=this.shadow,i=e.contextTop,r=e.getZoom();e&&e._isRetinaScaling()&&(r*=x.devicePixelRatio),i.shadowColor=t.color,i.shadowBlur=t.blur*r,i.shadowOffsetX=t.offsetX*r,i.shadowOffsetY=t.offsetY*r}},needsFullRender:function(){return new x.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var e=this.canvas.contextTop;e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0},_isOutSideCanvas:function(e){return e.x<0||e.x>this.canvas.getWidth()||e.y<0||e.y>this.canvas.getHeight()}}),x.PencilBrush=x.util.createClass(x.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(e){this.canvas=e,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(e,t,i){var r=t.midPointFrom(i);return e.quadraticCurveTo(t.x,t.y,r.x,r.y),r},onMouseDown:function(e,t){this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],this._prepareForDrawing(e),this._captureDrawingPath(e),this._render())},onMouseMove:function(e,t){if(this.canvas._isMainEvent(t.e)&&(this.drawStraightLine=t.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(e))&&this._captureDrawingPath(e)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(n,i[r-2],i[r-1],!0),n.stroke(),n.restore()}},onMouseUp:function(e){return!this.canvas._isMainEvent(e.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(e){var t=new x.Point(e.x,e.y);this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)},_addPoint:function(e){return!(this._points.length>1&&e.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(e),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(e){var t=new x.Point(e.x,e.y);return this._addPoint(t)},_render:function(e){var t,i,r=this._points[0],n=this._points[1];if(e=e||this.canvas.contextTop,this._saveAndTransform(e),e.beginPath(),2===this._points.length&&r.x===n.x&&r.y===n.y){var s=this.width/1e3;r=new x.Point(r.x,r.y),n=new x.Point(n.x,n.y),r.x-=s,n.x+=s}for(e.moveTo(r.x,r.y),t=1,i=this._points.length;t=n&&(o=e[i],a.push(o));return a.push(e[s]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var e=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(e))this.canvas.requestRenderAll();else{var t=this.createPath(e);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:t}),this.canvas.add(t),this.canvas.requestRenderAll(),t.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:t})}}}),x.CircleBrush=x.util.createClass(x.BaseBrush,{width:10,initialize:function(e){this.canvas=e,this.points=[]},drawDot:function(e){var t=this.addPoint(e),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,t),i.restore()},dot:function(e,t){e.fillStyle=t.fill,e.beginPath(),e.arc(t.x,t.y,t.radius,0,2*Math.PI,!1),e.closePath(),e.fill()},onMouseDown:function(e){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(e)},_render:function(){var e,t,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),e=0,t=r.length;e0&&!this.preserveObjectStacking){t=[],i=[];for(var n=0,s=this._objects.length;n1&&(this._activeObject._objects=i),t.push.apply(t,i)}else t=this._objects;return t},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var e=this.contextContainer;return this.renderCanvas(e,this._chooseObjectsToRender()),this},renderTopLayer:function(e){e.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(e),this.contextTopDirty=!0),e.restore()},renderTop:function(){var e=this.contextTop;return this.clearContext(e),this.renderTopLayer(e),this.fire("after:render"),this},_normalizePointer:function(e,t){var i=e.calcTransformMatrix(),r=x.util.invertTransform(i),n=this.restorePointerVpt(t);return x.util.transformPoint(n,r)},isTargetTransparent:function(e,t,i){if(e.shouldCache()&&e._cacheCanvas&&e!==this._activeObject){var r=this._normalizePointer(e,{x:t,y:i}),n=Math.max(e.cacheTranslationX+r.x*e.zoomX,0),s=Math.max(e.cacheTranslationY+r.y*e.zoomY,0);return x.util.isTransparent(e._cacheContext,Math.round(n),Math.round(s),this.targetFindTolerance)}var o=this.contextCache,a=e.selectionBackgroundColor,h=this.viewportTransform;return e.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),e.render(o),o.restore(),e.selectionBackgroundColor=a,x.util.isTransparent(o,t,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(e){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(t){return!0===e[t]})):e[this.selectionKey]},_shouldClearSelection:function(e,t){var i=this.getActiveObjects(),r=this._activeObject;return!t||t&&r&&i.length>1&&-1===i.indexOf(t)&&r!==t&&!this._isSelectionKeyPressed(e)||t&&!t.evented||t&&!t.selectable&&r&&r!==t},_shouldCenterTransform:function(e,t,i){var r;if(e)return"scale"===t||"scaleX"===t||"scaleY"===t||"resizing"===t?r=this.centeredScaling||e.centeredScaling:"rotate"===t&&(r=this.centeredRotation||e.centeredRotation),r?!i:i},_getOriginFromCorner:function(e,t){var i={x:e.originX,y:e.originY};return"ml"===t||"tl"===t||"bl"===t?i.x="right":"mr"!==t&&"tr"!==t&&"br"!==t||(i.x="left"),"tl"===t||"mt"===t||"tr"===t?i.y="bottom":"bl"!==t&&"mb"!==t&&"br"!==t||(i.y="top"),i},_getActionFromCorner:function(e,t,i,r){if(!t||!e)return"drag";var n=r.controls[t];return n.getActionName(i,n,r)},_setupCurrentTransform:function(e,i,r){if(i){var n=this.getPointer(e),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(e,i,o):x.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,e,i),l=this._getOriginFromCorner(i,s),c=e[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:n.x-i.left,offsetY:n.y-i.top,originX:l.x,originY:l.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:t(i.angle),width:i.width*i.scaleX,shiftKey:e.shiftKey,altKey:c,original:x.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(e)}},setCursor:function(e){this.upperCanvasEl.style.cursor=e},_drawSelection:function(e){var t=this._groupSelector,i=new x.Point(t.ex,t.ey),r=x.util.transformPoint(i,this.viewportTransform),n=new x.Point(t.ex+t.left,t.ey+t.top),s=x.util.transformPoint(n,this.viewportTransform),o=Math.min(r.x,s.x),a=Math.min(r.y,s.y),h=Math.max(r.x,s.x),l=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,x.Object.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(o,a,h-o,l-a))},findTarget:function(e,t){if(!this.skipTargetFind){var r,n,s=this.getPointer(e,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(e),l=a.length>1&&!t||1===a.length;if(this.targets=[],l&&o._findTargetCorner(s,h))return o;if(a.length>1&&!t&&o===this._searchPossibleTargets([o],s))return o;if(1===a.length&&o===this._searchPossibleTargets([o],s)){if(!this.preserveObjectStacking)return o;r=o,n=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return e[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),c}},_checkTarget:function(e,t,i){if(t&&t.visible&&t.evented&&t.containsPoint(e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;if(!this.isTargetTransparent(t,i.x,i.y))return!0}},_searchPossibleTargets:function(e,t){for(var i,r,n=e.length;n--;){var s=e[n],o=s.group?this._normalizePointer(s.group,t):t;if(this._checkTarget(o,s,t)){(i=e[n]).subTargetCheck&&i instanceof x.Group&&(r=this._searchPossibleTargets(i._objects,t))&&this.targets.push(r);break}}return i},restorePointerVpt:function(e){return x.util.transformPoint(e,x.util.invertTransform(this.viewportTransform))},getPointer:function(t,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,n=e(t),s=this.upperCanvasEl,o=s.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,i||(n=this.restorePointerVpt(n));var l=this.getRetinaScaling();return 1!==l&&(n.x/=l,n.y/=l),r=0===a||0===h?{width:1,height:1}:{width:s.width/a,height:s.height/h},{x:n.x*r.width,y:n.y*r.height}},_createUpperCanvas:function(){var e=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),t=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),x.util.addClass(i,"upper-canvas "+e),this.wrapperEl.appendChild(i),this._copyCanvasStyle(t,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=x.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),x.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),x.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(e){var t=this.width||e.width,i=this.height||e.height;x.util.setStyle(e,{position:"absolute",width:t+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),e.width=t,e.height=i,x.util.makeElementUnselectable(e)},_copyCanvasStyle:function(e,t){t.style.cssText=e.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var e=this._activeObject;return e?"activeSelection"===e.type&&e._objects?e._objects.slice(0):[e]:[]},_onObjectRemoved:function(e){e===this._activeObject&&(this.fire("before:selection:cleared",{target:e}),this._discardActiveObject(),this.fire("selection:cleared",{target:e}),e.fire("deselected")),e===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",e)},_fireSelectionEvents:function(e,t){var i=!1,r=this.getActiveObjects(),n=[],s=[];e.forEach((function(e){-1===r.indexOf(e)&&(i=!0,e.fire("deselected",{e:t,target:e}),s.push(e))})),r.forEach((function(r){-1===e.indexOf(r)&&(i=!0,r.fire("selected",{e:t,target:r}),n.push(r))})),e.length>0&&r.length>0?i&&this.fire("selection:updated",{e:t,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:t,selected:n}):e.length>0&&this.fire("selection:cleared",{e:t,deselected:s})},setActiveObject:function(e,t){var i=this.getActiveObjects();return this._setActiveObject(e,t),this._fireSelectionEvents(i,t),this},_setActiveObject:function(e,t){return this._activeObject!==e&&!!this._discardActiveObject(t,e)&&!e.onSelect({e:t})&&(this._activeObject=e,!0)},_discardActiveObject:function(e,t){var i=this._activeObject;if(i){if(i.onDeselect({e,object:t}))return!1;this._activeObject=null}return!0},discardActiveObject:function(e){var t=this.getActiveObjects(),i=this.getActiveObject();return t.length&&this.fire("before:selection:cleared",{target:i,e}),this._discardActiveObject(e),this._fireSelectionEvents(t,e),this},dispose:function(){var e=this.wrapperEl;return this.removeListeners(),e.removeChild(this.upperCanvasEl),e.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(e){x.util.cleanUpJsdomNode(this[e]),this[e]=void 0}.bind(this)),e.parentNode&&e.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,x.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(e){var t=this._activeObject;t&&t._renderControls(e)},_toObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(e),n=this.callSuper("_toObject",e,t,i);return this._unwindGroupTransformOnObject(e,r),n},_realizeGroupTransformOnObject:function(e){if(e.group&&"activeSelection"===e.group.type&&this._activeObject===e.group){var t={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){t[i]=e[i]})),x.util.addTransformToObject(e,this._activeObject.calcOwnMatrix()),t}return null},_unwindGroupTransformOnObject:function(e,t){t&&e.set(t)},_setSVGObject:function(e,t,i){var r=this._realizeGroupTransformOnObject(t);this.callSuper("_setSVGObject",e,t,i),this._unwindGroupTransformOnObject(t,r)},setViewportTransform:function(e){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),x.StaticCanvas.prototype.setViewportTransform.call(this,e)}}),x.StaticCanvas)"prototype"!==r&&(x.Canvas[r]=x.StaticCanvas[r])}(),function(){var e=x.util.addListener,t=x.util.removeListener,i={passive:!1};function r(e,t){return e.button&&e.button===t-1}x.util.object.extend(x.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(e,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(e,t){var r=this.upperCanvasEl,n=this._getEventPrefix();e(x.window,"resize",this._onResize),e(r,n+"down",this._onMouseDown),e(r,n+"move",this._onMouseMove,i),e(r,n+"out",this._onMouseOut),e(r,n+"enter",this._onMouseEnter),e(r,"wheel",this._onMouseWheel),e(r,"contextmenu",this._onContextMenu),e(r,"dblclick",this._onDoubleClick),e(r,"dragover",this._onDragOver),e(r,"dragenter",this._onDragEnter),e(r,"dragleave",this._onDragLeave),e(r,"drop",this._onDrop),this.enablePointerEvents||e(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&t in eventjs&&(eventjs[t](r,"gesture",this._onGesture),eventjs[t](r,"drag",this._onDrag),eventjs[t](r,"orientation",this._onOrientationChange),eventjs[t](r,"shake",this._onShake),eventjs[t](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(t,"remove");var e=this._getEventPrefix();t(x.document,e+"up",this._onMouseUp),t(x.document,"touchend",this._onTouchEnd,i),t(x.document,e+"move",this._onMouseMove,i),t(x.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(e,t){this.__onTransformGesture&&this.__onTransformGesture(e,t)},_onDrag:function(e,t){this.__onDrag&&this.__onDrag(e,t)},_onMouseWheel:function(e){this.__onMouseWheel(e)},_onMouseOut:function(e){var t=this._hoveredTarget;this.fire("mouse:out",{target:t,e}),this._hoveredTarget=null,t&&t.fire("mouseout",{e});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:t,e}),r&&t.fire("mouseout",{e})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(e){e.isEditing&&e.hiddenTextarea.focus()}))},_onMouseEnter:function(e){this._currentTransform||this.findTarget(e)||(this.fire("mouse:over",{target:null,e}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(e,t){this.__onOrientationChange&&this.__onOrientationChange(e,t)},_onShake:function(e,t){this.__onShake&&this.__onShake(e,t)},_onLongPress:function(e,t){this.__onLongPress&&this.__onLongPress(e,t)},_onDragOver:function(e){e.preventDefault();var t=this._simpleEventHandler("dragover",e);this._fireEnterLeaveEvents(t,e)},_onDrop:function(e){return this._simpleEventHandler("drop:before",e),this._simpleEventHandler("drop",e)},_onContextMenu:function(e){return this.stopContextMenu&&(e.stopPropagation(),e.preventDefault()),!1},_onDoubleClick:function(e){this._cacheTransformEventData(e),this._handleEvent(e,"dblclick"),this._resetTransformEventData(e)},getPointerId:function(e){var t=e.changedTouches;return t?t[0]&&t[0].identifier:this.enablePointerEvents?e.pointerId:-1},_isMainEvent:function(e){return!0===e.isPrimary||!1!==e.isPrimary&&("touchend"===e.type&&0===e.touches.length||!e.changedTouches||e.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(x.document,"touchend",this._onTouchEnd,i),e(x.document,"touchmove",this._onMouseMove,i),t(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();t(n,s+"move",this._onMouseMove,i),e(x.document,s+"up",this._onMouseUp),e(x.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var n=this._getEventPrefix();t(x.document,"touchend",this._onTouchEnd,i),t(x.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){e(s.upperCanvasEl,n+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(r)&&(t(x.document,s+"up",this._onMouseUp),t(x.document,s+"move",this._onMouseMove,i),e(n,s+"move",this._onMouseMove,i))},_onMouseMove:function(e){!this.allowTouchScrolling&&e.preventDefault&&e.preventDefault(),this.__onMouseMove(e)},_onResize:function(){this.calcOffset()},_shouldRender:function(e){var t=this._activeObject;return!!(!!t!=!!e||t&&e&&t!==e)||(t&&t.isEditing,!1)},__onMouseUp:function(e){var t,i=this._currentTransform,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.top;if(this._cacheTransformEventData(e),t=this._target,this._handleEvent(e,"up:before"),r(e,3))this.fireRightClick&&this._handleEvent(e,"up",3,o);else{if(r(e,2))return this.fireMiddleClick&&this._handleEvent(e,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(e);else if(this._isMainEvent(e)){if(i&&(this._finalizeCurrentTransform(e),s=i.actionPerformed),!o){var a=t===this._activeObject;this._maybeGroupObjects(e),s||(s=this._shouldRender(t)||!a&&t===this._activeObject)}var h,l;if(t){if(h=t._findTargetCorner(this.getPointer(e,!0),x.util.isTouchEvent(e)),t.selectable&&t!==this._activeObject&&"up"===t.activeOn)this.setActiveObject(t,e),s=!0;else{var c=t.controls[h],u=c&&c.getMouseUpHandler(e,t,c);u&&u(e,i,(l=this.getPointer(e)).x,l.y)}t.isMoving=!1}if(i&&(i.target!==t||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(e,t,c);l=l||this.getPointer(e),f&&f(e,i,l.x,l.y)}this._setCursorFromEvent(e,t),this._handleEvent(e,"up",1,o),this._groupSelector=null,this._currentTransform=null,t&&(t.__corner=0),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(e,t){var i=this.findTarget(t),r=this.targets,n={e:t,target:i,subTargets:r};if(this.fire(e,n),i&&i.fire(e,n),!r)return i;for(var s=0;s1&&(t=new x.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(t,e))},_collectObjects:function(e){for(var t,i=[],r=this._groupSelector.ex,n=this._groupSelector.ey,s=r+this._groupSelector.left,o=n+this._groupSelector.top,a=new x.Point(v(r,s),v(n,o)),h=new x.Point(y(r,s),y(n,o)),l=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((t=this._objects[u])&&t.selectable&&t.visible&&(l&&t.intersectsWithRect(a,h,!0)||t.isContainedWithinRect(a,h,!0)||l&&t.containsPoint(a,null,!0)||l&&t.containsPoint(h,null,!0))&&(i.push(t),c)););return i.length>1&&(i=i.filter((function(t){return!t.onSelect({e})}))),i},_maybeGroupObjects:function(e){this.selection&&this._groupSelector&&this._groupSelectedObjects(e),this.setCursor(this.defaultCursor),this._groupSelector=null}}),x.util.object.extend(x.StaticCanvas.prototype,{toDataURL:function(e){e||(e={});var t=e.format||"png",i=e.quality||1,r=(e.multiplier||1)*(e.enableRetinaScaling?this.getRetinaScaling():1),n=this.toCanvasElement(r,e);return x.util.toDataURL(n,t,i)},toCanvasElement:function(e,t){e=e||1;var i=((t=t||{}).width||this.width)*e,r=(t.height||this.height)*e,n=this.getZoom(),s=this.width,o=this.height,a=n*e,h=this.viewportTransform,l=(h[4]-(t.left||0))*e,c=(h[5]-(t.top||0))*e,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=x.util.createCanvasElement(),_=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=s,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=_,g}}),x.util.object.extend(x.StaticCanvas.prototype,{loadFromJSON:function(e,t,i){if(e){var r="string"==typeof e?JSON.parse(e):x.util.object.clone(e),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(e){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,e,o,t)})):n.__setupCanvas.call(n,r,e,o,t)}))}),i),this}},__setupCanvas:function(e,t,i,r){var n=this;t.forEach((function(e,t){n.insertAt(e,t)})),this.renderOnAddRemove=i,delete e.objects,delete e.backgroundImage,delete e.overlayImage,delete e.background,delete e.overlay,this._setOptions(e),this.renderAll(),r&&r()},_setBgOverlay:function(e,t){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(e.backgroundImage||e.overlayImage||e.background||e.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&t&&t()};this.__setBgOverlay("backgroundImage",e.backgroundImage,i,r),this.__setBgOverlay("overlayImage",e.overlayImage,i,r),this.__setBgOverlay("backgroundColor",e.background,i,r),this.__setBgOverlay("overlayColor",e.overlay,i,r)}else t&&t()},__setBgOverlay:function(e,t,i,r){var n=this;if(!t)return i[e]=!0,void(r&&r());"backgroundImage"===e||"overlayImage"===e?x.util.enlivenObjects([t],(function(t){n[e]=t[0],i[e]=!0,r&&r()})):this["set"+x.util.string.capitalize(e,!0)](t,(function(){i[e]=!0,r&&r()}))},_enlivenObjects:function(e,t,i){e&&0!==e.length?x.util.enlivenObjects(e,(function(e){t&&t(e)}),null,i):t&&t([])},_toDataURL:function(e,t){this.clone((function(i){t(i.toDataURL(e))}))},_toDataURLWithMultiplier:function(e,t,i){this.clone((function(r){i(r.toDataURLWithMultiplier(e,t))}))},clone:function(e,t){var i=JSON.stringify(this.toJSON(t));this.cloneWithoutData((function(t){t.loadFromJSON(i,(function(){e&&e(t)}))}))},cloneWithoutData:function(e){var t=x.util.createCanvasElement();t.width=this.width,t.height=this.height;var i=new x.Canvas(t);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),e&&e(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):e&&e(i)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n=t.util.toFixed,s=t.util.string.capitalize,o=t.util.degreesToRadians,a=!t.isLikelyNode;t.Object||(t.Object=t.util.createClass(t.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(e){e&&this.setOptions(e)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=t.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(e){var i=t.perfLimitSizeTotal,r=e.width,n=e.height,s=t.maxCacheSideLimit,o=t.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(e.zoomX/=r/c,e.width=c,e.capped=!0),n>u&&(e.zoomY/=n/u,e.height=u,e.capped=!0),e},_getCacheCanvasDimensions:function(){var e=this.getTotalObjectScaling(),t=this._getTransformedDimensions(0,0),i=t.x*e.scaleX/this.scaleX,r=t.y*e.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:e.scaleX,zoomY:e.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var e=this.canvas;if(this.noScaleCache&&e&&e._currentTransform){var i=e._currentTransform.target,r=e._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var n,s,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=t.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,_=f||g,p=0,m=0,v=!1;if(f){var y=this._cacheCanvas.width,S=this._cacheCanvas.height,w=l>y||c>S;v=w||(l<.9*y||c<.9*S)&&y>h&&S>h,w&&!a.capped&&(l>h||c>h)&&(p=.1*l,m=.1*c)}return this instanceof t.Text&&this.path&&(_=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!_&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+m)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),n=a.x/2,s=a.y/2,this.cacheTranslationX=Math.round(o.width/2-n)+n,this.cacheTranslationY=Math.round(o.height/2-s)+s,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(e){this._setOptions(e),this._initGradient(e.fill,"fill"),this._initGradient(e.stroke,"stroke"),this._initPattern(e.fill,"fill"),this._initPattern(e.stroke,"stroke")},transform:function(e){var t=this.group&&!this.group._transformDone||this.group&&this.canvas&&e===this.canvas.contextTop,i=this.calcTransformMatrix(!t);e.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(e){var i=t.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:t.version,originX:this.originX,originY:this.originY,left:n(this.left,i),top:n(this.top,i),width:n(this.width,i),height:n(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:n(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:n(this.strokeMiterLimit,i),scaleX:n(this.scaleX,i),scaleY:n(this.scaleY,i),angle:n(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:n(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:n(this.skewX,i),skewY:n(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(e),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),t.util.populateWithProperties(this,r,e),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(e){return this.toObject(e)},_removeDefaultValues:function(e){var i=t.util.getKlass(e.type).prototype;return i.stateProperties.forEach((function(t){"left"!==t&&"top"!==t&&(e[t]===i[t]&&delete e[t],Array.isArray(e[t])&&Array.isArray(i[t])&&0===e[t].length&&0===i[t].length&&delete e[t])})),e},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var e=t.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(e.scaleX),scaleY:Math.abs(e.scaleY)}},getTotalObjectScaling:function(){var e=this.getObjectScaling(),t=e.scaleX,i=e.scaleY;if(this.canvas){var r=this.canvas.getZoom(),n=this.canvas.getRetinaScaling();t*=r*n,i*=r*n}return{scaleX:t,scaleY:i}},getObjectOpacity:function(){var e=this.opacity;return this.group&&(e*=this.group.getObjectOpacity()),e},_set:function(e,i){var r="scaleX"===e||"scaleY"===e,n=this[e]!==i,s=!1;return r&&(i=this._constrainScale(i)),"scaleX"===e&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===e&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==e||!i||i instanceof t.Shadow?"dirty"===e&&this.group&&this.group.set("dirty",i):i=new t.Shadow(i),this[e]=i,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(e)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(e)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:t.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(e){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(e.save(),this._setupCompositeOperation(e),this.drawSelectionBackground(e),this.transform(e),this._setOpacity(e),this._setShadow(e,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(e)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(e),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),e.restore())},renderCache:function(e){e=e||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,e.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(e,i){if(e.save(),i.inverted?e.globalCompositeOperation="destination-out":e.globalCompositeOperation="destination-in",i.absolutePositioned){var r=t.util.invertTransform(this.calcTransformMatrix());e.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(e),e.scale(1/i.zoomX,1/i.zoomY),e.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),e.restore()},drawObject:function(e,t){var i=this.fill,r=this.stroke;t?(this.fill="black",this.stroke="",this._setClippingProperties(e)):this._renderBackground(e),this._render(e),this._drawClipPath(e,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(e,t){t&&(t.canvas=this.canvas,t.shouldCache(),t._transformDone=!0,t.renderCache({forClipping:!0}),this.drawClipPathOnCache(e,t))},drawCacheOnCanvas:function(e){e.scale(1/this.zoomX,1/this.zoomY),e.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(e){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!e&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!e){var t=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-t/2,-i/2,t,i)}return!0}return!1},_renderBackground:function(e){if(this.backgroundColor){var t=this._getNonTransformedDimensions();e.fillStyle=this.backgroundColor,e.fillRect(-t.x/2,-t.y/2,t.x,t.y),this._removeShadow(e)}},_setOpacity:function(e){this.group&&!this.group._transformDone?e.globalAlpha=this.getObjectOpacity():e.globalAlpha*=this.opacity},_setStrokeStyles:function(e,t){var i=t.stroke;i&&(e.lineWidth=t.strokeWidth,e.lineCap=t.strokeLineCap,e.lineDashOffset=t.strokeDashOffset,e.lineJoin=t.strokeLineJoin,e.miterLimit=t.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(e,i):(e.strokeStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,i)):e.strokeStyle=t.stroke)},_setFillStyles:function(e,t){var i=t.fill;i&&(i.toLive?(e.fillStyle=i.toLive(e,this),this._applyPatternGradientTransform(e,t.fill)):e.fillStyle=i)},_setClippingProperties:function(e){e.globalAlpha=1,e.strokeStyle="transparent",e.fillStyle="#000000"},_setLineDash:function(e,t){t&&0!==t.length&&(1&t.length&&t.push.apply(t,t),e.setLineDash(t))},_renderControls:function(e,i){var r,n,s,a=this.getViewportTransform(),h=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,h=t.util.multiplyTransformMatrices(a,h),r=t.util.qrDecompose(h),e.save(),e.translate(r.translateX,r.translateY),e.lineWidth=1*this.borderScaleFactor,this.group||(e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),e.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?n&&this.drawBordersInGroup(e,r,i):n&&this.drawBorders(e,i),s&&this.drawControls(e,i),e.restore()},_setShadow:function(e){if(this.shadow){var i,r=this.shadow,n=this.canvas,s=n&&n.viewportTransform[0]||1,o=n&&n.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),n&&n._isRetinaScaling()&&(s*=t.devicePixelRatio,o*=t.devicePixelRatio),e.shadowColor=r.color,e.shadowBlur=r.blur*t.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,e.shadowOffsetX=r.offsetX*s*i.scaleX,e.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(e){this.shadow&&(e.shadowColor="",e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0)},_applyPatternGradientTransform:function(e,t){if(!t||!t.toLive)return{offsetX:0,offsetY:0};var i=t.gradientTransform||t.patternTransform,r=-this.width/2+t.offsetX||0,n=-this.height/2+t.offsetY||0;return"percentage"===t.gradientUnits?e.transform(this.width,0,0,this.height,r,n):e.transform(1,0,0,1,r,n),i&&e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_renderPaintInOrder:function(e){"stroke"===this.paintFirst?(this._renderStroke(e),this._renderFill(e)):(this._renderFill(e),this._renderStroke(e))},_render:function(){},_renderFill:function(e){this.fill&&(e.save(),this._setFillStyles(e,this),"evenodd"===this.fillRule?e.fill("evenodd"):e.fill(),e.restore())},_renderStroke:function(e){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this.strokeUniform&&this.group){var t=this.getObjectScaling();e.scale(1/t.scaleX,1/t.scaleY)}else this.strokeUniform&&e.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(e,this.strokeDashArray),this._setStrokeStyles(e,this),e.stroke(),e.restore()}},_applyPatternForTransformedGradient:function(e,i){var r,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=t.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=n.x/this.scaleX/o,h=n.y/this.scaleY/o;s.width=a,s.height=h,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(n.zoomX/this.scaleX/o,n.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(e),r.fill(),e.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),e.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),e.strokeStyle=r.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var e=t.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",e.scaleX),this.set("scaleY",e.scaleY),this.angle=e.angle,this.skewX=e.skewX,this.skewY=0}},_removeTransformMatrix:function(e){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=t.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,e&&(this.scaleX*=e.scaleX,this.scaleY*=e.scaleY,this.cropX=e.cropX,this.cropY=e.cropY,i.x+=e.offsetLeft,i.y+=e.offsetTop,this.width=e.width,this.height=e.height),this.setPositionByOrigin(i,"center","center")},clone:function(e,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,e):t.Object._fromObject("Object",r,e)},cloneAsImage:function(e,i){var r=this.toCanvasElement(i);return e&&e(new t.Image(r)),this},toCanvasElement:function(e){e||(e={});var i=t.util,r=i.saveObjectTransform(this),n=this.group,s=this.shadow,o=Math.abs,a=(e.multiplier||1)*(e.enableRetinaScaling?t.devicePixelRatio:1);delete this.group,e.withoutTransform&&i.resetObjectTransform(this),e.withoutShadow&&(this.shadow=null);var h,l,c,u,d=t.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),_.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+_.x,u=f.height+_.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new t.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===e.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new t.Point(p.width/2,p.height/2),"center","center");var m=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,e);return this.shadow=s,this.set("canvas",m),n&&(this.group=n),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(e){return e||(e={}),t.util.toDataURL(this.toCanvasElement(e),e.format||"png",e.quality||1)},isType:function(e){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===e},complexity:function(){return 1},toJSON:function(e){return this.toObject(e)},rotate:function(e){var t=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return t&&this._setOriginToCenter(),this.set("angle",e),t&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(e,i){i=i||this.canvas.getPointer(e);var r=new t.Point(i.x,i.y),n=this._getLeftTopCoords();return this.angle&&(r=t.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.y}},_setupCompositeOperation:function(e){this.globalCompositeOperation&&(e.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){t.runningAnimations&&t.runningAnimations.cancelByTarget(this)}}),t.util.createAccessors&&t.util.createAccessors(t.Object),i(t.Object.prototype,t.Observable),t.Object.NUM_FRACTION_DIGITS=2,t.Object.ENLIVEN_PROPS=["clipPath"],t.Object._fromObject=function(e,i,n,s){var o=t[e];i=r(i,!0),t.util.enlivenPatterns([i.fill,i.stroke],(function(e){void 0!==e[0]&&(i.fill=e[0]),void 0!==e[1]&&(i.stroke=e[1]),t.util.enlivenObjectEnlivables(i,i,(function(){var e=s?new o(i[s],i):new o(i);n&&n(e)}))}))},t.Object.__uid=0)}(t),S=x.util.degreesToRadians,w={left:-.5,center:0,right:.5},b={top:-.5,center:0,bottom:.5},x.util.object.extend(x.Object.prototype,{translateToGivenOrigin:function(e,t,i,r,n){var s,o,a,h=e.x,l=e.y;return"string"==typeof t?t=w[t]:t-=.5,"string"==typeof r?r=w[r]:r-=.5,"string"==typeof i?i=b[i]:i-=.5,"string"==typeof n?n=b[n]:n-=.5,o=n-i,((s=r-t)||o)&&(a=this._getTransformedDimensions(),h=e.x+s*a.x,l=e.y+o*a.y),new x.Point(h,l)},translateToCenterPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,t,i,"center","center");return this.angle?x.util.rotatePoint(r,e,S(this.angle)):r},translateToOriginPoint:function(e,t,i){var r=this.translateToGivenOrigin(e,"center","center",t,i);return this.angle?x.util.rotatePoint(r,e,S(this.angle)):r},getCenterPoint:function(){var e=new x.Point(this.left,this.top);return this.translateToCenterPoint(e,this.originX,this.originY)},getPointByOrigin:function(e,t){var i=this.getCenterPoint();return this.translateToOriginPoint(i,e,t)},toLocalPoint:function(e,t,i){var r,n,s=this.getCenterPoint();return r=void 0!==t&&void 0!==i?this.translateToGivenOrigin(s,"center","center",t,i):new x.Point(this.left,this.top),n=new x.Point(e.x,e.y),this.angle&&(n=x.util.rotatePoint(n,s,-S(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(e,t,i){var r=this.translateToCenterPoint(e,t,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(e){var t,i,r=S(this.angle),n=this.getScaledWidth(),s=x.util.cos(r)*n,o=x.util.sin(r)*n;t="string"==typeof this.originX?w[this.originX]:this.originX-.5,i="string"==typeof e?w[e]:e-.5,this.left+=s*(i-t),this.top+=o*(i-t),this.setCoords(),this.originX=e},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var e=this.getCenterPoint();this.originX="center",this.originY="center",this.left=e.x,this.top=e.y},_resetOrigin:function(){var e=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=e.x,this.top=e.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var e=x.util,t=e.degreesToRadians,i=e.multiplyTransformMatrices,r=e.transformPoint;e.object.extend(x.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(e,t){return t?e?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),e?this.aCoords:this.lineCoords)},getCoords:function(e,t){return i=this._getCoords(e,t),[new x.Point(i.tl.x,i.tl.y),new x.Point(i.tr.x,i.tr.y),new x.Point(i.br.x,i.br.y),new x.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(e,t,i,r){var n=this.getCoords(i,r);return"Intersection"===x.Intersection.intersectPolygonRectangle(n,e,t).status},intersectsWithObject:function(e,t,i){return"Intersection"===x.Intersection.intersectPolygonPolygon(this.getCoords(t,i),e.getCoords(t,i)).status||e.isContainedWithinObject(this,t,i)||this.isContainedWithinObject(e,t,i)},isContainedWithinObject:function(e,t,i){for(var r=this.getCoords(t,i),n=t?e.aCoords:e.lineCoords,s=0,o=e._getImageLines(n);s<4;s++)if(!e.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(e,t,i,r){var n=this.getBoundingRect(i,r);return n.left>=e.x&&n.left+n.width<=t.x&&n.top>=e.y&&n.top+n.height<=t.y},containsPoint:function(e,t,i,r){var n=this._getCoords(i,r),s=(t=t||this._getImageLines(n),this._findCrossPoints(e,t));return 0!==s&&s%2==1},isOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,e).some((function(e){return e.x<=i.x&&e.x>=t.x&&e.y<=i.y&&e.y>=t.y}))||!!this.intersectsWithRect(t,i,!0,e)||this._containsCenterOfCanvas(t,i,e)},_containsCenterOfCanvas:function(e,t,i){var r={x:(e.x+t.x)/2,y:(e.y+t.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(e){if(!this.canvas)return!1;var t=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(t,i,!0,e)||this.getCoords(!0,e).every((function(e){return(e.x>=i.x||e.x<=t.x)&&(e.y>=i.y||e.y<=t.y)}))&&this._containsCenterOfCanvas(t,i,e)},_getImageLines:function(e){return{topline:{o:e.tl,d:e.tr},rightline:{o:e.tr,d:e.br},bottomline:{o:e.br,d:e.bl},leftline:{o:e.bl,d:e.tl}}},_findCrossPoints:function(e,t){var i,r,n,s=0;for(var o in t)if(!((n=t[o]).o.y=e.y&&n.d.y>=e.y||(n.o.x===n.d.x&&n.o.x>=e.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(e.y-0*e.x-(n.o.y-i*n.o.x))/(0-i)),r>=e.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(t,i){var r=this.getCoords(t,i);return e.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(e){return Math.abs(e)\n')}},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(e),{reviver:e})},toClipPathSVG:function(e){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(e),{reviver:e})},_createBaseClipPathSVGMarkup:function(e,t){var i=(t=t||{}).reviver,r=t.additionalTransform||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=e.indexOf("COMMON_PARTS");return e[s]=n,i?i(e.join("")):e.join("")},_createBaseSVGMarkup:function(e,t){var i,r,n=(t=t||{}).noStyle,s=t.reviver,o=n?"":'style="'+this.getSvgStyles()+'" ',a=t.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=e.indexOf("COMMON_PARTS"),p=t.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+x.Object.__uid++,r='\n'+h.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),e[_]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(e.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var e=x.util.object.extend,t="stateProperties";function i(t,i,r){var n={};r.forEach((function(e){n[e]=t[e]})),e(t[i],n,!0)}function r(e,t,i){if(e===t)return!0;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(var n=0,s=e.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(t?this.oCoords[n].touchCorner:this.oCoords[n].corner),0!==(i=this._findCrossPoints({x:s,y:o},r))&&i%2==1))return this.__corner=n,n;return!1},forEachControl:function(e){for(var t in this.controls)e(this.controls[t],t,this)},_setCornerCoords:function(){var e=this.oCoords;for(var t in e){var i=this.controls[t];e[t].corner=i.calcCornerCoords(this.angle,this.cornerSize,e[t].x,e[t].y,!1),e[t].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,e[t].x,e[t].y,!0)}},drawSelectionBackground:function(t){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;t.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),n=this.canvas.viewportTransform;return t.translate(i.x,i.y),t.scale(1/n[0],1/n[3]),t.rotate(e(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-r.x/2,-r.y/2,r.x,r.y),t.restore(),this},drawBorders:function(e,t){t=t||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,n=i.x+r,s=i.y+r,o=void 0!==t.hasControls?t.hasControls:this.hasControls,a=!1;return e.save(),e.strokeStyle=t.borderColor||this.borderColor,this._setLineDash(e,t.borderDashArray||this.borderDashArray),e.strokeRect(-n/2,-s/2,n,s),o&&(e.beginPath(),this.forEachControl((function(t,i,r){t.withConnection&&t.getVisibility(r,i)&&(a=!0,e.moveTo(t.x*n,t.y*s),e.lineTo(t.x*n+t.offsetX,t.y*s+t.offsetY))})),a&&e.stroke()),e.restore(),this},drawBordersInGroup:function(e,t,i){i=i||{};var r=x.util.sizeAfterTransform(this.width,this.height,t),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():t.scaleX)+o,h=r.y+n*(s?this.canvas.getZoom():t.scaleY)+o;return e.save(),this._setLineDash(e,i.borderDashArray||this.borderDashArray),e.strokeStyle=i.borderColor||this.borderColor,e.strokeRect(-a/2,-h/2,a,h),e.restore(),this},drawControls:function(e,t){t=t||{},e.save();var i,r,n=this.canvas.getRetinaScaling();return e.setTransform(n,0,0,n,0,0),e.strokeStyle=e.fillStyle=t.cornerColor||this.cornerColor,this.transparentCorners||(e.strokeStyle=t.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(e,t.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=x.util.transformPoint(r,i)),n.render(e,r.x,r.y,t,o))})),e.restore(),this},isControlVisible:function(e){return this.controls[e]&&this.controls[e].getVisibility(this,e)},setControlVisible:function(e,t){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[e]=t,this},setControlsVisibility:function(e){for(var t in e||(e={}),e)this.setControlVisible(t,e[t]);return this},onDeselect:function(){},onSelect:function(){}})}(),x.util.object.extend(x.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(t){e.set("left",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxCenterObjectV:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(t){e.set("top",t),s.requestRenderAll(),n()},onComplete:function(){e.setCoords(),r()}})},fxRemove:function(e,t){var i=function(){},r=(t=t||{}).onComplete||i,n=t.onChange||i,s=this;return x.util.animate({target:this,startValue:e.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(t){e.set("opacity",t),s.requestRenderAll(),n()},onComplete:function(){s.remove(e),r()}})}}),x.util.object.extend(x.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var e,t,i=[],r=[];for(e in arguments[0])i.push(e);for(var n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[1]]:this.get(e);"from"in i||(i.from=a),o||(t=~t.indexOf("=")?a+parseFloat(t.replace("=","")):parseFloat(t));var h={target:this,startValue:i.from,endValue:t,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(e,t,r){return i.abort.call(s,e,t,r)},onChange:function(t,o,a){n?s[n[0]][n[1]]=t:s.set(e,t),r||i.onChange&&i.onChange(t,o,a)},onComplete:function(e,t,n){r||(s.setCoords(),i.onComplete&&i.onComplete(e,t,n))}};return o?x.util.animateColor(h.startValue,h.endValue,h.duration,h):x.util.animate(h)}}),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.object.clone,n={x1:1,x2:1,y1:1,y2:1};function s(e,t){var i=e.origin,r=e.axis1,n=e.axis2,s=e.dimension,o=t.nearest,a=t.center,h=t.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(n));case a:return Math.min(this.get(r),this.get(n))+.5*this.get(s);case h:return Math.max(this.get(r),this.get(n))}}}t.Line?t.warn("fabric.Line is already defined"):(t.Line=t.util.createClass(t.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:t.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(e,t){e||(e=[0,0,0,0]),this.callSuper("initialize",t),this.set("x1",e[0]),this.set("y1",e[1]),this.set("x2",e[2]),this.set("y2",e[3]),this._setWidthHeight(t)},_setWidthHeight:function(e){e||(e={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in e?e.left:this._getLeftToOriginX(),this.top="top"in e?e.top:this._getTopToOriginY()},_set:function(e,t){return this.callSuper("_set",e,t),void 0!==n[e]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(e){e.beginPath();var t=this.calcLinePoints();e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineWidth=this.strokeWidth;var i=e.strokeStyle;e.strokeStyle=this.stroke||e.fillStyle,this.stroke&&this._renderStroke(e),e.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(e){return i(this.callSuper("toObject",e),this.calcLinePoints())},_getNonTransformedDimensions:function(){var e=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(e.y-=this.strokeWidth),0===this.height&&(e.x-=this.strokeWidth)),e},calcLinePoints:function(){var e=this.x1<=this.x2?-1:1,t=this.y1<=this.y2?-1:1,i=e*this.width*.5,r=t*this.height*.5;return{x1:i,x2:e*this.width*-.5,y1:r,y2:t*this.height*-.5}},_toSVG:function(){var e=this.calcLinePoints();return["\n']}}),t.Line.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),t.Line.fromElement=function(e,r,n){n=n||{};var s=t.parseAttributes(e,t.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new t.Line(o,i(s,n)))},t.Line.fromObject=function(e,i){var n=r(e,!0);n.points=[e.x1,e.y1,e.x2,e.y2],t.Object._fromObject("Line",n,(function(e){delete e.points,i&&i(e)}),"points")})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.degreesToRadians;t.Circle?t.warn("fabric.Circle is already defined."):(t.Circle=t.util.createClass(t.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:t.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(e,t){return this.callSuper("_set",e,t),"radius"===e&&this.setRadius(t),this},toObject:function(e){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(e))},_toSVG:function(){var e,r=(this.endAngle-this.startAngle)%360;if(0===r)e=["\n'];else{var n=i(this.startAngle),s=i(this.endAngle),o=this.radius;e=['180?"1":"0")+" 1"," "+t.util.cos(s)*o+" "+t.util.sin(s)*o,'" ',"COMMON_PARTS"," />\n"]}return e},_render:function(e){e.beginPath(),e.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(e)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(e){return this.radius=e,this.set("width",2*e).set("height",2*e)}}),t.Circle.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),t.Circle.fromElement=function(e,i){var r,n=t.parseAttributes(e,t.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=n)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");n.left=(n.left||0)-n.radius,n.top=(n.top||0)-n.radius,i(new t.Circle(n))},t.Circle.fromObject=function(e,i){t.Object._fromObject("Circle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={});t.Triangle?t.warn("fabric.Triangle is already defined"):(t.Triangle=t.util.createClass(t.Object,{type:"triangle",width:100,height:100,_render:function(e){var t=this.width/2,i=this.height/2;e.beginPath(),e.moveTo(-t,i),e.lineTo(0,-i),e.lineTo(t,i),e.closePath(),this._renderPaintInOrder(e)},_toSVG:function(){var e=this.width/2,t=this.height/2;return["']}}),t.Triangle.fromObject=function(e,i){return t.Object._fromObject("Triangle",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=2*Math.PI;t.Ellipse?t.warn("fabric.Ellipse is already defined."):(t.Ellipse=t.util.createClass(t.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this.set("rx",e&&e.rx||0),this.set("ry",e&&e.ry||0)},_set:function(e,t){switch(this.callSuper("_set",e,t),e){case"rx":this.rx=t,this.set("width",2*t);break;case"ry":this.ry=t,this.set("height",2*t)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']},_render:function(e){e.beginPath(),e.save(),e.transform(1,0,0,this.ry/this.rx,0,0),e.arc(0,0,this.rx,0,i,!1),e.restore(),this._renderPaintInOrder(e)}}),t.Ellipse.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),t.Ellipse.fromElement=function(e,i){var r=t.parseAttributes(e,t.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new t.Ellipse(r))},t.Ellipse.fromObject=function(e,i){t.Object._fromObject("Ellipse",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend;t.Rect?t.warn("fabric.Rect is already defined"):(t.Rect=t.util.createClass(t.Object,{stateProperties:t.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:t.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(e){this.callSuper("initialize",e),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(e){var t=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==t||0!==i,h=.4477152502;e.beginPath(),e.moveTo(s+t,o),e.lineTo(s+r-t,o),a&&e.bezierCurveTo(s+r-h*t,o,s+r,o+h*i,s+r,o+i),e.lineTo(s+r,o+n-i),a&&e.bezierCurveTo(s+r,o+n-h*i,s+r-h*t,o+n,s+r-t,o+n),e.lineTo(s+t,o+n),a&&e.bezierCurveTo(s+h*t,o+n,s,o+n-h*i,s,o+n-i),e.lineTo(s,o+i),a&&e.bezierCurveTo(s,o+h*i,s+h*t,o,s+t,o),e.closePath(),this._renderPaintInOrder(e)},toObject:function(e){return this.callSuper("toObject",["rx","ry"].concat(e))},_toSVG:function(){return["\n']}}),t.Rect.ATTRIBUTE_NAMES=t.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),t.Rect.fromElement=function(e,r,n){if(!e)return r(null);n=n||{};var s=t.parseAttributes(e,t.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var o=new t.Rect(i(n?t.util.object.clone(n):{},s));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},t.Rect.fromObject=function(e,i){return t.Object._fromObject("Rect",e,i)})}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.util.object.extend,r=t.util.array.min,n=t.util.array.max,s=t.util.toFixed,o=t.util.projectStrokeOnPoints;t.Polyline?t.warn("fabric.Polyline is already defined"):(t.Polyline=t.util.createClass(t.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:t.Object.prototype.cacheProperties.concat("points"),initialize:function(e,t){t=t||{},this.points=e||[],this.callSuper("initialize",t),this._setPositionDimensions(t)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(e){var t,i=this._calcDimensions(e),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,e.fromSVG||(t=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===e.left&&(this.left=e.fromSVG?i.left:t.x),void 0===e.top&&(this.top=e.fromSVG?i.top:t.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var e=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,t=r(e,"x")||0,i=r(e,"y")||0;return{left:t,top:i,width:(n(e,"x")||0)-t,height:(n(e,"y")||0)-i}},toObject:function(e){return i(this.callSuper("toObject",e),{points:this.points.concat()})},_toSVG:function(){for(var e=[],i=this.pathOffset.x,r=this.pathOffset.y,n=t.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(e){var t,i=this.points.length,r=this.pathOffset.x,n=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;e.beginPath(),e.moveTo(this.points[0].x-r,this.points[0].y-n);for(var s=0;s"},toObject:function(e){return n(this.callSuper("toObject",e),{path:this.path.map((function(e){return e.slice()}))})},toDatalessObject:function(e){var t=this.toObject(["sourcePath"].concat(e));return t.sourcePath&&delete t.path,t},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var e=t.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,e)+", "+o(-this.pathOffset.y,e)+")"},toClipPathSVG:function(e){var t=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},toSVG:function(e){var t=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var e,n,s=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(e){var i=!!this.group;return this._restoreObjectsState(),t.util.resetObjectTransform(this),e&&(i&&t.util.removeTransformFromObject(e,this.group.calcTransformMatrix()),this._objects.push(e),e.group=this,e._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(e){return this._restoreObjectsState(),t.util.resetObjectTransform(this),this.remove(e),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(e){this.dirty=!0,e.group=this,e._set("canvas",this.canvas)},_onObjectRemoved:function(e){this.dirty=!0,delete e.group},_set:function(e,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(e,i);if("canvas"===e)for(;r--;)this._objects[r]._set(e,i);t.Object.prototype._set.call(this,e,i)},toObject:function(e){var i=this.includeDefaultValues,r=this._objects.filter((function(e){return!e.excludeFromExport})).map((function(t){var r=t.includeDefaultValues;t.includeDefaultValues=i;var n=t.toObject(e);return t.includeDefaultValues=r,n})),n=t.Object.prototype.toObject.call(this,e);return n.objects=r,n},toDatalessObject:function(e){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(t){var i=t.includeDefaultValues;t.includeDefaultValues=n;var r=t.toDatalessObject(e);return t.includeDefaultValues=i,r}))}var s=t.Object.prototype.toDatalessObject.call(this,e);return s.objects=i,s},render:function(e){this._transformDone=!0,this.callSuper("render",e),this._transformDone=!1},shouldCache:function(){var e=t.Object.prototype.shouldCache.call(this);if(e)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),t},getSvgStyles:function(){var e=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",t=this.visible?"":" visibility: hidden;";return[e,this.getSvgFilter(),t].join("")},toClipPathSVG:function(e){for(var t=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(e,t,i){e.save(),e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",e,t),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,n=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,e=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?t.concat(e,i):t.concat(i,e)},getSrc:function(e){var t=e?this._element:this._originalElement;return t?t.toDataURL?t.toDataURL():this.srcFromAttribute?t.getAttribute("src"):t.src:this.src||""},setSrc:function(e,t,i){return x.util.loadImage(e,(function(e,r){this.setElement(e,i),this._setWidthHeight(),t&&t(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var e=this.resizeFilter,t=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!e||r>t&&n>t)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=n);x.filterBackend||(x.filterBackend=x.initFilterBackend());var o=x.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=s.width,l=s.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=n,x.filterBackend.applyFilters([e],s,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(e){if(e=(e=e||this.filters||[]).filter((function(e){return e&&!e.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===e.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var t=this._originalElement,i=t.naturalWidth||t.width,r=t.naturalHeight||t.height;if(this._element===this._originalElement){var n=x.util.createCanvasElement();n.width=i,n.height=r,this._element=n,this._filteredEl=n}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return x.filterBackend||(x.filterBackend=x.initFilterBackend()),x.filterBackend.applyFilters(e,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(e){x.util.setImageSmoothing(e,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(e),this._renderPaintInOrder(e)},drawCacheOnCanvas:function(e){x.util.setImageSmoothing(e,this.imageSmoothing),x.Object.prototype.drawCacheOnCanvas.call(this,e)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(e){var t=this._element;if(t){var i=this._filterScalingX,r=this._filterScalingY,n=this.width,s=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=t.naturalWidth||t.width,u=t.naturalHeight||t.height,d=h*i,f=l*r,g=o(n*i,c-d),_=o(s*r,u-f),p=-n/2,m=-s/2,v=o(n,c/i-h),y=o(s,u/r-l);t&&e.drawImage(t,d,f,g,_,p,m,v,y)}},_needsResize:function(){var e=this.getTotalObjectScaling();return e.scaleX!==this._lastScaleX||e.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(e,t){this.setElement(x.util.getById(e),t),x.util.addClass(this.getElement(),x.Image.CSS_CANVAS)},_initConfig:function(e){e||(e={}),this.setOptions(e),this._setWidthHeight(e)},_initFilters:function(e,t){e&&e.length?x.util.enlivenObjects(e,(function(e){t&&t(e)}),"fabric.Image.filters"):t&&t()},_setWidthHeight:function(e){e||(e={});var t=this.getElement();this.width=e.width||t.naturalWidth||t.width||0,this.height=e.height||t.naturalHeight||t.height||0},parsePreserveAspectRatioAttribute:function(){var e,t=x.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,n=1,s=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!t||"none"===t.alignX&&"none"===t.alignY?(n=c/i,s=u/r):("meet"===t.meetOrSlice&&(e=(c-i*(n=s=x.util.findScaleToFit(this._element,d)))/2,"Min"===t.alignX&&(o=-e),"Max"===t.alignX&&(o=e),e=(u-r*s)/2,"Min"===t.alignY&&(a=-e),"Max"===t.alignY&&(a=e)),"slice"===t.meetOrSlice&&(e=i-c/(n=s=x.util.findScaleToCover(this._element,d)),"Mid"===t.alignX&&(h=e/2),"Max"===t.alignX&&(h=e),e=r-u/s,"Mid"===t.alignY&&(l=e/2),"Max"===t.alignY&&(l=e),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),x.Image.CSS_CANVAS="canvas-img",x.Image.prototype.getSvgSrc=x.Image.prototype.getSrc,x.Image.fromObject=function(e,t){var i=x.util.object.clone(e);x.util.loadImage(i.src,(function(e,r){r?t&&t(null,!0):x.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],x.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],x.util.enlivenObjectEnlivables(i,i,(function(){var r=new x.Image(e,i);t(r,!1)}))}))}))}),null,i.crossOrigin)},x.Image.fromURL=function(e,t,i){x.util.loadImage(e,(function(e,r){t&&t(new x.Image(e,i),r)}),null,i&&i.crossOrigin)},x.Image.ATTRIBUTE_NAMES=x.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),x.Image.fromElement=function(e,i,r){var n=x.parseAttributes(e,x.Image.ATTRIBUTE_NAMES);x.Image.fromURL(n["xlink:href"],i,t(r?x.util.object.clone(r):{},n))})}(t),x.util.object.extend(x.Object.prototype,{_getAngleValueForStraighten:function(){var e=this.angle%360;return e>0?90*Math.round((e-1)/90):90*Math.round(e/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(e){var t=function(){},i=(e=e||{}).onComplete||t,r=e.onChange||t,n=this;return x.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(e){n.rotate(e),r()},onComplete:function(){n.setCoords(),i()}})}}),x.util.object.extend(x.StaticCanvas.prototype,{straightenObject:function(e){return e.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(e){return e.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function e(e,t){var i="precision "+t+" float;\nvoid main(){}",r=e.createShader(e.FRAGMENT_SHADER);return e.shaderSource(r,i),e.compileShader(r),!!e.getShaderParameter(r,e.COMPILE_STATUS)}function t(e){e&&e.tileSize&&(this.tileSize=e.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}x.isWebglSupported=function(t){if(x.isLikelyNode)return!1;t=t||x.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),n=!1;if(r){x.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=x.maxTextureSize>=t;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(e(r,s[o])){x.webGlPrecision=s[o];break}}return this.isSupported=n,n},x.WebglFilterBackend=t,t.prototype={tileSize:2048,resources:{},setupGLContext:function(e,t){this.dispose(),this.createWebGLCanvas(e,t),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(e,t)},chooseFastestCopyGLTo2DMethod:function(e,t){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(e){i=!1}var n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=x.util.createCanvasElement(),a=new ArrayBuffer(e*t*4);if(x.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=A);var h,l,c={imageBuffer:a,destinationWidth:e,destinationHeight:t,targetCanvas:o};o.width=e,o.height=t,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),A.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=A):this.copyGLTo2D=I}},createWebGLCanvas:function(e,t){var i=x.util.createCanvasElement();i.width=e,i.height=t;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",r);n||(n=i.getContext("experimental-webgl",r)),n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)},applyFilters:function(e,t,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,t));var h={originalWidth:t.width||t.originalWidth,originalHeight:t.height||t.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&t),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&t),passes:e.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),e.forEach((function(e){e&&e.applyTo(h)})),function(e){var t=e.targetCanvas,i=t.width,r=t.height,n=e.destinationWidth,s=e.destinationHeight;i===n&&r===s||(t.width=n,t.height=s)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),n.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(e,t,i,r){var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),r?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,i,0,e.RGBA,e.UNSIGNED_BYTE,null),n},getCachedTexture:function(e,t){if(this.textureCache[e])return this.textureCache[e];var i=this.createTexture(this.gl,t.width,t.height,t);return this.textureCache[e]=i,i},evictCachesForKey:function(e){this.textureCache[e]&&(this.gl.deleteTexture(this.textureCache[e]),delete this.textureCache[e])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var e=this.gl,t={renderer:"",vendor:""};if(!e)return t;var i=e.getExtension("WEBGL_debug_renderer_info");if(i){var r=e.getParameter(i.UNMASKED_RENDERER_WEBGL),n=e.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(t.renderer=r.toLowerCase()),n&&(t.vendor=n.toLowerCase())}return this.gpuInfo=t,t}}}(),function(){var e=function(){};function t(){}x.Canvas2dFilterBackend=t,t.prototype={evictCachesForKey:e,dispose:e,clearWebGLCaches:e,resources:{},applyFilters:function(e,t,i,r,n){var s=n.getContext("2d");s.drawImage(t,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:t,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return e.forEach((function(e){e.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(n.width=o.imageData.width,n.height=o.imageData.height),s.putImageData(o.imageData,0,0),o}}}(),x.Image=x.Image||{},x.Image.filters=x.Image.filters||{},x.Image.filters.BaseFilter=x.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(e){e&&this.setOptions(e)},setOptions:function(e){for(var t in e)this[t]=e[t]},createProgram:function(e,t,i){t=t||this.fragmentSource,i=i||this.vertexSource,"highp"!==x.webGlPrecision&&(t=t.replace(/precision highp float/g,"precision "+x.webGlPrecision+" float"));var r=e.createShader(e.VERTEX_SHADER);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+e.getShaderInfoLog(r));var n=e.createShader(e.FRAGMENT_SHADER);if(e.shaderSource(n,t),e.compileShader(n),!e.getShaderParameter(n,e.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+e.getShaderInfoLog(n));var s=e.createProgram();if(e.attachShader(s,r),e.attachShader(s,n),e.linkProgram(s),!e.getProgramParameter(s,e.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+e.getProgramInfoLog(s));var o=this.getAttributeLocations(e,s),a=this.getUniformLocations(e,s)||{};return a.uStepW=e.getUniformLocation(s,"uStepW"),a.uStepH=e.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(e,t){return{aPosition:e.getAttribLocation(t,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(e,t,i){var r=t.aPosition,n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.bufferData(e.ARRAY_BUFFER,i,e.STATIC_DRAW)},_setupFrameBuffer:function(e){var t,i,r=e.context;e.passes>1?(t=e.destinationWidth,i=e.destinationHeight,e.sourceWidth===t&&e.sourceHeight===i||(r.deleteTexture(e.targetTexture),e.targetTexture=e.filterBackend.createTexture(r,t,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(e){e.passes--,e.pass++;var t=e.targetTexture;e.targetTexture=e.sourceTexture,e.sourceTexture=t},isNeutralState:function(){var e=this.mainParameter,t=x.Image.filters[this.type].prototype;if(e){if(Array.isArray(t[e])){for(var i=t[e].length;i--;)if(this[e][i]!==t[e][i])return!1;return!0}return t[e]===this[e]}return!1},applyTo:function(e){e.webgl?(this._setupFrameBuffer(e),this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)},retrieveShader:function(e){return e.programCache.hasOwnProperty(this.type)||(e.programCache[this.type]=this.createProgram(e.context)),e.programCache[this.type]},applyToWebGL:function(e){var t=e.context,i=this.retrieveShader(e);0===e.pass&&e.originalTexture?t.bindTexture(t.TEXTURE_2D,e.originalTexture):t.bindTexture(t.TEXTURE_2D,e.sourceTexture),t.useProgram(i.program),this.sendAttributeData(t,i.attributeLocations,e.aPosition),t.uniform1f(i.uniformLocations.uStepW,1/e.sourceWidth),t.uniform1f(i.uniformLocations.uStepH,1/e.sourceHeight),this.sendUniformData(t,i.uniformLocations),t.viewport(0,0,e.destinationWidth,e.destinationHeight),t.drawArrays(t.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(e,t,i){e.activeTexture(i),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE0)},unbindAdditionalTexture:function(e,t){e.activeTexture(t),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(e){this[this.mainParameter]=e},sendUniformData:function(){},createHelpLayer:function(e){if(!e.helpLayer){var t=document.createElement("canvas");t.width=e.sourceWidth,t.height=e.sourceHeight,e.helpLayer=t}},toObject:function(){var e={type:this.type},t=this.mainParameter;return t&&(e[t]=this[t]),e},toJSON:function(){return this.toObject()}}),x.Image.filters.BaseFilter.fromObject=function(e,t){var i=new x.Image.filters[e.type](e);return t&&t(i),i},function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(e){this.callSuper("initialize",e),this.matrix=this.matrix.slice(0)},applyTo2d:function(e){var t,i,r,n,s,o=e.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(s=0;s=S||o<0||o>=y||(h=4*(a*y+o),l=p[f*m+d],t+=_[h]*l,i+=_[h+1]*l,r+=_[h+2]*l,C||(n+=_[h+3]*l));b[s]=t,b[s+1]=i,b[s+2]=r,b[s+3]=C?_[s+3]:n}e.imageData=w},getUniformLocations:function(e,t){return{uMatrix:e.getUniformLocation(t,"uMatrix"),uOpaque:e.getUniformLocation(t,"uOpaque"),uHalfSize:e.getUniformLocation(t,"uHalfSize"),uSize:e.getUniformLocation(t,"uSize")}},sendUniformData:function(e,t){e.uniform1fv(t.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),t.Image.filters.Convolute.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(e){var t,i,r=e.imageData.data,n=r.length,s=this.mode;for(t=0;tl[0]&&n>l[1]&&s>l[2]&&r 0.0) {\n"+this.fragmentSource[e]+"}\n}"},retrieveShader:function(e){var t,i=this.type+"_"+this.mode;return e.programCache.hasOwnProperty(i)||(t=this.buildSource(this.mode),e.programCache[i]=this.createProgram(e.context,t)),e.programCache[i]},applyTo2d:function(e){var i,r,n,s,o,a,h,l=e.imageData.data,c=l.length,u=1-this.alpha;i=(h=new t.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,n=h[2]*this.alpha;for(var d=0;d=e||t<=-e)return 0;if(t<1.1920929e-7&&t>-1.1920929e-7)return 1;var i=(t*=Math.PI)/e;return a(t)/t*a(i)/i}},applyTo2d:function(e){var t=e.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var n,s=t.width,a=t.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(e,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(e,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(e,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(e,s,a,h,l)),e.imageData=n},sliceByTwo:function(e,i,n,s,o){var a,h,l=e.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*c,_=t.filterBackend.resources,p=0,m=0,v=i,y=0;for(_.sliceByTwo||(_.sliceByTwo=document.createElement("canvas")),((a=_.sliceByTwo).width<1.5*i||a.height=t)){M=r(1e3*s(x-w.x)),S[M]||(S[M]={});for(var F=b.y-y;F<=b.y+y;F++)F<0||F>=o||(L=r(1e3*s(F-w.y)),S[M][L]||(S[M][L]=f(n(i(M*p,2)+i(L*m,2))/1e3)),(T=S[M][L])>0&&(A+=T,E+=T*c[I=4*(F*t+x)],O+=T*c[I+1],D+=T*c[I+2],R+=T*c[I+3]))}d[I=4*(C*a+h)]=E/A,d[I+1]=O/A,d[I+2]=D/A,d[I+3]=R/A}return++h1&&L<-1||(y=2*L*L*L-3*L*L+1)>0&&(T+=y*f[3+(M=4*(R+A*t))],w+=y,f[M+3]<255&&(y=y*f[M+3]/250),b+=y*f[M],C+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=b/S,_[v+1]=C/S,_[v+2]=x/S,_[v+3]=T/w}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),t.Image.filters.Resize.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(e){if(0!==this.contrast){var t,i=e.imageData.data,r=i.length,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));for(t=0;t1&&(t=1/this.aspectRatio):this.aspectRatio<1&&(t=this.aspectRatio),e=t*this.blur*.12,this.horizontal?i[0]=e:i[1]=e,i}}),i.Blur.fromObject=t.Image.filters.BaseFilter.fromObject}(t),function(e){var t=e.fabric||(e.fabric={}),i=t.Image.filters,r=t.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(e){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,e)},applyTo2d:function(e){var t,i=e.imageData.data,r=this.gamma,n=i.length,s=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),t=0,n=256;t'},_getCacheCanvasDimensions:function(){var e=this.callSuper("_getCacheCanvasDimensions"),t=this.fontSize;return e.width+=t*e.zoomX,e.height+=t*e.zoomY,e},_render:function(e){var t=this.path;t&&!t.isNotVisible()&&t._render(e),this._setTextStyles(e),this._renderTextLinesBackground(e),this._renderTextDecoration(e,"underline"),this._renderText(e),this._renderTextDecoration(e,"overline"),this._renderTextDecoration(e,"linethrough")},_renderText:function(e){"stroke"===this.paintFirst?(this._renderTextStroke(e),this._renderTextFill(e)):(this._renderTextFill(e),this._renderTextStroke(e))},_setTextStyles:function(e,t,i){if(e.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":e.textBaseline="middle";break;case"ascender":e.textBaseline="top";break;case"descender":e.textBaseline="bottom"}e.font=this._getFontDeclaration(t,i)},calcTextWidth:function(){for(var e=this.getLineWidth(0),t=1,i=this._textLines.length;te&&(e=r)}return e},_renderTextLine:function(e,t,i,r,n,s){this._renderChars(e,t,i,r,n,s)},_renderTextLinesBackground:function(e){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var t,i,r,n,s,o,a,h=e.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,_=this._textLines.length;g<_;g++)if(t=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){r=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,n=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,m=r.length;p=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,s,o),u+=s.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(e,i,r){var n=e+i.kernedWidth/2,s=this.path,o=t.util.getPointOnPath(s.path,n,s.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(e,t,i,r,n){var s,o=this.getCompleteStyleDeclaration(t,i),a=r?this.getCompleteStyleDeclaration(t,i-1):{},h=this._measureChar(e,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),l+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[t][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(e){if(this.__lineHeights[e])return this.__lineHeights[e];for(var t=this._textLines[e],i=this.getHeightOfChar(e,0),r=1,n=t.length;r0){var A=v+s+u;"rtl"===this.direction&&(A=this.width-A-d),l&&m&&(e.fillStyle=m,e.fillRect(A,c+b*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,m=p,r=n,o=a}else d+=f.kernedWidth;A=v+s+u,"rtl"===this.direction&&(A=this.width-A-d),e.fillStyle=p,g&&p&&e.fillRect(A,c+b*r+o,d-w,this.fontSize/15),y+=i}else y+=i;this._removeShadow(e)}},_getFontDeclaration:function(e,i){var r=e||this,n=this.fontFamily,s=t.Text.genericFonts.indexOf(n.toLowerCase())>-1,o=void 0===n||n.indexOf("'")>-1||n.indexOf(",")>-1||n.indexOf('"')>-1||s?r.fontFamily:'"'+r.fontFamily+'"';return[t.isLikelyNode?r.fontWeight:r.fontStyle,t.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(e){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",e)))},_splitTextIntoLines:function(e){for(var i=e.split(this._reNewline),r=new Array(i.length),n=["\n"],s=[],o=0;o-1&&(e.underline=!0),e.textDecoration.indexOf("line-through")>-1&&(e.linethrough=!0),e.textDecoration.indexOf("overline")>-1&&(e.overline=!0),delete e.textDecoration)}x.IText=x.util.createClass(x.Text,x.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(e,t){this.callSuper("initialize",e,t),this.initBehavior()},setSelectionStart:function(e){e=Math.max(e,0),this._updateAndFire("selectionStart",e)},setSelectionEnd:function(e){e=Math.min(e,this.text.length),this._updateAndFire("selectionEnd",e)},_updateAndFire:function(e,t){this[e]!==t&&(this._fireSelectionChanged(),this[e]=t),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(e){this.clearContextTop(),this.callSuper("render",e),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(e){this.callSuper("_render",e)},clearContextTop:function(e){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this.canvas.contextTop,i=this.canvas.viewportTransform;t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(t),this._clearTextArea(t),e||t.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this._getCursorBoundaries(),t=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(e,t):this.renderSelection(e,t),t.restore()}},_clearTextArea:function(e){var t=this.width+4,i=this.height+4;e.clearRect(-t/2,-i/2,t,i)},_getCursorBoundaries:function(e){void 0===e&&(e=this.selectionStart);var t=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(e);return{left:t,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(e){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var t,i,r,n,s=0,o=0,a=this.get2DCursorLocation(e);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(n.left*=-1),this.cursorOffsetCache=n,this.cursorOffsetCache},renderCursor:function(e,t){var i=this.get2DCursorLocation(),r=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(r,n,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=e.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(e,t),t.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),t.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,t.fillRect(e.left+e.leftOffset-a/2,h+e.top+l,a,s)},renderSelection:function(e,t){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,n=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=s.lineIndex,h=o.lineIndex,l=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=e.left+f+_,y=p-_,S=g,w=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,w=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+w,y,S),e.topOffset+=d}},getCurrentCharFontSize:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fontSize")},getCurrentCharColor:function(){var e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,"fill")},_getCurrentCharIndex:function(){var e=this.get2DCursorLocation(this.selectionStart,!0),t=e.charIndex>0?e.charIndex-1:0;return{l:e.lineIndex,c:t}}}),x.IText.fromObject=function(t,i){if(e(t),t.styles)for(var r in t.styles)for(var n in t.styles[r])e(t.styles[r][n]);x.Object._fromObject("IText",t,i,"text")}}(),C=x.util.object.clone,x.util.object.extend(x.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var e=this;this.on("added",(function(){var t=e.canvas;t&&(t._hasITextHandlers||(t._hasITextHandlers=!0,e._initCanvasHandlers(t)),t._iTextInstances=t._iTextInstances||[],t._iTextInstances.push(e))}))},initRemovedHandler:function(){var e=this;this.on("removed",(function(){var t=e.canvas;t&&(t._iTextInstances=t._iTextInstances||[],x.util.removeFromArray(t._iTextInstances,e),0===t._iTextInstances.length&&(t._hasITextHandlers=!1,e._removeCanvasHandlers(t)))}))},_initCanvasHandlers:function(e){e._mouseUpITextHandler=function(){e._iTextInstances&&e._iTextInstances.forEach((function(e){e.__isMousedown=!1}))},e.on("mouse:up",e._mouseUpITextHandler)},_removeCanvasHandlers:function(e){e.off("mouse:up",e._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(e,t,i,r){var n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},e.animate("_currentCursorOpacity",t,{duration:i,onComplete:function(){n.isAborted||e[r]()},onChange:function(){e.canvas&&e.selectionStart===e.selectionEnd&&e.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_onTickComplete:function(){var e=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){e._currentTickCompleteState=e._animateCursor(e,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(e){var t=this,i=e?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){t._tick()}),i)},abortCursorAnimation:function(){var e=this._currentTickState||this._currentTickCompleteState,t=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,e&&t&&t.clearContext(t.contextTop||t.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(e){var t=0,i=e-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i--;for(;/\S/.test(this._text[i])&&i>-1;)t++,i--;return e-t},findWordBoundaryRight:function(e){var t=0,i=e;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)t++,i++;for(;/\S/.test(this._text[i])&&i-1;)t++,i--;return e-t},findLineBoundaryRight:function(e){for(var t=0,i=e;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=t):(this.selectionStart=t,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(e,t,i){var r=i.slice(0,e),n=x.util.string.graphemeSplit(r).length;if(e===t)return{selectionStart:n,selectionEnd:n};var s=i.slice(e,t);return{selectionStart:n,selectionEnd:n+x.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(e,t,i){var r=i.slice(0,e).join("").length;return e===t?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(e,t).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var e=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=e.selectionStart,this.hiddenTextarea.selectionEnd=e.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var e=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var e=this._calcTextareaPosition();this.hiddenTextarea.style.left=e.left,this.hiddenTextarea.style.top=e.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var e=this.inCompositionMode?this.compositionStart:this.selectionStart,t=this._getCursorBoundaries(e),i=this.get2DCursorLocation(e),r=i.lineIndex,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=t.leftOffset,a=this.calcTransformMatrix(),h={x:t.left+o,y:t.top+t.topOffset+s},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-s,g=d-s,_=c.clientWidth/u,p=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=_,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var e=this._textBeforeEdit!==this.text,t=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),e&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),e&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var e in this.styles)this._textLines[e]||delete this.styles[e]},removeStyleFromTo:function(e,t){var i,r,n=this.get2DCursorLocation(e,!0),s=this.get2DCursorLocation(t,!0),o=n.lineIndex,a=n.charIndex,h=s.lineIndex,l=s.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(e,t){var i=C(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>e&&(this.styles[n+t]=i[n],i[n-t]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(e,t,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[e].length===t;for(var h in i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&(n=this.styles[e][0===t?t:t-1]),this.styles[e]){var l=parseInt(h,10);l>=t&&(o=!0,s[l-t]=this.styles[e][h],a&&0===t||delete this.styles[e][h])}var c=!1;for(o&&!a&&(this.styles[e+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[e+i]={0:C(r[i-1])}:n?this.styles[e+i]={0:C(n)}:delete this.styles[e+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(e,t,i,r){this.styles||(this.styles={});var n=this.styles[e],s=n?C(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=t&&(n[a+i]=s[a],s[a-i]||delete n[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[e]||(this.styles[e]={}),this.styles[e][t+i]=C(r[i]));else if(n)for(var h=n[t?t-1:1];h&&i--;)this.styles[e][t+i]=C(h)},insertNewStyleBlock:function(e,t,i){for(var r=this.get2DCursorLocation(t,!0),n=[0],s=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),s&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+n[0],s),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,n[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,n[o],i)},setSelectionStartEndWithShift:function(e,t,i){i<=e?(t===e?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=e),this.selectionStart=i):i>e&&ie?this.selectionStart=e:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>e?this.selectionEnd=e:this.selectionEnd<0&&(this.selectionEnd=0)}}),x.util.object.extend(x.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(e){if(this.canvas){this.__newClickTime=+new Date;var t=e.pointer;this.isTripleClick(t)&&(this.fire("tripleclick",e),this._stopEvent(e.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=t,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(e){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===e.x&&this.__lastPointer.y===e.y},_stopEvent:function(e){e.preventDefault&&e.preventDefault(),e.stopPropagation&&e.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(e){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(e.e))},tripleClickHandler:function(e){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(e.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(e.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(e){!this.canvas||!this.editable||e.e.button&&1!==e.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(e){if(this.__isMousedown=!1,!(!this.editable||this.group||e.transform&&e.transform.actionPerformed||e.e.button&&1!==e.e.button)){if(this.canvas){var t=this.canvas._activeObject;if(t&&t!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(e.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(e){var t=this.getSelectionStartFromPointer(e),i=this.selectionStart,r=this.selectionEnd;e.shiftKey?this.setSelectionStartEndWithShift(i,r,t):(this.selectionStart=t,this.selectionEnd=t),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(e){for(var t,i=this.getLocalPointer(e),r=0,n=0,s=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));n=this._getLineLeftOffset(a)*this.scaleX,t=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=t.length;cs||o<0?0:1);return this.flipX&&(a=n-a),a>this._text.length&&(a=this._text.length),a}}),x.util.object.extend(x.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=x.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var e=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+e.top+"; left: "+e.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+e.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):x.document.body.appendChild(this.hiddenTextarea),x.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),x.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),x.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),x.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(x.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(e){if(this.isEditing){var t="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(e.keyCode in t)this[t[e.keyCode]](e);else{if(!(e.keyCode in this.ctrlKeysMapDown)||!e.ctrlKey&&!e.metaKey)return;this[this.ctrlKeysMapDown[e.keyCode]](e)}e.stopImmediatePropagation(),e.preventDefault(),e.keyCode>=33&&e.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(e){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:e.keyCode in this.ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)&&(this[this.ctrlKeysMapUp[e.keyCode]](e),e.stopImmediatePropagation(),e.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(e){var t=this.fromPaste;if(this.fromPaste=!1,e&&e.stopPropagation(),this.isEditing){var i,r,n,s,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[e][t-1]).left+i.width),r},getDownCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||e.metaKey||34===e.keyCode)return this._text.length-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n+1,o);return this._textLines[n].slice(s).length+a+1+this.missingNewlineOffset(n)},_getSelectionForOffset:function(e,t){return e.shiftKey&&this.selectionStart!==this.selectionEnd&&t?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(e,t){var i=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(i),n=r.lineIndex;if(0===n||e.metaKey||33===e.keyCode)return-i;var s=r.charIndex,o=this._getWidthBeforeCursor(n,s),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,s),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)},_getIndexOnLine:function(e,t){for(var i,r,n=this._textLines[e],s=this._getLineLeftOffset(e),o=0,a=0,h=n.length;at){r=!0;var l=s-i,c=s,u=Math.abs(l-t);o=Math.abs(c-t)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",e)},moveCursorUp:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",e)},_moveCursorUpOrDown:function(e,t){var i=this["get"+e+"CursorOffset"](t,"right"===this._selectionDirection);t.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(e){var t="left"===this._selectionDirection?this.selectionStart+e:this.selectionEnd+e;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,t),0!==e},moveCursorWithoutShift:function(e){return e<0?(this.selectionStart+=e,this.selectionEnd=this.selectionStart):(this.selectionEnd+=e,this.selectionStart=this.selectionEnd),0!==e},moveCursorLeft:function(e){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",e)},_move:function(e,t,i){var r;if(e.altKey)r=this["findWordBoundary"+i](this[t]);else{if(!e.metaKey&&35!==e.keyCode&&36!==e.keyCode)return this[t]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[t])}if(void 0!==typeof r&&this[t]!==r)return this[t]=r,!0},_moveLeft:function(e,t){return this._move(e,t,"Left")},_moveRight:function(e,t){return this._move(e,t,"Right")},moveCursorLeftWithoutShift:function(e){var t=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(t=this._moveLeft(e,"selectionStart")),this.selectionEnd=this.selectionStart,t},moveCursorLeftWithShift:function(e){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(e,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(e,"selectionStart")):void 0},moveCursorRight:function(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",e)},_moveCursorLeftOrRight:function(e,t){var i="moveCursor"+e+"With";this._currentCursorOpacity=1,t.shiftKey?i+="Shift":i+="outShift",this[i](t)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(e){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(e,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(e,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(e){var t=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(t=this._moveRight(e,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,t},removeChars:function(e,t){void 0===t&&(t=e+1),this.removeStyleFromTo(e,t),this._text.splice(e,t-e),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(e,t,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var n=x.util.string.graphemeSplit(e);this.insertNewStyleBlock(n,i,t),this._text=[].concat(this._text.slice(0,i),n,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var e=x.util.toFixed,t=/ +/g;x.util.object.extend(x.Text.prototype,{_toSVG:function(){var e=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(e.textTop,e.textLeft);return this._wrapSVGTextAndBg(t)},toSVG:function(e){return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(e){var t=this.getSvgTextDecoration(this);return[e.textBgRects.join(""),'\t\t",e.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(e,t){var i,r=[],n=[],s=e;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",x.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(e,t,i,r){var n,s,o,a,h,l=this.getHeightOfLine(t),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[t];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)h=g===_||this.charSpacing,u+=f[g],o=this.__charBounds[t][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(n=n||this.getCompleteStyleDeclaration(t,g),s=this.getCompleteStyleDeclaration(t,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(t,g)||{},e.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(t,i,r,n,s,o){var a=x.Object.NUM_FRACTION_DIGITS;t.push("\t\t\n')},_setSVGTextLineBg:function(e,t,i,r){for(var n,s,o=this._textLines[t],a=this.getHeightOfLine(t)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(e){for(var t=0,i=0,r=0,n={},s=0;s0?(i=0,r++,t++):!this.splitByGrapheme&&this._reSpaceAndTab.test(e.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:t,offset:i},r+=e.graphemeLines[s].length,i+=e.graphemeLines[s].length;return n},styleHas:function(e,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return t.Text.prototype.styleHas.call(this,e,i)},isEmptyStyles:function(e){if(!this.styles)return!0;var t,i,r=0,n=!1,s=this._styleMap[e],o=this._styleMap[e+1];for(var a in s&&(e=s.line,r=s.offset),o&&(n=o.line===e,t=o.offset),i=void 0===e?this.styles:{line:this.styles[e]})for(var h in i[a])if(h>=r&&(!n||hr&&!p?(a.push(h),h=[],s=f,p=!0):s+=m,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(h),_+n>this.dynamicMinWidth&&(this.dynamicMinWidth=_-m+n),a},isEndOfWrapping:function(e){return!this._styleMap[e+1]||this._styleMap[e+1].line!==this._styleMap[e].line},missingNewlineOffset:function(e){return this.splitByGrapheme?this.isEndOfWrapping(e)?1:0:1},_splitTextIntoLines:function(e){for(var i=t.Text.prototype._splitTextIntoLines.call(this,e),r=this._wrapText(i.lines,this.width),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},P={};function k(e){var t=P[e];if(void 0!==t)return t.exports;var i=P[e]={exports:{}};return F[e](i,i.exports,k),i.exports}k.d=(e,t)=>{for(var i in t)k.o(t,i)&&!k.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},k.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var B={};(()=>{let e;k.d(B,{R:()=>e}),e="undefined"!=typeof document&&"undefined"!=typeof window?k(653).fabric:{version:"5.2.1"}})();var N=B.R; /*! * Dynamsoft JavaScript Library * @product Dynamsoft Camera Enhancer JS Edition @@ -18,4 +18,4 @@ const e="undefined"==typeof self;let t,i,r,n,s;if("undefined"!=typeof navigator& * @version 3.3.1 (js 20230217) * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest - */const j="undefined"==typeof self;let V,U,G,W,H;if("undefined"!=typeof navigator&&(V=navigator,U=V.userAgent,G=V.platform,W=V.mediaDevices),!j){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:V.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:G,search:"Win"},Mac:{str:G},Linux:{str:G}};let i="unknownBrowser",r=0,n="unknownOS";for(let t in e){const n=e[t]||{};let s=n.str||U,o=n.search||t,a=n.verStr||U,h=n.verSearch||t;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=t;for(let e of h){let t=a.indexOf(e);if(-1!=t){r=parseFloat(a.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let r=i.str||U,s=i.search||e;if(-1!=r.indexOf(s)){n=e;break}}"Linux"==n&&-1!=U.indexOf("Windows NT")&&(n="HarmonyOS"),H={browser:i,version:r,OS:n}}j&&(H={browser:"ssr",version:0,OS:"ssr"});const Y="undefined"!=typeof WebAssembly&&U&&!(/Safari/.test(U)&&!/Chrome/.test(U)&&/\(.+\s11_2_([2-6]).*\)/.test(U)),X=!("undefined"==typeof Worker),z=!(!W||!W.getUserMedia),Z=async()=>{let e=!1;if(z)try{(await W.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===H.browser&&H.version>66||"Safari"===H.browser&&H.version>13||"OPR"===H.browser&&H.version>43||"Edge"===H.browser&&H.version;const K=(()=>{if(!j&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})();class J{constructor(e,t){this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,this._setFabricObject(e),this._mediaType=e.type,this.styleSelector="default",this.styleId=t}get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}_setFabricObject(e){this._fabricObject=e,this._fabricObject.on("selected",(()=>{this.styleSelector="selected"})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.styleSelector="selected":this.styleSelector="default","textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),e.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}_on(e,t){if(!t)return;const i=e.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${e}' does not exist.`);let n=r.get(t);n||(n=e=>{const i=e.e;if(!i)return void(t&&t.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let e,t,n,s;const o=i.target.getBoundingClientRect();e=o.left,t=o.top,n=e+window.scrollX,s=t+window.scrollY;const a=this._drawingLayer.fabricCanvas.lowerCanvasEl.width,h=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,l=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),c=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),u=l/c,d=a/h,f=this._drawingLayer._getObjectFit();let g,_,p,m,v=1;if("contain"===f)u0?i-1:r,$),actionName:"modifyPolygon",pointIndex:i}),e}),{})}_extendSet(e,t){if("vertices"===e){const e=this._fabricObject;if(e.group){const i=e.group;e.points=t.map((e=>({x:e.x-i.left-i.width/2,y:e.y-i.top-i.height/2}))),i.addWithUpdate()}else e.points=t;const i=e.points.length-1;return e.controls=e.points.reduce((function(e,t,r){return e["p"+r]=new N.Control({positionHandler:q,actionHandler:ee(r>0?r-1:i,$),actionName:"modifyPolygon",pointIndex:r}),e}),{}),e._setPositionDimensions({}),!0}}_extendGet(e){if("vertices"===e){const e=[],t=this._fabricObject;if(t.selectable&&!t.group)for(let i in t.oCoords)e.push({x:t.oCoords[i].x,y:t.oCoords[i].y});else for(let i of t.points){let r=i.x-t.pathOffset.x,n=i.y-t.pathOffset.y;const s=N.util.transformPoint({x:r,y:n},t.calcTransformMatrix());e.push({x:s.x,y:s.y})}return e}}}const ie=e=>{let t=(e=>e.split("\n").map((e=>e.split("\t"))))(e);return(e=>{for(let t=0;;t++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=e[r].length-1)continue;let n=" ".repeat(i+2-e[r][t].length);e[r][t]=e[r][t].concat(n)}}})(t),(e=>{let t="";for(let i=0;im?(g=d,_=d/p,{x:n.x*i.width,y:(n.y-(f-_)/2)*i.width}):(g=f*p,_=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>m?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},N.Canvas.prototype._onTouchStart=function(e){var t=this.findTarget(e);!this.allowTouchScrolling&&e.cancelable&&e.preventDefault&&e.preventDefault(),t&&e.cancelable&&e.preventDefault&&e.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(e)),this.__onMouseDown(e),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();N.util.addListener(N.document,"touchend",this._onTouchEnd,{passive:!1}),N.util.addListener(N.document,"touchmove",this._onMouseMove,{passive:!1}),N.util.removeListener(i,r+"down",this._onMouseDown)},N.Textbox.prototype._wrapLine=function(e,t,i,r){const n=e.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?N.util.string.graphemeSplit(e):e.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,_=0,p=0,m=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!m?(h.push(l),l=[],o=g,m=!0):o+=v,m||a||l.push(f),l=l.concat(u),_=a?0:this._measureWord([f],t,d),d++,m=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class ne{constructor(e,t,i,r){let n,s;switch(this.mapMediaType_Style=new Map,this.mode="viewer",this.onSelectionChange=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,e.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=e.getFabricCanvas():(this.fabricCanvas=new N.Canvas(e,Object.assign(r,{allowTouchScrolling:!0})),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(e){const t=e.selected,i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(e){const t=this.getActiveObjects(),i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{const t=[];for(let r of i)e.hasDrawingItem(r)&&t.push(r);t.length>0&&e.onSelectionChange&&e.onSelectionChange([],t)}),0)}})),this.fabricCanvas.on("selection:updated",(function(e){const t=e.selected,i=e.deselected,r=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of i){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of r){const r=[],n=[];for(let i of t){const t=i.getDrawingItem();t._drawingLayer===e&&r.push(t)}for(let t of i){const i=t.getDrawingItem();i._drawingLayer===e&&n.push(i)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(r,n)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",e.getFabricCanvas=()=>this.fabricCanvas),this.id=t,this._mapDrawingStyles=i,t){case 1:n=i.get(1),s=i.get(5);break;case 2:n=i.get(2),s=i.get(6);break;case 3:n=i.get(3),s=i.get(7);break;default:n=i.get(4),s=i.get(8)}for(let e of J.arrMediaTypes)this.mapMediaType_Style.set(e,{default:n,selected:s})}getId(){return this.id}_getDrawingStyle(e,t){if("number"!=typeof e)throw new Error("Invalid style id.");const i=this._mapDrawingStyles.get(e);return i?t?JSON.parse(JSON.stringify(i)):i:null}setVisible(e){if(e){for(let e of this._arrFabricObject)e.visible=!0;this._visible=!0}else{for(let e of this._arrFabricObject)e.visible=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(e){return e.styleId?e.styleId:this.mapMediaType_Style.get(e._mediaType)[e.styleSelector].styleId}_getItemCurrentStyle(e){if(e.styleId)return this._getDrawingStyle(e.styleId);return e._mapStyle.get(e.styleSelector)||null}_changeMediaTypeCurStyleInStyleSelector(e,t,i,r){let n;switch(e){case"rect":n=this.fabricCanvas.getObjects("rect");break;case"arc":n=this.fabricCanvas.getObjects("circle");break;case"polygon":n=this.fabricCanvas.getObjects("polygon");break;case"image":n=this.fabricCanvas.getObjects("image");break;case"text":n=this.fabricCanvas.getObjects("textbox");break;case"line":n=this.fabricCanvas.getObjects("line");break;case"path":n=this.fabricCanvas.getObjects("path")}for(let e of n){if(!this._arrFabricObject.includes(e))continue;const r=e.getDrawingItem();r.styleSelector===t&&this._changeItemStyle(r,i,!0)}r||this.fabricCanvas.renderAll()}_changeItemStyle(e,t,i){if(!e||!t)return;const r=e._getFabricObject();"number"==typeof e.styleId&&(t=this._getDrawingStyle(e.styleId)),r.strokeWidth=t.lineWidth,"fill"===t.paintMode?(r.fill=t.fillStyle,r.stroke=t.fillStyle):"stroke"===t.paintMode?(r.fill="transparent",r.stroke=t.strokeStyle):"strokeAndFill"===t.paintMode&&(r.fill=t.fillStyle,r.stroke=t.strokeStyle),r.fontFamily&&(r.fontFamily=t.fontFamily),r.fontSize&&(r.fontSize=t.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(e,t,i){if(!e||!t)return;const r=e.getChildItems();if("add"===i){if(r.includes(t))return;const i=t._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");t._zIndex=null}else{let i;if(t.styleId)i=this._getDrawingStyle(t.styleId);else{i=this.mapMediaType_Style.get(t._mediaType)[e.styleSelector];const r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected,!0)},n=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default,!0)};t._on("selected",r),t._on("deselected",n),t._funcChangeStyleToSelected=r,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,i,!0)}e._fabricObject.addWithUpdate(t._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(t))return;t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,e._fabricObject.removeWithUpdate(t._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(e,t){let i=e._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===e._mediaType){n=e.getChildItems();for(let e of n)if(e._drawingLayer&&e._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(t&&"object"==typeof t&&!Array.isArray(t))for(let e in t)i.set(e,t[e]);if(n){for(let e of n){const t=this.mapMediaType_Style.get(e._mediaType);for(let i of J.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)s=this._getDrawingStyle(e.styleId);else{s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e._on("selected",i),e._on("deselected",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of J.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)s=this._getDrawingStyle(e.styleId);else{s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default)};e._on("selected",i),e._on("deselected",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}this._changeItemStyle(e,s)}e._zIndex=this.id,e._drawingLayer=this,e._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let t=0;t{for(let t of this._arrDrawingLayer)if(t.getId()===e)return!0;return!1};if(void 0===t){for(let e=100;;e++)if(!i(e)){t=e;break}}else if(i(t))throw new Error("Existed drawing layer id.");const r=new ne(e,t,this._mapDrawingStyles,{enableRetinaScaling:!1});return r._manager=this,this._arrDrawingLayer.push(r),this._switchPointerEvent(),r}deleteDrawingLayer(e){const t=this.getDrawingLayer(e);if(!t)return;const i=this._arrDrawingLayer;t.dispose(),i.splice(i.indexOf(t),1),this._switchPointerEvent()}clearDrawingLayers(){for(let e of this._arrDrawingLayer)e.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(e){for(let t of this._arrDrawingLayer)if(t.getId()===e)return t;return null}getDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const e=this._arrDrawingLayer[0].fabricCanvas.getActiveObjects(),t=[];for(let i of e)t.push(i.getDrawingItem());return t}setDimensions(e,t){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(e,t)}setObjectFit(e){for(let t of this._arrDrawingLayer)t&&t._setObjectFit(e)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(e){this._arrDrawingLayer.length&&(this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.display=e?"block":"none")}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let e of this._arrDrawingLayer)e.getMode()}}class oe{constructor(e){this._controlTarget=null,this._arrUsers=[],this._mapAction_UserArgs=new Map,this._mapProperty_UserValue=new Map,this._mapAction_Callbacks=new Map,this._controlTarget=e}setControlTarget(e){this._controlTarget=e}getControlTarget(){return this._controlTarget}register(e){this._arrUsers.includes(e)||this._arrUsers.push(e)}logout(e){const t=this._arrUsers.indexOf(e);-1!==t&&(this.clearUserDisiredAction({user:e}),this.clearUserDisiredValue({user:e}),this._arrUsers.splice(t,1))}getRegisteredUsers(){return this._arrUsers}ifUserExisted(e){return this._arrUsers.includes(e)}setDisiredValue(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");r&&(this._controlTarget[t]=i),this._mapProperty_UserValue.get(t)?this._mapProperty_UserValue.get(t).set(e,i):this._mapProperty_UserValue.set(t,new Map([[e,i]]))}clearUserDisiredValue(e){if(e&&(e.user||e.property)){if(e.property&&e.user){const t=this._mapProperty_UserValue.get(e.property);if(!t)return;t.delete(e.user)}else if(e.property)this._mapProperty_UserValue.delete(e.property);else if(e.user)for(let t of this._mapProperty_UserValue.values())t.delete(e.user)}else this._mapProperty_UserValue=new Map}getValue(e){if(!this._controlTarget)throw new Error("Control target is not set.");return this._controlTarget[e]}getPropertyDisiredValue(e){if(this._mapProperty_UserValue.get(e)){const t=[],i=this._mapProperty_UserValue.get(e);for(let e of i.values())t.push(e);return t}return null}setDisiredAction(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");return i||(i=[]),r?this._controlTarget[t](...i):(this._mapAction_UserArgs.get(t)?this._mapAction_UserArgs.get(t).set(e,i):this._mapAction_UserArgs.set(t,new Map([[e,i]])),this._render(t))}clearUserDisiredAction(e){if(e&&(e.user||e.actionName)){if(e.actionName&&e.user){const t=this._mapAction_UserArgs.get(e.actionName);if(!t)return;t.delete(e.user)}else if(e.actionName)this._mapAction_UserArgs.delete(e.actionName);else if(e.user)for(let t of this._mapAction_UserArgs.values())t.delete(e.user);this.render()}else this._mapAction_UserArgs=new Map}addCallback(e,t){const i=this._mapAction_Callbacks.get(e);i?i.push(t):this._mapAction_Callbacks.set(e,[t])}removeCallback(e,t){const i=this._mapAction_Callbacks.get(e);if(!i)return;const r=i.indexOf(t);-1!==r&&i.splice(r,1)}clearCallback(e){e?this._mapAction_Callbacks.delete(e):this._mapAction_Callbacks.clear()}_fireCallback(e){const t=this._mapAction_Callbacks.get(e);if(t)for(let e of t){if(!e)return;setTimeout(e.bind(this._controlTarget),0)}}_render(e){const t=this._mapAction_UserArgs.get(e);if(!t)throw new Error("Unrecorded action.");if(t.size===this._arrUsers.length){let i=[];for(let e of t.values())e.length>0&&(i=e);if(this._controlTarget[e]){const t=this._controlTarget[e](...i);return this._mapAction_UserArgs.delete(e),this._fireCallback(e),t}}}render(e){if(e)return this._render(e);for(let e of this._mapAction_UserArgs.keys())this._render(e)}}class ae{static multiply(e,t){const i=[];for(let r=0;r<3;r++){const n=t.slice(3*r,3*r+3);for(let t=0;t<3;t++){const r=[e[t],e[t+3],e[t+6]].reduce(((e,t,i)=>e+t*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,t,i){return ae.multiply(e,[1,0,0,0,1,0,t,i,1])}static rotate(e,t){var i=Math.cos(t),r=Math.sin(t);return ae.multiply(e,[i,-r,0,r,i,0,0,0,1])}static scale(e,t,i){return ae.multiply(e,[t,0,0,0,i,0,0,0,1])}}var he;!function(e){e.GREY="grey",e.GREY32="grey32",e.RGBA="rgba",e.RBGA="rbga",e.GRBA="grba",e.GBRA="gbra",e.BRGA="brga",e.BGRA="bgra"}(he||(he={}));const le=(e,t,i,r)=>{let n=t+Math.round((e-t)/i)*i;return r&&(n=Math.min(n,r)),n};class ce{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this._predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this._mapCameraResolutions=new Map,this._bWebGLSupported=!0,this.extraBindings=[],this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode&&!this.getDrawingLayers().some((e=>"editor"==e.getMode()))){if(!this._singleFrameModeIpt){const e=document.createElement("input");this._singleFrameModeIpt=e,e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.addEventListener("change",(async()=>{const t=e.files[0];e.value="";const i=await(async e=>{let t=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(t=await createImageBitmap(e),t)return t}catch(e){}var r;return t||(i=await(r=e,new Promise(((e,t)=>{let i=URL.createObjectURL(r),n=new Image;n.dbrObjUrl=i,n.src=i,n.onload=()=>{e(n)},n.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})(t),r=i instanceof HTMLImageElement?i.naturalWidth:i.width,n=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=n;const s=e=>{const t=Date.now();if(0===r||0===n)return null;if(e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");const i=this._scanRegion,s=this.getFrameSize(r,n,i,this.maxCvsSideLength);if(!s)return null;let o=!0;r===s.sWidth&&n===s.sHeight&&(o=!1);const a=this.mapPixelFormatString_Enum.get(this.framePixelFormat.toLowerCase()),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:s.sx,sy:s.sy,width:s.dWidth,height:s.dHeight,colorMode:null,pixelFormat:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:s.sWidth,_sHeight:s.sHeight,_bUseWebGL:null},l=this._getImageData(e,r,n,s,null,{pixelFormat:a});if(!l)return null;const c=Date.now();return h.data=l.data,h.pixelFormat=h.colorMode=l.pixelFormat,h._bUseWebGL=l._bUseWebGL,h.timeSpent=c-t,h.timeStamp=c,l.pixelFormat===he.GREY?h.stride=h.width:h.stride=4*h.width,h};(e=>{let t=this._cvsSingleFrameMode;if(!t){if(t=document.createElement("canvas"),!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(t),t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit="contain",t.style.pointerEvents="none",this._cvsSingleFrameMode=t}t.width==r&&t.height==n||(t.width=r,t.height=n);const i=t.getContext("2d");i.clearRect(0,0,t.width,t.height),i.drawImage(e,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);let o;this._updateDrawingLayersSize();try{o=s(i)}catch(e){throw e}const a=this.mapCameraEvents.get("singleframeacquired");for(let e of a)if(e)try{const t={data:new Uint8Array(o.data),region:JSON.parse(JSON.stringify(o.region)),sx:o.sx,sy:o.sy,width:o.width,height:o.height,stride:o.stride,colorMode:o.colorMode,pixelFormat:o.pixelFormat,timeSpent:o.timeSpent,timeStamp:o.timeStamp,isCropped:o.isCropped,toCanvas:o.toCanvas,_sWidth:o._sWidth,_sHeight:o._sHeight,_bUseWebGL:o._bUseWebGL};await e.apply(this,[t])}catch(e){console.error(e)}})),e.style.position="fixed",e.style.left="-1px",e.style.top="-1px",e.style.width="1px",e.style.height="1px",e.style.backgroundColor="transparent",e.style.color="transparent",document.body.appendChild(e)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._framePixelFormat=void 0,this._defaultFramePixelFormat="rgba",this.mapPixelFormatString_Enum=new Map([["grey",he.GREY],["grey32",he.GREY32],["rgba",he.RGBA],["rbga",he.RBGA],["grba",he.GRBA],["gbra",he.GBRA],["brga",he.BRGA],["bgra",he.BGRA]]),this.shaderPixelFormat=he.RGBA,this.maxVideoCvsLength=3,this._reusedCvs=null,this._reusedWebGLCvs=null,this._tempDataContainer=null,this._webGLTexture=null,this._webGLProgramInfo=null,this._webGLBuffers=null,this._softwareScale=1,this._scaleCenter={x:0,y:0},this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,_focusArea:null},this._tapFocusEnabled=!0,this._focusSupported=!0,this._tapDoFocus=async e=>{if(this._touchMoved)return void(this._touchMoved=!1);if(!this._tapFocusEnabled)return;if(!this._bOpen)return;if(this.singleFrameMode)return;if(!this._video||this._video.paused)return;if(!this._videoTrack)return;if(!this._focusSupported)return;if(this.getDrawingLayers().some((e=>"editor"==e.getMode())))return;if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let t,i,r,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),e instanceof MouseEvent)t=e.clientX,i=e.clientY;else{if(!(e instanceof TouchEvent))throw new Error("Unknown event type.");if(!e.changedTouches.length)return;t=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY}const s=this.getVideoFit(),o=this._video.videoWidth,a=this._video.videoHeight,h=this._elContainer.getBoundingClientRect(),l=h.left,c=h.top,u=window.getComputedStyle(this._elContainer),d=parseFloat(u.width),f=parseFloat(u.height),g=d/f,_=o/a;let p=1;if("contain"===s)_>g?(p=d/o,r=(t-l)/p,n=(i-c-(f-d/_)/2)/p):(p=f/a,n=(i-c)/p,r=(t-l-(d-f*_)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");_>g?(p=f/a,n=(i-c)/p,r=(t-l+(f*_-d)/2)/p):(p=d/o,r=(t-l)/p,n=(i-c+(d/_-f)/2)/p)}const m={x:r+"px",y:n+"px"},v=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=v;await this._setLocalFocus(m,v,y,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance),this._focusParameters.taskBackToContinous=setTimeout((()=>{this._videoTrack&&this._videoTrack.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime)},this._touchMoved=!1,this._touchMoveEvent=()=>{this._touchMoved=!0},this._recordedStates={},this.playCallbackInfo=null,this._toCanvas=function(){const e=document.createElement("canvas");let t;if(e.width=this.width,e.height=this.height,"grey"===(this.pixelFormat||this.colorMode)){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}await this.setResolution(e,t),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this.singleFrameMode)if("visible"===document.visibilityState){if(ce._onLog&&ce._onLog("DCE: document visible."),this._bOpen&&this._vc_bPlayingVideoBeforeHide)if(this.videoSrc)this._video.play();else if(this._video.srcObject){const e=this._video.srcObject.getTracks()[0];this._video.srcObject.active&&e&&!e.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(ce._onLog&&ce._onLog("DCE: document hidden."),["iPhone","iPad"].includes(H.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let e of this._arrScanRegionOverlays)e&&(e.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&(e.style.display="",this._updateScanRegionOverlay(e));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null}static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:Y,worker:X,getUserMedia:z,camera:await Z(),browser:H.browser,version:H.version,OS:H.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");ce._engineResourcePath=(e=>{if(null==e&&(e="./"),!j){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(e){let t;try{t=window[e];const i="__storage_test__";return t.setItem(i,i),t.removeItem(i),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&t&&0!==t.length}}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"data"in e&&"region"in e&&"sx"in e&&"sy"in e&&"width"in e&&"height"in e&&("colorMode"in e||"pixelFormat"in e)&&"timeSpent"in e&&"timeStamp"in e&&"isCropped"in e&&"toCanvas"in e&&"_sWidth"in e&&"_sHeight"in e&&"_bUseWebGL"in e}static async testCameraAccess(){try{if(!navigator||!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return{ok:!1,message:"Insecure context."};(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()}))}catch(e){if("OverconstrainedError"===e.name||"NotFoundError"===e.name)return{ok:!1,message:"No camera detected."};if("NotAllowedError"===e.name)return{ok:!1,message:"No permission to access camera."};if("AbortError"===e.name)return{ok:!1,message:"Some problem occurred which prevented the device from being used."};if("NotReadableError"===e.name)return{ok:!1,message:"A hardware error occurred."};if("SecurityError"===e.name)return{ok:!1,message:"User media support is disabled."};throw e}return{ok:!0,message:"Successfully accessed the camera."}}set maxCvsSideLength(e){if(e<=0)throw new Error("Invalid value.");this._maxCvsSideLength=e}get maxCvsSideLength(){if(void 0!==this._maxCvsSideLength)return this._maxCvsSideLength;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxCvsSideLength");if(e&&1===e.length)return e[0]}return this._defaultMaxCvsSideLength}static set defaultUIElementURL(e){ce._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=ce._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",ce.engineResourcePath)}getUIElement(){return this.UIElement}async setUIElement(e){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof e||e instanceof String){if(!e.trim().startsWith("<")){let t=await fetch(e);if(!t.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+t.statusText);e=await t.text()}if(!e.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let t=document.createElement("div");t.innerHTML=e;for(let e=0;e100||e.regionTop>100||e.regionRight>100||e.regionBottom>100)))}set scanRegion(e){if(!this._checkValidRegion(e))throw new Error("Invalid region.");this._scanRegion=JSON.parse(JSON.stringify(e)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}setScanRegion(e){this.scanRegion=e}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}_calculateCvsSize(){if(!this._bOpen)return null;let e,t,i;if(this.singleFrameMode)e=this._imgWidth,t=this._imgHeight,i="contain";else{if(!this._video)return null;e=this._video.videoWidth,t=this._video.videoHeight,i=this.getVideoFit()}return{width:e,height:t,objectFit:i}}addScanRegionOverlayCanvas(){this._assertOpen();const e=document.createElement("canvas");if(this._updateScanRegionOverlay(e),!this._scanRegionOverlayContainer){const e=document.createElement("div");if(this._scanRegionOverlayContainer=e,e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.overflow="hidden",e.style.pointerEvents="none",this._layerBaseCvs)this._layerBaseCvs.parentElement.after(e);else if(this._cvsScanRegion)this._cvsScanRegion.after(e);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(e);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e)}this._recordedStates.overlayShow=!0}return this._scanRegionOverlayContainer.append(e),this._arrScanRegionOverlays.push(e),e}removeScanRegionOverlayCanvas(e){const t=this._arrScanRegionOverlays.indexOf(e);-1!==t&&(e.remove(),this._arrScanRegionOverlays.splice(t,1))}_updateScanRegionOverlay(e){if(!e)return;const t=this._calculateCvsSize();if(!t)return;const{width:i,height:r,objectFit:n}=t;if(i<=0||r<=0)return e.width=0,void(e.height=0);const s=this._getRegionInPixels(i,r,this._scanRegion),o=this.getFrameSize(i,r,this._scanRegion,this.maxCvsSideLength),a=o.dWidth,h=o.dHeight;e.width==a&&e.height==h||(e.width=a,e.height=h);const l=window.getComputedStyle(this._elContainer),c=parseFloat(l.width),u=parseFloat(l.height),d=c/u,f=i/r;let g,_,p,m,v=1;"contain"===n?(f>d?(v=c/i,g=0,_=(u-r*v)/2):(v=u/r,g=(c-i*v)/2,_=0),g+=s.regionLeft*v,_+=s.regionTop*v,p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):"cover"===n?(f>d?(v=u/r,g=s.regionLeft*v-(i*v-c)/2,_=s.regionTop*v):(v=c/i,g=s.regionLeft*v,_=s.regionTop*v-(r*v-u)/2),p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):(g=0,_=0,p=0,m=0),e.style.position="absolute",e.style.left=g+"px",e.style.top=_+"px",e.style.width=p+"px",e.style.height=m+"px"}showScanRegionOverlays(){this._scanRegionOverlayContainer&&("none"==this._scanRegionOverlayContainer.style.display&&(this._scanRegionOverlayContainer.style.display=""),this._recordedStates.overlayShow=!0)}hideScanRegionOverlays(){this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none",this._recordedStates.overlayShow=!1)}setViewDecorator(e,t){if(!e)return void(this._cvsViewDecorator&&(this._cvsViewDecorator.remove(),this._cvsViewDecorator=null));if(!t)throw new Error("Invalid area.");this._assertOpen();let i=[];if("string"==typeof e?i.push(e):Array.isArray(e)&&(i=JSON.parse(JSON.stringify(e))),!this._cvsViewDecorator){if(this._cvsViewDecorator=document.createElement("canvas"),this._scanRegionOverlayContainer)this._scanRegionOverlayContainer.after(this._cvsViewDecorator);else if(this._layerBaseCvs)this._layerBaseCvs.parentElement.after(this._cvsViewDecorator);else if(this._cvsScanRegion)this._cvsScanRegion.after(this._cvsViewDecorator);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(this._cvsViewDecorator);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(this._cvsViewDecorator);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(this._cvsViewDecorator)}this._recordedStates.decoratorShow=!0}this._decoratorArea=JSON.parse(JSON.stringify(t)),this._decoratorType.length=0;const r=["rectangle","focus"],n=["crossline","crosshair"];let s=!1,o=!1;for(let e of i)e=e.toLowerCase(),r.includes(e)&&!s&&(s=!0,this._decoratorType.push(e)),n.includes(e)&&!o&&(o=!0,!this._decoratorType.includes(e)&&this._decoratorType.push(e));this._updateViewDecorator()}getViewDecorator(){return{type:JSON.parse(JSON.stringify(this._decoratorType)),area:JSON.parse(JSON.stringify(this._decoratorArea)),canvas:this._cvsViewDecorator}}showViewDecorator(){this._cvsViewDecorator&&("none"==this._cvsViewDecorator.style.display&&(this._cvsViewDecorator.style.display=""),this._recordedStates.decoratorShow=!0)}hideViewDecorator(){this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none",this._recordedStates.decoratorShow=!1)}setViewDecoratorLineWidth(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("lineWidth"))throw new Error(`It is not allowed to change the property 'lineWidth' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].lineWidth=t,this._updateViewDecorator()}setViewDecoratorStrokeStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("strokeStyle"))throw new Error(`It is not allowed to change the property 'strokeStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].strokeStyle=t,this._updateViewDecorator()}setViewDecoratorFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("fillStyle"))throw new Error(`It is not allowed to change the property 'fillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].fillStyle=t,this._updateViewDecorator()}setViewDecoratorMaskFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("maskFillStyle"))throw new Error(`It is not allowed to change the property 'maskFillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].maskFillStyle=t,this._updateViewDecorator()}_updateViewDecorator(){if(!this._bOpen)return;if(!this._cvsViewDecorator||!this._decoratorArea)return;let e;if(this.singleFrameMode)e="contain";else{if(!this._video)return;e=this.getVideoFit()}const t=this._cvsViewDecorator;t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit=e,t.style.pointerEvents="none";const i=this.getVisibleRegion(!0),r=i.regionRight-i.regionLeft,n=i.regionBottom-i.regionTop;if(t.width==r&&t.height==n||(t.width=r,t.height=n),r<=0||n<=0)return;const s=t.getContext("2d");s.clearRect(0,0,t.width,t.height);const o=this._decoratorArea.x/100*r,a=this._decoratorArea.y/100*n,h=this._decoratorArea.width/100*r,l=this._decoratorArea.height/100*n;for(let e of this._decoratorType){if("rectangle"===e){s.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,s.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const e=s.lineWidth/2;s.strokeRect(Math.round(o-e),Math.round(a-e),Math.round(h+s.lineWidth),Math.round(l+s.lineWidth))}if("focus"===e){s.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.focus.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.focus.lineWidth,s.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const e=s.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];s.beginPath();for(let e=0;e{const e=parseFloat(window.getComputedStyle(this._elContainer).width),t=parseFloat(window.getComputedStyle(this._elContainer).height);let s,o={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?e/tthis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){if(void 0!==this._maxNumberOfFramesInBuffer)return this._maxNumberOfFramesInBuffer;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxNumberOfFramesInBuffer");if(e&&1===e.length)return e[0]}return this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(e){this._refreshInterval=e}get refreshInterval(){if(void 0!==this._refreshInterval)return this._refreshInterval;if(this._controler){const e=this._controler.getPropertyDisiredValue("refreshInterval");if(e&&1===e.length)return e[0]}return this._defaultRefreshInterval}static async createInstance(e){let t=new ce;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,ce.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ce.onWarning&&ce.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ce.onWarning&&ce.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),t._drawingLayersManager=new se,t}static async playVideo(e,t,i){return new Promise(((r,n)=>{e||n(new Error("Invalid video element.")),t||n(new Error("Invalid source.")),e.onloadedmetadata=async()=>{e.onloadedmetadata=null,await e.play(),r(e)},"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,void 0!==i&&setTimeout((()=>n(new Error("Failed to play video. Timeout."))),i)}))}static findBestRearCamera(e){if(!e||!e.length)return null;const t=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"];for(let i of e){const e=i.label.toLowerCase();if(e&&t.some((t=>e.includes(t)))&&/\b0(\b)?/.test(e))return i.deviceId}return["Android","HarmonyOS"].includes(H.OS)?e[e.length-1].deviceId:null}async play(e,t,i,r){let n;if(this._video&&this.videoSrc){ce._onLog&&(n=Date.now(),ce._onLog("DCE: start loading static video: "+n));const e=await ce.playVideo(this._video,this.videoSrc,4e3);if(ce._onLog&&ce._onLog("DCE: finish loading static video. Costs: "+(Date.now()-n)),!this._video)return e.pause(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};const t={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};this.playCallbackInfo=JSON.parse(JSON.stringify(t));const i=this.mapCameraEvents.get("played");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[i])}),0)}return this._recordedStates.videoPlaying=!0,t}if(this.singleFrameMode)return r&&r.notTriggerSingleFrameClick||this._clickIptSingleFrameMode(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};if(!this._video)throw new Error("'video' is null or undefined.");const s=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,s{var r;try{this._video&&this._video.srcObject&&this.stop(),ce._onLog&&ce._onLog("DCE: ======before video========");const n=()=>{if(!this._video)throw a&&a.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},s=this.getVideoSettings();let o,a;if("boolean"==typeof s.video&&(s.video={}),e)delete s.video.facingMode,s.video.deviceId={exact:e};else if(s.video.deviceId);else if(this._lastDeviceId)delete s.video.facingMode,s.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&ce.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete s.video.facingMode,s.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),t=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&t&&(s.video.width=e,s.video.height=t)}else if(this.ifSkipCameraInspection);else if(s.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=s.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){o=!0;const e=ce.findBestRearCamera(this._allCameras);e&&(delete s.video.facingMode,s.video.deviceId={ideal:e})}}t&&(s.video.width={ideal:t}),i&&(s.video.height={ideal:i}),ce._onLog&&ce._onLog("DCE: ======try getUserMedia========");let h=[0,500],l=null;const c=async e=>{for(let t of h){t&&await new Promise((e=>setTimeout(e,t))),n();try{ce._onLog&&ce._onLog("DCE: ask "+JSON.stringify(e)),a=await navigator.mediaDevices.getUserMedia(e);break}catch(e){l=e,ce._onLog&&ce._onLog("DCE: "+e.message||e)}}};let u;if(await c(s),a||(ce._onLog&&ce._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(s)),"object"==typeof u.video&&(["iPhone","iPad"].includes(H.OS)?(t>=1280||i>=1280?u.video.width=1280:t>=640||i>=640?u.video.width=640:(t<640||i<640)&&(u.video.width=320),delete u.video.height):o&&!s.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0),ce._onLog&&ce._onLog("DCE: "+u),await c(u)),a||(h=[1e3,2e3],await c(s)),a||await c(u),!a)throw l;const d=()=>{const e=a.getVideoTracks();let t,i;if(e.length&&(t=this._videoTrack=e[0]),this._video&&t){const e=t.getSettings();if(e)for(let r of this._allCameras)if(e.deviceId===r.deviceId){r._checked=!0,r.label=t.label,i=r;break}}this._currentCamera=i};if(await this.getAllCameras(!1),n(),o){d();const e=ce.findBestRearCamera(this._allCameras),t=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;e&&e!=t&&(a.getTracks().forEach((e=>{e.stop()})),h=[0,500,1e3,2e3],await c(s))}ce._onLog&&ce._onLog("DCE: ======play video========"),n(),await ce.playVideo(this._video,a,4e3),n(),ce._onLog&&ce._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=f,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),ce._onLog&&ce._onLog("DCE: got "+f),d(),this._renderSelCameraInfo();const g={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};g.deviceId&&(this._lastDeviceId=g.deviceId,this.ifSaveLastUsedCamera&&ce.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),s.video.width&&s.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(s.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(s.video.height)))));const _=this.mapCameraEvents.get("played");for(let e of _){if(!e)continue;const t=JSON.parse(JSON.stringify(g));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}return this.promisePlay=null,g}catch(e){throw this.promisePlay=null,this._bgLoading&&(this._bgLoading.style.display="none"),"NotFoundError"===e.name&&(DOMException?e=new DOMException("No camera available, please use a device with an accessible camera.",e.name):(e=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),e}})(),ce._onLog&&(n=Date.now(),ce._onLog("DCE: start opening camera: "+n));const o=await this.promisePlay;return ce._onLog&&ce._onLog("DCE: finish opening camera. Costs: "+(Date.now()-n)),this.playCallbackInfo=JSON.parse(JSON.stringify(o)),this._recordedStates.videoPlaying=!0,o}async resume(){this._assertOpen(),this._video&&(await this._video.play(),this._recordedStates.videoPlaying=!0),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&t.classList.contains("dce-opt-gotResolution")?this._optGotRsl=t:!this._btnClose&&t.classList.contains("dce-btn-close")?this._btnClose=t:!this._selMinLtr&&t.classList.contains("dlr-sel-minletter")?(this._selMinLtr=t,this._selMinLtr.options.length||(this._selMinLtr.innerHTML=[this._optGotMinLtr?"":'','','','','','','','','','',''].join(""),this._optGotMinLtr=this._optGotMinLtr||this._selMinLtr.options[0])):!this._optGotMinLtr&&t.classList.contains("dlr-opt-gotMinLtr")&&(this._optGotMinLtr=t);if(this.extraBindings&&this.extraBindings.length)for(let i of this.extraBindings)try{i(t)}catch(e){}}if(!this._video)throw this._unbindUI(),Error(`Can not find the video container element with class '${this.containerClassName}'`);this.singleFrameMode||this.videoSrc?(this.singleFrameMode&&(this._elContainer&&(this._elContainer.addEventListener("click",this._clickIptSingleFrameMode),this._elContainer.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._elContainer&&(["Android","HarmonyOS"].includes(H.OS)?(this._elContainer.addEventListener("touchend",this._tapDoFocus),this._elContainer.addEventListener("touchmove",this._touchMoveEvent)):this._elContainer.addEventListener("click",this._tapDoFocus)),this._selCam&&(this._selCam.style.display="block",this._selCam.addEventListener("change",this._onCameraSelChange)),this._selRsl&&(this._selRsl.style.display="block",this._selRsl.addEventListener("change",this._onResolutionSelChange)),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._bgLoading&&(this._bgLoading.style.display="block")),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&(this._resizeObserver||(this._resizeObserver=new ResizeObserver((e=>{for(let t of e)t.target===this._elContainer&&this._updateLayers()}))),this._elContainer&&this._resizeObserver.observe(this._elContainer)),window.addEventListener("resize",this._updateLayers)}_unbindUI(){this.singleFrameMode?(this._elContainer&&(this._elContainer.removeEventListener("click",this._clickIptSingleFrameMode),this._elContainer.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._elContainer&&(this._elContainer.removeEventListener("click",this._tapDoFocus),this._elContainer.removeEventListener("touchend",this._tapDoFocus),this._elContainer.removeEventListener("touchmove",this._touchMoveEvent)),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._drawingLayersManager.setVisible(!1),this._hideOriginalImageCvs(),this._videoContainer&&this._videoContainer.remove(),this._video=null,this._videoContainer=null,this._elContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._updateLayers)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}async open(e){this.UIElement||await this.setUIElement(ce.defaultUIElementURL),this._bindUI(),e&&this.appendAndShowUI();let t=await this.play();this.bOpen=!0,this._focusParameters.fds=null,this._focusParameters.kTimeout=void 0,this._focusSupported=!0,this._tapFocusEnabled&&!this.singleFrameMode&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,this._focusParameters.fds||(this._focusSupported=!1,this._tapFocusEnabled=!1));const i=this.mapCameraEvents.get("cameraopen");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[i])}),0)}return t}close(e){if(!this._video)return;this.stop(),this._hideOriginalImage(!1),this.hideTip(),this._unbindUI(),e&&this.hideUI(),this.stopFetchingLoop(),this.bOpen=!1;const t=this.mapCameraEvents.get("cameraclose");for(let e of t){if(!e)continue;const t={width:0,height:0,deviceId:null};setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}stop(){this._video&&this._video.srcObject&&(ce._onLog&&ce._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((e=>{e.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(ce._onLog&&ce._onLog("DCE: ======stop existing video========"),this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0,this._reusedCvs&&this._reusedCvs.ctx2d&&this._reusedCvs.ctx2d.clearRect(0,0,this._reusedCvs.width,this._reusedCvs.height),this.forceLoseContext()}async getAllCameras(e=!0){let t=(await navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind));if(e&&t&&t.length&&!t[0].deviceId){let e=await navigator.mediaDevices.getUserMedia({video:!0});t=(await navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)),e.getTracks().forEach((e=>{e.stop()}))}const i=[],r=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&r.push(e);for(let e=0;e{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}if(r!==s.width||n!==s.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const e=this.mapCameraEvents.get("resolutionchange");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(s));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return s}getResolution(){if(this._bOpen)return[this._video.videoWidth,this._video.videoHeight];{let e=0,t=0;const i=this.videoSettings.video.width,r=this.videoSettings.video.height;return i&&(e=i.exact||i.ideal||i),r&&(t=r.exact||r.ideal||r),[e,t]}}async setResolution(e,t){let i,r;if(e instanceof Array?(i=e[0],r=e[1]):(i=e,r=t),this.videoSettings.video.width={ideal:i},this.videoSettings.video.height={ideal:r},!this._bOpen||this._video.paused)return null;const n=this._video.videoWidth,s=this._video.videoHeight,o=await this.play(null,i,r);if(n!==o.width||s!==o.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const e=this.mapCameraEvents.get("resolutionchange");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(o));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return o}async getResolutions(e){let t="";const i=(e,t)=>{const i=this._mapCameraResolutions.get(e);if(!i||!i.length)return!1;for(let e of i)if(e[0]===t.width&&e[1]===t.height)return!0;return!1},r=async(e,t,i)=>{const r={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(e){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const e=s[0].getSettings();o={width:e.width,height:e.height}}catch(e){const t=document.createElement("video");t.srcObject=n,o={width:t.videoWidth,height:t.videoHeight},t.srcObject=null}return s.forEach((e=>{e.stop()})),o};if(!this._bOpen){const n=this.videoSettings.video.deviceId;if(!n)return null;if(t=n.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:n.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!t)return null;let s=this._mapCameraResolutions.get(t);if(s&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),s=this._mapCameraResolutions.get(t);for(let e of this._predefinedResolutions){const n=await r(t,e.width,e.height);n&&!i(t,n)&&s.push([n.width,n.height])}return s}if(this._currentCamera){t=this._currentCamera.deviceId;let r=this._mapCameraResolutions.get(t);if(r&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),r=this._mapCameraResolutions.get(t);const n=this.getConstraints();for(let e of this._predefinedResolutions){await this._videoTrack.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const n=this._videoTrack.getSettings(),s={width:n.width,height:n.height};i(t,s)||r.push([s.width,s.height])}return await this._videoTrack.applyConstraints(n),r}return null}on(e,t){if(!t)return;const i=this.mapCameraEvents.get(e.toLowerCase());if(!i)throw new Error(`Event '${e}' does not exist.`);i.includes(t)||i.push(t)}off(e,t){const i=this.mapCameraEvents.get(e.toLowerCase());if(!i)throw new Error(`Event '${e}' does not exist.`);const r=i.indexOf(t);-1!==r&&i.splice(r,1)}offAll(e){if(e){if("string"==typeof e){const t=this.mapCameraEvents.get(e);t&&(t.length=0)}}else for(let e of this.mapCameraEvents.values())e&&(e.length=0)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(e){if(this.videoSettings=JSON.parse(JSON.stringify(e)),this._lastDeviceId=null,this._bOpen)return this.play()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return await this._videoTrack.applyConstraints(e)}async turnOnTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}async turnOffTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}async setColorTemperature(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let t=this.getCapabilities().colorTemperature;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({advanced:[{colorTemperature:e,whiteBalanceMode:"manual"}]})}getColorTemperature(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let t=this.getCapabilities().exposureCompensation;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({advanced:[{exposureCompensation:e}]})}getExposureCompensation(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setHardwareScale()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");if(!this._videoTrack)return;const t=this.getCapabilities().zoom;if(!t)throw new Error("Not supported.");return et.max&&(e=t.max),e=le(e,t.min,t.step,t.max),await this._videoTrack.applyConstraints({advanced:[{zoom:e}]}),e}_getHardwareScale(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(e,t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setSoftwareScale()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");t&&this._setScaleCenter(t),this._softwareScale=e,this._scaleVideo(e,t)}_getSoftwareScale(){return this._softwareScale}_setScaleCenter(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setScaleCenter()' is unavailable in singleFrameMode.");if(!e||"string"!=typeof e.x||"string"!=typeof e.y)throw new Error("Invalid center.");const t=this._video.videoWidth,i=this._video.videoHeight;let r=0,n=0;if(e.x.endsWith("px"))r=parseFloat(e.x);else{if(!e.x.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(e.x)/100*t}if(e.y.endsWith("px"))n=parseFloat(e.y);else{if(!e.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(e.y)/100*i}if(NaN==r||NaN==n)throw new Error("Invalid scale center.");this._scaleCenter={x:r,y:n}}_resetScaleCenter(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_resetScaleCenter()' is unavailable in singleFrameMode.");const e=this._video.videoWidth,t=this._video.videoHeight;this._scaleCenter={x:e/2,y:t/2}}_isVideoCenter(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_isVideoCenter()' is unavailable in singleFrameMode.");return e&&e.x==this._video.videoWidth/2&&e.y==this._video.videoHeight/2}async _setZoom(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const t=await this._setHardwareScale(e);let i=this._getHardwareScale();1==i&&1!=t&&(i=t),e>i?this._setSoftwareScale(e/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(e)}catch(t){if("Not supported."!==(t.message||t))throw t;this._setSoftwareScale(e)}}async setZoom(e){if("number"!=typeof e&&"object"!=typeof e)throw new TypeError("Illegal type of argument.");if("number"==typeof e)return this._setZoom(e);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(e){if("number"!=typeof e.factor)throw new TypeError("Illegal type of 'factor'.");if(e.factor<1)throw new RangeError("Invalid value.");e.centerPoint?this._setScaleCenter(e.centerPoint):this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const t=await this._setHardwareScale(e.factor);let i=this._getHardwareScale();1==i&&1!=t&&(i=t),e.factor>i?this._setSoftwareScale(e.factor/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(e.factor)}catch(t){if("Not supported."!==(t.message||t))throw t;this._setSoftwareScale(e.factor)}}}getZoom(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?{factor:this._getHardwareScale()*this._softwareScale}:null}async resetZoom(){await this.setZoom({factor:1})}async setFrameRate(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let t=this.getCapabilities().frameRate;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:e})}getFrameRate(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(e,t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if("string"!=typeof e)throw Error("Invalid focus mode.");e=e.toLowerCase();const i=this.getCapabilities().focusMode,r=this.getCapabilities().focusDistance;if(!i)throw Error("Not supported.");if(!i.includes(e))throw Error("Unsupported mode.");if(t>=0){if(!r)throw Error("Manual focus unsupported.");return tr.max&&(t=r.max),t=le(t,r.min,r.step,r.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:e,focusDistance:t}]})}return await this._videoTrack.applyConstraints({advanced:[{focusMode:e}]})}async setFocus(e,t){if("string"==typeof e)return this._setFocus(e,t);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if(!e)return;const i=this.getCapabilities(),r=i.focusMode,n=i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof e.mode)throw Error("Invalid focus mode.");const s=e.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"!==s)return this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:s}]});if(!n)throw Error("Manual focus unsupported.");if(e.hasOwnProperty("distance")){let t=e.distance;return tn.max&&(t=n.max),t=le(t,n.min,n.step,n.max),this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:s,focusDistance:t}]})}if(!e.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const t=e.area.centerPoint;let i=e.area.width,r=e.area.height;if(!i||!r){const e=this._video.videoWidth,t=this._video.videoHeight;i||(i=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters._focusArea={centerPoint:{x:t.x,y:t.y},width:i,height:r},await this._setLocalFocus(t,i,r)}}getFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const e=this._videoTrack.getSettings().focusMode;return e?"continuous"===e?{mode:e}:{mode:e,distance:this._videoTrack.getSettings().focusDistance}:null}getFocusSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const e=this._videoTrack.getSettings(),t=e.focusMode;return t?"manual"===t?this._focusParameters._focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters._focusArea))}:{mode:"manual",distance:e.focusDistance}:{mode:t}:null}async _setFocusAndGetContract(e,t){const i=e=>{if(!this._bOpen||!this._videoTrack||this.video.paused||e.focusTaskId!=this._focusParameters.curFocusTaskId){this._bOpen&&this._videoTrack&&!this.video.paused||(this._focusParameters.isDoingFocus=0);const t=new Error(`Focus task ${e.focusTaskId} canceled.`);throw t.name="DeprecatedTaskError",t}1===this._focusParameters.isDoingFocus&&Date.now()-e.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;t=le(t,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:"manual",focusDistance:t}]}),i(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/t),Math.abs(1/this._focusParameters.fds.max-1/t))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/t)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=t,await new Promise((e=>{setTimeout(e,r)})),i(e);let n=e.focusL-e.focusW/2,s=e.focusT-e.focusH/2,o=e.focusW,a=e.focusH;if(n>=this.video.videoWidth||s>=this.video.videoHeight)throw new Error("Invalid area.");n+o>this.video.videoWidth&&(o=this.video.videoWidth-n),s+a>this.video.videoHeight&&(a=this.video.videoHeight-s);const h=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:n,sy:s,sWidth:o,sHeight:a,dWidth:o,dHeight:a},null,{pixelFormat:he.RGBA});if(!h)return this._setFocusAndGetContract(e,t);const l=h.data;let c=0;for(let e=0,t=l.length-8;eo&&oc)return await this._doFocusDetail(e,s,o,r,n,l,c)}else{let a=await this._setFocusAndGetContract(e,l);if(o>a)return await this._doFocusDetail(e,s,o,r,n,l,a);if(o==a)return await this._doFocusDetail(e,s,o,l,a);let c=await this._setFocusAndGetContract(e,h);if(c>o&&o{try{(null==t||tthis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=le(Math.sqrt(i*(t||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=le(Math.sqrt((t||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=le(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await this._setFocusAndGetContract(e,s),a=await this._setFocusAndGetContract(e,n),h=await this._setFocusAndGetContract(e,r);if(a>h&&ho&&a>o){let t=await this._setFocusAndGetContract(e,i);const n=await this._doFocusDetail(e,r,h,i,t,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const t=await this._doFocusDetail(e,r,h,s,o);return this._focusParameters.isDoingFocus=0,t}return d(e,t,i)}catch(e){if("DeprecatedTaskError"!==e.name)throw e}};return d(u,r,n)}async enableTapToFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'enableTapToFocus()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error("Video is not playing.");if(!this._focusSupported)throw new Error("Tapping to focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,this._tapFocusEnabled=!1,new Error("Tapping to focus unsupported.");this._tapFocusEnabled=!0}disableTapToFocus(){this._tapFocusEnabled=!1}isTapToFocusEnabled(){return this._tapFocusEnabled}_updateVideoContainerStyle(){if(!this._video)return;if(this.singleFrameMode)return;const e=this._getSoftwareScale(),t=this._videoContainer;if("contain"===this.videoFit&&e>1){const e=this._video.videoWidth,i=this._video.videoHeight,r=window.getComputedStyle(this._elContainer),n=parseFloat(r.width),s=parseFloat(r.height),o=e/i;if(n/sa?o/(i/e):s/(r/e));const c=l*(1-1/e)*(i/2-this._scaleCenter.x),u=l*(1-1/e)*(r/2-this._scaleCenter.y);this._video.style.transform=`translate(${c}px, ${u}px) scale(${e})`}this._updateVideoContainerStyle()}}getFrameSize(e,t,i,r){if(!e||!t)return null;let n,s,o,a,h=e,l=t;const c={regionLeft:0,regionTop:0,regionRight:h,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*h/100,c.regionTop=i.regionTop*l/100,c.regionRight=i.regionRight*h/100,c.regionBottom=i.regionBottom*l/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),n=Math.round(c.regionLeft),s=Math.round(c.regionTop),h=Math.round(c.regionRight-c.regionLeft),l=Math.round(c.regionBottom-c.regionTop)):(n=0,s=0,h=Math.round(h),l=Math.round(l));const u=Math.max(h,l);if(r&&r>0&&u>r){const e=r/u;h>l?(o=r,a=Math.round(l*e)):(o=Math.round(h*e),a=r)}else o=h,a=l;return o<=0||a<=0?null:{sx:n,sy:s,sWidth:h,sHeight:l,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoData()}getImage(){return this.getFrame()}_drawImage(e,t,i,r,n,s,o){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!i||!r)return null;if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let a;ce._onLog&&(a=Date.now(),ce._onLog("DCE: _drawImage(), START: "+a));let h=0,l=0,c=i,u=r,d=0,f=0,g=i,_=r;n&&(n.sx&&(h=Math.round(n.sx)),n.sy&&(l=Math.round(n.sy)),n.sWidth&&(c=Math.round(n.sWidth)),n.sHeight&&(u=Math.round(n.sHeight)),n.dx&&(d=Math.round(n.dx)),n.dy&&(f=Math.round(n.dy)),n.dWidth&&(g=Math.round(n.dWidth)),n.dHeight&&(_=Math.round(n.dHeight)));let p=he.RGBA;o&&o.pixelFormat&&(p=o.pixelFormat);const m=e;if(o&&o.bUseWebGL){ce._onLog&&ce._onLog("DCE: _drawImage() in WebGL."),(m.width{const t=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),e.STATIC_DRAW);const i=e.createBuffer();return e.bindBuffer(e.ARRAY_BUFFER,i),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),e.STATIC_DRAW),{positions:t,texCoords:i}},i=e=>{const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t},r=(e,t)=>{const i=e.createProgram();if(t.forEach((t=>e.attachShader(i,t))),e.linkProgram(i),!e.getProgramParameter(i,e.LINK_STATUS)){const t=new Error(`An error occured linking the program: ${e.getProgramInfoLog(i)}.`);throw t.name="WebGLError",t}return e.useProgram(i),i},n=(e,t,i)=>{const r=e.createShader(t);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){const t=new Error(`An error occured compiling the shader: ${e.getShaderInfoLog(r)}.`);throw t.name="WebGLError",t}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(e,[n(e,e.VERTEX_SHADER,s),n(e,e.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:h,attribLocations:{vertexPosition:e.getAttribLocation(h,"a_position"),texPosition:e.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:e.getUniformLocation(h,"u_image"),uColorFactor:e.getUniformLocation(h,"uColorFactor"),uMatrix:e.getUniformLocation(h,"u_matrix"),uTextureMatrix:e.getUniformLocation(h,"u_textureMatrix")}},this._webGLBuffers=t(e),this._webGLTexture=i(e),this.shaderPixelFormat=p}const n=(e,t,i)=>{e.bindBuffer(e.ARRAY_BUFFER,t),e.enableVertexAttribArray(i),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)},o=(e,t,i)=>{const r=e.RGBA,n=e.RGBA,s=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,r,n,s,i)},v=(e,t,s,o)=>{e.clearColor(0,0,0,1),e.clearDepth(1),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),n(e,s.positions,t.attribLocations.vertexPosition),n(e,s.texCoords,t.attribLocations.texPosition),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,o),e.uniform1i(t.uniformLocations.uSampler,0),e.uniform1f(t.uniformLocations.uColorFactor,[he.GREY,he.GREY32].includes(p)?1:0);let a,m,v=ae.translate(ae.identity(),-1,-1);v=ae.scale(v,2,2),v=ae.scale(v,1/e.canvas.width,1/e.canvas.height),a=ae.translate(v,d,f),a=ae.scale(a,g,_),e.uniformMatrix3fv(t.uniformLocations.uMatrix,!1,a),m=ae.translate(ae.identity(),h/i,l/r),m=ae.scale(m,c/i,u/r),e.uniformMatrix3fv(t.uniformLocations.uTextureMatrix,!1,m),e.drawArrays(e.TRIANGLES,0,6)};let y;if(o(e,this._webGLTexture,t),v(e,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),s){if(s.lengtht||r.sy>i||r.sx+r.sWidth>t||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;ce._onLog&&(o=Date.now(),ce._onLog("DCE: _getImageData(), START: "+o));const a=Math.round(r.sx),h=Math.round(r.sy),l=Math.round(r.sWidth),c=Math.round(r.sHeight),u=Math.round(r.dWidth),d=Math.round(r.dHeight);let f=he.RGBA;s&&s.pixelFormat&&(f=s.pixelFormat);let g,_,p,m=this._bWebGLSupported;s&&0==s.bUseWebGL&&(m=!1),m?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),g=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),g=this._reusedCvs);try{if(m)if(ce._onLog&&ce._onLog("DCE: _getImageData() in WebGL."),n)if(f===he.GREY){if(p=new Uint8Array(u*d*4),_=this._drawImage(g,e,t,i,{sx:a,sy:h,sWidth:l,sHeight:c,dWidth:u,dHeight:d},p,{pixelFormat:f,bUseWebGL:m}),p=this._transformPixelFormat(p,_.pixelFormat,f),n){if(n.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");e=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return e}_fetchingLoop(e){if(this.isDisposed&&this.disposed)return;if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();const t=()=>{ce._onLog&&ce._onLog("DCE: start fetching a frame into buffer: "+Date.now());const e=this.getCurrentRegion();let t=this._getVideoData(null,{region:e});if(!t)return void ce._onLog;for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t);const i=this.mapCameraEvents.get("frameaddedtobuffer");for(let e of i)e&&setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this)}),0)},i=()=>{this.isDisposed&&this.disposed||(this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.isDisposed&&this.disposed||(this._bOpen&&this.isFetchingLoopStarted()?(t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,ce._onLog&&ce._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(ce._onLog&&ce._onLog("DCE: stop fetching loop: "+Date.now()),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1,this._recordedStates.fetchingLoopStart=!1)}getFrameFromBuffer(e){return this._frameQueue&&this._frameQueue.length?e?ee.getId()>=0))}getSelectedDrawingItems(){return this._drawingLayersManager.getSelectedDrawingItems()}createDrawingStyle(e){return this._drawingLayersManager.createDrawingStyle(e)}getDrawingStyle(e){return this._drawingLayersManager.getDrawingStyle(e)}getDrawingStyles(){return this._drawingLayersManager.getDrawingStyles()}updateDrawingStyle(e,t){return this._drawingLayersManager.updateDrawingStyle(e,t)}clearDrawingLayers(){const e=this.getDrawingLayers();for(let t of e)this.deleteDrawingLayer(t.getId())}showTip(e,t,i,r,n=3e3,s=!0){this._assertOpen(),this._tipArgs.x=e,this._tipArgs.y=t,this._tipArgs.width=i,this._tipArgs.autoShowSuggestedTip=!!s,this._drawingLayerOfTip||(this._drawingLayerOfTip=this._createDrawingLayer(-1)),this._tipStyleId||(this._tipStyleId=this.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip.clearDrawingItems();const o=new re(r||"",e,t,i,this._tipStyleId);o._fabricObject.paddingTop=15,o._fabricObject.calcTextHeight=function(){for(var e=0,t=0,i=this._textLines.length;t0&&(this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}_hideTip(){this._drawingLayerOfTip&&(this.deleteDrawingLayer(this._drawingLayerOfTip.getId()),this._drawingLayerOfTip=null,this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId))}hideTip(){this._hideTip(),this._tipArgs.x=null,this._tipArgs.y=null,this._tipArgs.width=null,this._tipArgs.autoShowSuggestedTip=null}updateTipMessage(e){if(!this._drawingLayerOfTip)throw new Error("The Tip is not showing.");this._drawingLayerOfTip.getDrawingItems()[0].setAttribute("text",e),this._drawingLayerOfTip.renderAll(),this._tipArgs.duration>0&&(this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId),this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}suggestTip(e,t){this._tipArgs.autoShowSuggestedTip&&(this._drawingLayerOfTip?this.updateTipMessage(t):void 0!==this._tipArgs.x&&this.showTip(this._tipArgs.x,this._tipArgs.y,this._tipArgs.width,t,this._tipArgs.duration)),this.onTipSuggested&&setTimeout((()=>{this.isDisposed&&this.disposed||this.onTipSuggested.apply(this,[e,t])}),0)}_createControler(){if(this._controler||(this._controler=new oe(this)),this._controler)return this._controler}_destroyControler(){this._controler=null}setOriginalImage(e,t,i){if(!e||!t||!i)throw new Error("Invalid arguments");this._originalImageData={imageData:e,width:t,height:i};let r=this._cvsOriginalImage;r||(r=document.createElement("canvas"),r.style.position="absolute",r.style.width="100%",r.style.height="100%",r.style.left="0",r.style.top="0",r.style.backgroundColor="white",r.style.objectFit="contain",this._cvsOriginalImage=r),r.width===t&&r.height===i||(r.width=t,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),e instanceof Uint8Array||e instanceof Uint8ClampedArray?(e instanceof Uint8Array&&(e=new Uint8ClampedArray(e.buffer)),n.putImageData(new ImageData(e,t,i),0,0)):e instanceof HTMLCanvasElement&&n.drawImage(e,0,0),document.body.contains(r)&&""===r.style.display&&this._updateDrawingLayersSize({width:t,height:i,objectFit:"contain"})}getOriginalImage(){return this._originalImageData?Object.assign({},this._originalImageData):null}async deleteOriginalImage(){await this.hideOriginalImage(),this._cvsOriginalImage&&(this._cvsOriginalImage.remove(),this._cvsOriginalImage=null),this._originalImageData=null}_showOriginalImageCvs(){this._cvsOriginalImage&&"none"==this._cvsOriginalImage.style.display&&(this._cvsOriginalImage.style.display="")}_hideOriginalImageCvs(){this._cvsOriginalImage&&(this._cvsOriginalImage.style.display="none")}showOriginalImage(){if(!this._originalImageData)throw new Error("No original image is set.");const e=this._cvsOriginalImage;if(""===e.style.display&&document.body.contains(e))return;const{width:t,height:i}=this._originalImageData;if(this._updateDrawingLayersSize({width:t,height:i,objectFit:"contain"}),this._bOpen&&(this._video&&!this._video.paused&&this._video.pause(),this._bFetchingLoopStarted&&(this.stopFetchingLoop(),this._recordedStates.fetchingLoopStart=!0),this.ifShowScanRegionMask&&this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this.ifShowScanRegionLaser&&this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none"),this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none"),this._selCam&&(this._selCam.parentElement.style.display="none")),!document.body.contains(e))if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e)}this._showOriginalImageCvs()}async _hideOriginalImage(e){this._originalImageData&&this._cvsOriginalImage&&"none"!==this._cvsOriginalImage.style.display&&(this._updateDrawingLayersSize(),this._bOpen&&e&&(this._video&&this._recordedStates.videoPlaying&&await this.play(null,null,null,{notTriggerSingleFrameClick:!0}),this._recordedStates.fetchingLoopStart&&!this.singleFrameMode&&this.startFetchingLoop(),this.ifShowScanRegionMask&&this._cvsScanRegion&&this._recordedStates.maskShow&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this._divScanLight&&this._recordedStates.laserShow&&this.showScanRegionLaser(),this._cvsViewDecorator&&this._recordedStates.decoratorShow&&this.showViewDecorator(),this._scanRegionOverlayContainer&&this._recordedStates.overlayShow&&this.showScanRegionOverlays()),this._selCam&&(this._selCam.parentElement.style.display=""),this._hideOriginalImageCvs())}async hideOriginalImage(){return this._hideOriginalImage(!0)}dispose(e){this.UIElement&&(this._uiOriginalState&&this._uiOriginalState.inDom?this.UIElement.style.display=this._uiOriginalState.display:this.UIElement.style.display="none"),this.clearDrawingLayers(),this.close(),this.forceLoseContext(),this.setViewDecorator(null,null),this._scanRegionOverlayContainer&&this._scanRegionOverlayContainer.remove(),this._arrScanRegionOverlays.length=0,e&&this.UIElement&&this.UIElement.remove(),this.__proto__=null;for(let e in this)delete this[e];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"isDisposed",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}ce._jsVersion="3.3.1",ce._jsEditVersion="20230217",ce._version="JS "+ce._jsVersion+"."+ce._jsEditVersion,ce.browserInfo=H,ce._hasEngineResourceLoaded=!1,ce._engineResourcePath=K,ce._defaultUIElementURL="@engineResourcePath/dce.ui.html";const ue={DT_Arc:class extends J{constructor(e,t,i,r,n,s){super(new N.Circle({left:e,top:t,radius:i,startAngle:r,endAngle:n}),s),this._mediaType="arc"}},DT_Polygon:te,DT_Rect:class extends J{constructor(e,t,i,r,n){super(new N.Rect({left:e,top:t,width:i,height:r}),n)}},DT_Image:class extends J{constructor(e,t,i,r){super(new N.Image(e,{left:t,top:i}),r),this.image=e}_extendSet(e,t){if("image"===e){if(t instanceof HTMLImageElement)return this._fabricObject.setElement(t),this.image=t,!0;if(t instanceof HTMLCanvasElement){const e=new Image;return e.src=t.toDataURL(),this._fabricObject.setElement(e),this.image=t,!0}throw new Error("Unsupported value.")}}_extendGet(e){if("image"===e)return this.image}},DT_Text:re,DT_Line:class extends te{constructor(e,t,i){super([e,t],i),this._mediaType="line"}_extendSet(e,t){if("startPoint"===e||"endPoint"===e){t="startPoint"===e?[t,this.get("endPoint")]:[this.get("startPoint"),t];const i=this._fabricObject;if(i.group){const e=i.group;i.points=t.map((t=>({x:t.x-e.left-e.width/2,y:t.y-e.top-e.height/2}))),e.addWithUpdate()}else i.points=t;const r=i.points.length-1;return i.controls=i.points.reduce((function(e,t,i){return e["p"+i]=new N.Control({positionHandler:q,actionHandler:ee(i>0?i-1:r,$),actionName:"modifyPolygon",pointIndex:i}),e}),{}),i._setPositionDimensions({}),!0}}_extendGet(e){if("startPoint"===e||"endPoint"===e){const t=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let e in i.oCoords)t.push({x:i.oCoords[e].x,y:i.oCoords[e].y});else for(let e of i.points){let r=e.x-i.pathOffset.x,n=e.y-i.pathOffset.y;const s=N.util.transformPoint({x:r,y:n},i.calcTransformMatrix());t.push({x:s.x,y:s.y})}return"startPoint"===e?t[0]:t[1]}}},DT_Group:class extends J{constructor(e){super(new N.Group(e.map((e=>e._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.styleSelector="selected";const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.styleSelector="default";const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)}))}getChildItems(){return this._fabricObject._objects.map((e=>e.getDrawingItem()))}addChildItem(e){if(!e||!e.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"add"):this._fabricObject.addWithUpdate(e._getFabricObject())}removeChildItem(e){e&&e.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"remove"):this._fabricObject.removeWithUpdate(e._getFabricObject()))}}};function de(e,t,i){return(i.x-e.x)*(t.y-e.y)==(t.x-e.x)*(i.y-e.y)&&Math.min(e.x,t.x)<=i.x&&i.x<=Math.max(e.x,t.x)&&Math.min(e.y,t.y)<=i.y&&i.y<=Math.max(e.y,t.y)}function fe(e){return Math.abs(e)<1e-6?0:e<0?-1:1}function ge(e,t,i,r){let n=e[0]*(i[1]-t[1])+t[0]*(e[1]-i[1])+i[0]*(t[1]-e[1]),s=e[0]*(r[1]-t[1])+t[0]*(e[1]-r[1])+r[0]*(t[1]-e[1]);return!((n^s)>=0&&0!==n&&0!==s)&&(n=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),s=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),!((n^s)>=0&&0!==n&&0!==s))}class _e extends L{constructor(){super(),this._barcodeFillStyle="rgba(254,180,32,0.3)",this._barcodeStrokeStyle="rgba(254,180,32,0.9)",this._barcodeLineWidth=1,this._barcodeFillStyleBeforeVerification="rgba(248,252,0,0.2)",this._barcodeStrokeStyleBeforeVerification="transparent",this._barcodeLineWidthBeforeVerification=2,this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${ce.getVersion()})`}static _fireHTTPSWarnning(){_e.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{_e.onWarning&&_e.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return ce.testCameraAccess()}_fireResolutionWarning(){if(!this.singleFrameMode&&this.onWarning&&this.dce.isOpen()){const e=this.dce.getConstraints();e&&e.width<1280&&e.height<720&&setTimeout((()=>{this.onWarning&&this.onWarning({id:3,message:"Camera resolution too low, please use a higher resolution (720P or better)."})}),0)}}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}get video(){return this.dce&&this.dce.video}set videoSrc(e){this.dce&&(this.dce.videoSrc=e)}get videoSrc(){return this.dce&&this.dce.videoSrc}set onTipSuggested(e){this.dce&&(this.dce.onTipSuggested=e)}get onTipSuggested(){return this.dce&&this.dce.onTipSuggested}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set barcodeFillStyle(e){this._barcodeFillStyle=e,this.dce&&this.dce.updateDrawingStyle(3,{fillStyle:e})}get barcodeFillStyle(){return this._barcodeFillStyle}set barcodeStrokeStyle(e){this._barcodeStrokeStyle=e,this.dce&&this.dce.updateDrawingStyle(3,{strokeStyle:e})}get barcodeStrokeStyle(){return this._barcodeStrokeStyle}set barcodeLineWidth(e){this._barcodeLineWidth=e,this.dce&&this.dce.updateDrawingStyle(3,{lineWidth:e})}get barcodeLineWidth(){return this._barcodeLineWidth}set barcodeFillStyleBeforeVerification(e){this._barcodeFillStyleBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{fillStyle:e})}get barcodeFillStyleBeforeVerification(){return this._barcodeFillStyleBeforeVerification}set barcodeStrokeStyleBeforeVerification(e){this._barcodeStrokeStyleBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{strokeStyle:e})}get barcodeStrokeStyleBeforeVerification(){return this._barcodeStrokeStyleBeforeVerification}set barcodeLineWidthBeforeVerification(e){this._barcodeLineWidthBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{lineWidth:e})}get barcodeLineWidthBeforeVerification(){return this._barcodeLineWidthBeforeVerification}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.framePixelFormat=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(L._onLog&&L._onLog("createDCEInstance()"),ce.defaultUIElementURL=null,this.dce=await ce.createInstance(),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=ue,["iPhone","iPad","Android","HarmonyOS"].includes(L.browserInfo.OS)||this.dce.setResolution(1920,1080),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"}),this.barcodeLineWidth=this._barcodeLineWidth,this.dce.on("cameraChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async e=>{if(!e)return;if(!e.data)return;let t;this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:i,sx:r,sy:n,width:s,height:o,stride:a,pixelFormat:h,timeStamp:l,_sWidth:c,_sHeight:u}=e,d={timeStamp:l};if("grey"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_GrayScaled,0,d);else if("rgba"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_ARGB_8888,0,d)}if(await this.clearMapDecodeRecord(),L.recalculateResultLocation(t,r,n,c,u,s,o),this._drawResults(t),this.onFrameRead&&this.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onFrameRead(e)}if(this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))})))}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new _e;t._instanceID=await _e.createInstanceInWorker(!0),await t.createDCEInstance(),"string"==typeof e&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return await t.dce.setUIElement(_e.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),_e._fireHTTPSWarnning(),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const i=this.dce._getVideoData(null,{region:t});return this._decode_DCEFrame(i)}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=9}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=512,t.deblurLevel=3,t.localizationModes=[2,16,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=9,t.timeout=1e5}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=512,t.deblurLevel=5,t.scaleDownThreshold=1e5,t.localizationModes=[2,16,4,8,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=9,t.timeout=1e5}else if("single"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region)}else if("dense"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=0,t.deblurLevel=7,t.scaleDownThreshold=1e5,t.localizationModes=[2,8,0,0,0,0,0,0],t.minResultConfidence=0,t.barcodeZoneMinDistanceToImageBorders=9,t.timeout=1e5}else if("distance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=0,t.scaleDownThreshold=1e5,t.localizationModes=[2,8,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=9,t.timeout=1e5}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let i=e.region;[i.regionLeft,i.regionTop,i.regionLeft,i.regionBottom,i.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:i.regionLeft||0,regionTop:i.regionTop||0,regionRight:i.regionRight||0,regionBottom:i.regionBottom||0,regionMeasuredByPercentage:i.regionMeasuredByPercentage||0})}}if(!L._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(v.BF_ONED|v.BF_QR_CODE|v.BF_PDF417|v.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=t.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){i(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),L._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})})),"string"==typeof e&&["speed","balance","coverage","dense","distance"].includes(e)&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","1"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","0"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","0"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){const t=await this.dce.selectCamera(e);return this._fireResolutionWarning(),t}getResolution(){return this.dce.getResolution()}async setResolution(e,t){const i=await this.dce.setResolution(e,t);return this._fireResolutionWarning(),i}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}set ifSaveLastUsedCamera(e){this.dce&&(this.dce.ifSaveLastUsedCamera=e)}get ifSaveLastUsedCamera(){return this.dce&&this.dce.ifSaveLastUsedCamera}set ifSkipCameraInspection(e){this.dce&&(this.dce.ifSkipCameraInspection=e)}get ifSkipCameraInspection(){return this.dce&&this.dce.ifSkipCameraInspection}stop(){this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.dce.stop(),this.dce.ifShowScanRegionLaser=!1,this.dce.hideViewDecorator(),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this.dce.pause()}async play(e,t,i){this.dce.ifShowScanRegionLaser=!0;const r=await this.dce.play(e,t,i);return this._fireResolutionWarning(),r}pauseScan(e){this._assertOpen(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}getColorTemperature(){return this.dce.getColorTemperature()}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}getExposureCompensation(){return this.dce.getExposureCompensation()}async setZoom(e){return this.dce.setZoom(e)}getZoomSettings(){return this.dce.getZoomSettings()}resetZoom(){return this.dce.resetZoom()}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}getFocusSettings(){return this.dce.getFocusSettings()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(!this.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return L._onLog&&L._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));L._onLog&&L._onLog("======= once read ======="),L._onLog&&(this._timeStartDecode=Date.now());const e=this._getVideoFrame();if(!e)return L._onLog&&L._onLog("Get invalid frame."),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{e._bUseWebGL||"grey"!==e.pixelFormat||(this.dce.framePixelFormat="rgba");let t=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:i,sx:r,sy:n,width:s,height:o,stride:a,pixelFormat:h,timeStamp:l,_sWidth:c,_sHeight:u}=e,d={timeStamp:l};if("grey"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_GrayScaled,0,d);else if("rgba"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_ARGB_8888,0,d)}if(L.recalculateResultLocation(t,r,n,c,u,s,o),0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration)),this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan&&(this.autoZoom||this.autoFocus||this.autoSuggestTip))if(t.length)this.autoZoomInFrameArray.length=0,this.autoZoomOutFrameCount=0,this.frameArrayInIdealZoom.length=0,this.suggestTipFrameArray.length=0,this.autoZoom&&this.autoFocus&&(this.nextActionInIdealZoom="focus"),this.autoFocusFrameArray.length=0,this.noIntermediateResultsCount=0;else{const e=await this.getIntermediateResults(),t=(e,t,i,r,n,s,o)=>{let a=s/r,h=o/n;e.x1=e.x1/a+t,e.x2=e.x2/a+t,e.x3=e.x3/a+t,e.x4=e.x4/a+t,e.y1=e.y1/h+i,e.y2=e.y2/h+i,e.y3=e.y3/h+i,e.y4=e.y4/h+i},i=e=>{if(!e)return null;const i={};let a,h,l,d,f;{const e=this.video.videoWidth*(1-this.autoZoomDetectionArea)/2,t=this.video.videoWidth*(1+this.autoZoomDetectionArea)/2,i=t,r=e,n=this.video.videoHeight*(1-this.autoZoomDetectionArea)/2,s=n,o=this.video.videoHeight*(1+this.autoZoomDetectionArea)/2;f={x1:e,x2:t,x3:i,x4:r,y1:n,y2:s,y3:o,y4:o}}const g=(e,t)=>{const i=(e,t)=>{if(!e&&!t)throw new Error("Invalid arguments.");return function(e,t,i){let r=!1;const n=e.length;if(n<=2)return!1;for(let s=0;s0!=fe(a.y-i)>0&&fe(t-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}([{x:t.x1,y:t.y1},{x:t.x2,y:t.y2},{x:t.x3,y:t.y3},{x:t.x4,y:t.y4}],e.x,e.y)},r=(e,t)=>!!(ge([e[0],e[1]],[e[2],e[3]],[t.x1,t.y1],[t.x2,t.y2])||ge([e[0],e[1]],[e[2],e[3]],[t.x2,t.y2],[t.x3,t.y3])||ge([e[0],e[1]],[e[2],e[3]],[t.x3,t.y3],[t.x4,t.y4])||ge([e[0],e[1]],[e[2],e[3]],[t.x4,t.y4],[t.x1,t.y1]));return!!(i({x:e.x1,y:e.y1},t)||i({x:e.x2,y:e.y2},t)||i({x:e.x3,y:e.y3},t)||i({x:e.x4,y:e.y4},t))||(!!(i({x:t.x1,y:t.y1},e)||i({x:t.x2,y:t.y2},e)||i({x:t.x3,y:t.y3},e)||i({x:t.x4,y:t.y4},e))||!!(r([t.x1,t.y1,t.x2,t.y2],e)||r([t.x2,t.y2,t.x3,t.y3],e)||r([t.x3,t.y3,t.x4,t.y4],e)||r([t.x4,t.y4,t.x1,t.y1],e)))},_=[];for(let i of e){if(i.resultType!==y.IRT_TYPED_BARCODE_ZONE)continue;const e=i.scaleDownRatio;for(let a of i.results){if(!a)continue;const i={x1:a.x1=a.x1*e,x2:a.x2=a.x2*e,x3:a.x3=a.x3*e,x4:a.x4=a.x4*e,y1:a.y1=a.y1*e,y2:a.y2=a.y2*e,y3:a.y4=a.y3*e,y4:a.y4=a.y4*e};t(i,r,n,c,u,s,o),g(f,i)&&_.push(a)}}const p=(e=>{if(!e||!e.length)return null;const t=e=>{const t=(e.x1+e.x2+e.x3+e.x4)/4,i=(e.y1+e.y2+e.y3+e.y4)/4;return(t-s/2)*(t-s/2)+(i-o/2)*(i-o/2)};let i,r=e.filter((e=>e.barcodeFormat==v.BF_QR_CODE||e.barcodeFormat==v.BF_DATAMATRIX));if(r.length||(r=e.filter((e=>e.barcodeFormat==v.BF_ONED)),r.length||(r=e)),!r.length)return null;i=r[0];let n=t(i);if(1!=r.length)for(let e=1;e1.1*i.confidence?(i=r[e],n=s):r[e].confidence>.9*i.confidence&&s!0===e)).length>=this.suggestTipFrameLimit[1]){this.suggestTipFrameArray.length=0;const e=a.x3-a.x1,t=a.y3-a.y1;a.result.moduleSizet?e>s*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):e>.6*s&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."):e<=t&&(t>o*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):t>.6*o&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."))}if(this.autoZoom){const e=this.autoZoomIdealArea[1];let i=(1-this.autoZoomTargetBorder)/2;const h=a.x1/c,l=(c-a.x3)/c,d=a.y1/u,f=(u-a.y3)/u;if(h>e&&l>e&&d>e&&f>e&&a.result.moduleSize{}))),this.autoZoomInFrameArray.filter((e=>!0===e)).length>=this.autoZoomInFrameLimit[1]){this.autoZoomInFrameArray.length=0;const e=[(.5-i)/(.5-h),(.5-i)/(.5-l),(.5-i)/(.5-d),(.5-i)/(.5-f)].filter((e=>e>0)),t=Math.min(...e,this.autoZoomInIdealModuleSize/a.result.moduleSize),r=this.dce.getZoomSettings().factor;let n=Math.max(Math.pow(r*t,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);n=Math.min(n,t);const s=r*n;await this.setZoom({factor:s}),this.dce.clearFrameBuffer()}}else if(this.autoZoomInFrameArray.length=0,this.frameArrayInIdealZoom.push(!0),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.frameArrayInIdealZoom.filter((e=>!0===e)).length>=this.frameLimitInIdealZoom[1])if(this.frameArrayInIdealZoom.length=0,"focus"===this.nextActionInIdealZoom&&this.autoFocus){t(a,r,n,c,u,s,o);try{await this.setFocus({mode:"manual",area:{centerPoint:{x:(a.x1+a.x3)/2+"px",y:(a.y1+a.y3)/2+"px"},width:a.x3-a.x1+"px",height:a.y3-a.y1+"px"}})}catch(e){}this.dce.clearFrameBuffer(),this.nextActionInIdealZoom="zoomOut"}else{if("zoomOut"!==this.nextActionInIdealZoom&&this.autoFocus)throw new Error("Invalid action.");if(this.enableZoomOutInIdealZoom){i=this.autoZoomIdealArea[1]+this.autoZoomOutStepRate_2;const e=[(.5-i)/(.5-h),(.5-i)/(.5-l),(.5-i)/(.5-d),(.5-i)/(.5-f)].filter((e=>e>0));let t=Math.min(...e)*this.dce.getZoomSettings().factor;await this.setZoom({factor:t}),this.dce.clearFrameBuffer(),this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((e=>{})))}}}else if(this.autoFocus&&(this.autoFocusFrameArray.push(!0),this.autoFocusFrameArray.splice(0,this.autoFocusFrameArray.length-this.autoFocusFrameLimit[0]),this.autoFocusFrameArray.filter((e=>!0===e)).length>=this.autoFocusFrameLimit[1])){this.autoFocusFrameArray.length=0;try{t(a,r,n,c,u,s,o),await this.setFocus({mode:"manual",area:{centerPoint:{x:(a.x1+a.x3)/2+"px",y:(a.y1+a.y3)/2+"px"},width:a.x3-a.x1+"px",height:a.y3-a.y1+"px"}})}catch(e){}this.dce.clearFrameBuffer()}}else if(this.noIntermediateResultsCount++,this.suggestTipFrameArray.push(!1),this.autoZoom){if(this.autoZoomInFrameArray.push(!1),this.autoZoomInFrameArray.splice(0,this.autoZoomInFrameArray.length-this.autoZoomInFrameLimit[0]),this.autoZoomOutFrameCount++,this.frameArrayInIdealZoom.push(!1),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.autoZoomOutFrameCount>=this.autoZoomOutFrameLimit){this.autoZoomOutFrameCount=0;const e=this.getZoomSettings().factor;if(e>this.autoZoomOutMinValue){const t=Math.max((e-1)*this.autoZoomOutStepRate,this.autoZoomOutMinStep),i=Math.max(e-t,this.autoZoomOutMinValue);await this.setZoom({factor:i}),this.dce.clearFrameBuffer()}}this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((e=>{})))}else this.autoFocus&&(this.autoFocusFrameArray.length=0,this.setFocus({mode:"continuous"}).catch((e=>{})))}return t})().then((e=>{if(L._onLog&&L._onLog(e),this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;const r=()=>{let r=0;if(this.region instanceof Array){let n=0,s=0;n=i+1>=this.region.length?0:i+1,s=n+1>=this.region.length?0:n+1,r=e[n]&&e[n].length&&t[s]&&t[s].length?Math.min(...e[n])-Math.max(...t[s]):0}else if(t&&t.length){let i=Math.min(...e),n=Math.max(...t);i&&n&&(r=i-n)}else r=0;return r>0?r:0};(()=>{if(this.region instanceof Array){for(e[i]&&e[i]instanceof Array||(e[i]=[]);e[i].length>=5;)e[i].shift();e[i].push(this._lastInnerDecodeDuration)}else{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=r()+this.intervalTime,L._onLog&&L._onLog("Next fetching frame loop interval: "+this._intervalGetVideoFrame)}if(this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onFrameRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){L._onLog&&L._onLog("Get frame in parallel.");let t=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,t||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;e=this.dce.getFrameFromBuffer();const i=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};i(e)}else L._onLog&&L._onLog("Get frame in serial."),this.dce.stopFetchingLoop(),e=this.dce.getFrame();return e}async open(){this._bindUI();const e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}close(){this.dce.close(),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}hide(){this.dce.close(!0),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}showTip(e,t,i,r,n=3e3,s=!0){this.dce&&this.dce.showTip(e,t,i,r,n,s)}hideTip(){this.dce&&this.dce.hideTip()}updateTipMessage(e){this.dce&&this.dce.updateTipMessage(e)}async enableTapToFocus(){this.dce&&this.dce.enableTapToFocus()}disableTapToFocus(){this.dce&&this.dce.disableTapToFocus()}isTapToFocusEnabled(){return this.dce.isTapToFocusEnabled()}destroyContext(){this.close(),this.dce&&this.dce.dispose(!1),this.bDestroyed||super.destroyContext()}}var pe,me,ve,ye,Se,we,be,Ce,xe,Te,Ie,Ae,Ee,Oe,De,Re,Me,Le,Fe,Pe,ke,Be,Ne,je,Ve,Ue;!function(e){e[e.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",e[e.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",e[e.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",e[e.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",e[e.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",e[e.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",e[e.BICM_SKIP=0]="BICM_SKIP",e[e.BICM_REV=2147483648]="BICM_REV"}(pe||(pe={})),function(e){e[e.BCM_AUTO=1]="BCM_AUTO",e[e.BCM_GENERAL=2]="BCM_GENERAL",e[e.BCM_SKIP=0]="BCM_SKIP",e[e.BCM_REV=2147483648]="BCM_REV"}(me||(me={})),function(e){e[e.BF2_NULL=0]="BF2_NULL",e[e.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",e[e.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",e[e.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",e[e.BF2_POSTNET=2097152]="BF2_POSTNET",e[e.BF2_PLANET=4194304]="BF2_PLANET",e[e.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",e[e.BF2_RM4SCC=16777216]="BF2_RM4SCC",e[e.BF2_DOTCODE=2]="BF2_DOTCODE",e[e.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",e[e.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",e[e.BF2_PHARMACODE=12]="BF2_PHARMACODE",e[e.BF2_ALL=4294967295]="BF2_ALL"}(ve||(ve={})),function(e){e[e.BM_AUTO=1]="BM_AUTO",e[e.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",e[e.BM_SKIP=0]="BM_SKIP",e[e.BM_THRESHOLD=4]="BM_THRESHOLD",e[e.BM_REV=2147483648]="BM_REV"}(ye||(ye={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(Se||(Se={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(we||(we={})),function(e){e[e.CCM_AUTO=1]="CCM_AUTO",e[e.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",e[e.CCM_SKIP=0]="CCM_SKIP",e[e.CCM_REV=2147483648]="CCM_REV"}(be||(be={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(Ce||(Ce={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(xe||(xe={})),function(e){e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(Te||(Te={})),function(e){e[e.DRM_AUTO=1]="DRM_AUTO",e[e.DRM_GENERAL=2]="DRM_GENERAL",e[e.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",e[e.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",e[e.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",e[e.DRM_SKIP=0]="DRM_SKIP",e[e.DRM_REV=2147483648]="DRM_REV"}(Ie||(Ie={})),function(e){e[e.DPMCRM_AUTO=1]="DPMCRM_AUTO",e[e.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",e[e.DPMCRM_SKIP=0]="DPMCRM_SKIP",e[e.DPMCRM_REV=2147483648]="DPMCRM_REV"}(Ae||(Ae={})),function(e){e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_REV=2147483648]="GTM_REV"}(Ee||(Ee={})),function(e){e[e.IPM_AUTO=1]="IPM_AUTO",e[e.IPM_GENERAL=2]="IPM_GENERAL",e[e.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",e[e.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",e[e.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",e[e.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",e[e.IPM_SKIP=0]="IPM_SKIP",e[e.IPM_REV=2147483648]="IPM_REV"}(Oe||(Oe={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(De||(De={})),function(e){e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_REV=2147483648]="LM_REV"}(Re||(Re={})),function(e){e[e.PDFRM_RASTER=1]="PDFRM_RASTER",e[e.PDFRM_AUTO=2]="PDFRM_AUTO",e[e.PDFRM_VECTOR=4]="PDFRM_VECTOR",e[e.PDFRM_REV=2147483648]="PDFRM_REV"}(Me||(Me={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(Le||(Le={})),function(e){e[e.RPM_AUTO=1]="RPM_AUTO",e[e.RPM_GENERAL=2]="RPM_GENERAL",e[e.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",e[e.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",e[e.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",e[e.RPM_SKIP=0]="RPM_SKIP",e[e.RPM_REV=2147483648]="RPM_REV"}(Fe||(Fe={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(Pe||(Pe={})),function(e){e[e.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",e[e.RT_RAW_TEXT=1]="RT_RAW_TEXT",e[e.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",e[e.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(ke||(ke={})),function(e){e[e.SUM_AUTO=1]="SUM_AUTO",e[e.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",e[e.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",e[e.SUM_SKIP=0]="SUM_SKIP",e[e.SUM_REV=2147483648]="SUM_REV"}(Be||(Be={})),function(e){e[e.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",e[e.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",e[e.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",e[e.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",e[e.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",e[e.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(Ne||(Ne={})),function(e){e[e.TFM_AUTO=1]="TFM_AUTO",e[e.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",e[e.TFM_SKIP=0]="TFM_SKIP",e[e.TFM_REV=2147483648]="TFM_REV"}(je||(je={})),function(e){e[e.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",e[e.TROM_POSITION=2]="TROM_POSITION",e[e.TROM_FORMAT=4]="TROM_FORMAT",e[e.TROM_SKIP=0]="TROM_SKIP",e[e.TROM_REV=2147483648]="TROM_REV"}(Ve||(Ve={})),function(e){e[e.TDM_AUTO=1]="TDM_AUTO",e[e.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",e[e.TDM_SKIP=0]="TDM_SKIP",e[e.TDM_REV=2147483648]="TDM_REV"}(Ue||(Ue={}));export{L as BarcodeReader,_e as BarcodeScanner,pe as EnumBarcodeColourMode,me as EnumBarcodeComplementMode,v as EnumBarcodeFormat,ve as EnumBarcodeFormat_2,ye as EnumBinarizationMode,Se as EnumClarityCalculationMethod,we as EnumClarityFilterMode,be as EnumColourClusteringMode,Ce as EnumColourConversionMode,xe as EnumConflictMode,Ae as EnumDPMCodeReadingMode,Te as EnumDeblurMode,Ie as EnumDeformationResistingMode,p as EnumErrorCode,Ee as EnumGrayscaleTransformationMode,m as EnumIMResultDataType,_ as EnumImagePixelFormat,Oe as EnumImagePreprocessingMode,De as EnumIntermediateResultSavingMode,y as EnumIntermediateResultType,Re as EnumLocalizationMode,Me as EnumPDFReadingMode,Le as EnumQRCodeErrorCorrectionLevel,Fe as EnumRegionPredetectionMode,Pe as EnumResultCoordinateType,ke as EnumResultType,Be as EnumScaleUpMode,Ne as EnumTerminatePhase,je as EnumTextFilterMode,Ve as EnumTextResultOrderMode,Ue as EnumTextureDetectionMode}; + */const j="undefined"==typeof self;let V,U,G,W,H;if("undefined"!=typeof navigator&&(V=navigator,U=V.userAgent,G=V.platform,W=V.mediaDevices),!j){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:V.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:G,search:"Win"},Mac:{str:G},Linux:{str:G}};let i="unknownBrowser",r=0,n="unknownOS";for(let t in e){const n=e[t]||{};let s=n.str||U,o=n.search||t,a=n.verStr||U,h=n.verSearch||t;if(h instanceof Array||(h=[h]),-1!=s.indexOf(o)){i=t;for(let e of h){let t=a.indexOf(e);if(-1!=t){r=parseFloat(a.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let r=i.str||U,s=i.search||e;if(-1!=r.indexOf(s)){n=e;break}}"Linux"==n&&-1!=U.indexOf("Windows NT")&&(n="HarmonyOS"),H={browser:i,version:r,OS:n}}j&&(H={browser:"ssr",version:0,OS:"ssr"});const Y="undefined"!=typeof WebAssembly&&U&&!(/Safari/.test(U)&&!/Chrome/.test(U)&&/\(.+\s11_2_([2-6]).*\)/.test(U)),X=!("undefined"==typeof Worker),z=!(!W||!W.getUserMedia),Z=async()=>{let e=!1;if(z)try{(await W.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===H.browser&&H.version>66||"Safari"===H.browser&&H.version>13||"OPR"===H.browser&&H.version>43||"Edge"===H.browser&&H.version;const K=(()=>{if(!j&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})();class J{constructor(e,t){this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,this._setFabricObject(e),this._mediaType=e.type,this.styleSelector="default",this.styleId=t}get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}_setFabricObject(e){this._fabricObject=e,this._fabricObject.on("selected",(()=>{this.styleSelector="selected"})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.styleSelector="selected":this.styleSelector="default","textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),e.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}_on(e,t){if(!t)return;const i=e.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${e}' does not exist.`);let n=r.get(t);n||(n=e=>{const i=e.e;if(!i)return void(t&&t.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let e,t,n,s;const o=i.target.getBoundingClientRect();e=o.left,t=o.top,n=e+window.scrollX,s=t+window.scrollY;const a=this._drawingLayer.fabricCanvas.lowerCanvasEl.width,h=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,l=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),c=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),u=l/c,d=a/h,f=this._drawingLayer._getObjectFit();let g,_,p,m,v=1;if("contain"===f)u0?i-1:r,$),actionName:"modifyPolygon",pointIndex:i}),e}),{})}_extendSet(e,t){if("vertices"===e){const e=this._fabricObject;if(e.group){const i=e.group;e.points=t.map((e=>({x:e.x-i.left-i.width/2,y:e.y-i.top-i.height/2}))),i.addWithUpdate()}else e.points=t;const i=e.points.length-1;return e.controls=e.points.reduce((function(e,t,r){return e["p"+r]=new N.Control({positionHandler:q,actionHandler:ee(r>0?r-1:i,$),actionName:"modifyPolygon",pointIndex:r}),e}),{}),e._setPositionDimensions({}),!0}}_extendGet(e){if("vertices"===e){const e=[],t=this._fabricObject;if(t.selectable&&!t.group)for(let i in t.oCoords)e.push({x:t.oCoords[i].x,y:t.oCoords[i].y});else for(let i of t.points){let r=i.x-t.pathOffset.x,n=i.y-t.pathOffset.y;const s=N.util.transformPoint({x:r,y:n},t.calcTransformMatrix());e.push({x:s.x,y:s.y})}return e}}}const ie=e=>{let t=(e=>e.split("\n").map((e=>e.split("\t"))))(e);return(e=>{for(let t=0;;t++){let i=-1;for(let r=0;ri&&(i=n.length)}if(-1===i)break;for(let r=0;r=e[r].length-1)continue;let n=" ".repeat(i+2-e[r][t].length);e[r][t]=e[r][t].concat(n)}}})(t),(e=>{let t="";for(let i=0;im?(g=d,_=d/p,{x:n.x*i.width,y:(n.y-(f-_)/2)*i.width}):(g=f*p,_=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?p>m?{x:(c-i.height*d)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(u-i.width*f)/2+n.y*i.width}:{x:n.x*i.width,y:n.y*i.height}}return i={width:1,height:1},{x:n.x*i.width,y:n.y*i.height}},N.Canvas.prototype._onTouchStart=function(e){var t=this.findTarget(e);!this.allowTouchScrolling&&e.cancelable&&e.preventDefault&&e.preventDefault(),t&&e.cancelable&&e.preventDefault&&e.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(e)),this.__onMouseDown(e),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();N.util.addListener(N.document,"touchend",this._onTouchEnd,{passive:!1}),N.util.addListener(N.document,"touchmove",this._onMouseMove,{passive:!1}),N.util.removeListener(i,r+"down",this._onMouseDown)},N.Textbox.prototype._wrapLine=function(e,t,i,r){const n=e.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!n||!n.length);var o=0,a=this.splitByGrapheme||s,h=[],l=[],c=a?N.util.string.graphemeSplit(e):e.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,_=0,p=0,m=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!m?(h.push(l),l=[],o=g,m=!0):o+=v,m||a||l.push(f),l=l.concat(u),_=a?0:this._measureWord([f],t,d),d++,m=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class ne{constructor(e,t,i,r){let n,s;switch(this.mapMediaType_Style=new Map,this.mode="viewer",this.onSelectionChange=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,e.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=e.getFabricCanvas():(this.fabricCanvas=new N.Canvas(e,Object.assign(r,{allowTouchScrolling:!0})),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(e){const t=e.selected,i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(e){const t=this.getActiveObjects(),i=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!i.includes(t)&&i.push(t)}for(let e of i){const i=[];for(let r of t){const t=r.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{const t=[];for(let r of i)e.hasDrawingItem(r)&&t.push(r);t.length>0&&e.onSelectionChange&&e.onSelectionChange([],t)}),0)}})),this.fabricCanvas.on("selection:updated",(function(e){const t=e.selected,i=e.deselected,r=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of i){const t=e.getDrawingItem()._drawingLayer;t&&!r.includes(t)&&r.push(t)}for(let e of r){const r=[],n=[];for(let i of t){const t=i.getDrawingItem();t._drawingLayer===e&&r.push(t)}for(let t of i){const i=t.getDrawingItem();i._drawingLayer===e&&n.push(i)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(r,n)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",e.getFabricCanvas=()=>this.fabricCanvas),this.id=t,this._mapDrawingStyles=i,t){case 1:n=i.get(1),s=i.get(5);break;case 2:n=i.get(2),s=i.get(6);break;case 3:n=i.get(3),s=i.get(7);break;default:n=i.get(4),s=i.get(8)}for(let e of J.arrMediaTypes)this.mapMediaType_Style.set(e,{default:n,selected:s})}getId(){return this.id}_getDrawingStyle(e,t){if("number"!=typeof e)throw new Error("Invalid style id.");const i=this._mapDrawingStyles.get(e);return i?t?JSON.parse(JSON.stringify(i)):i:null}setVisible(e){if(e){for(let e of this._arrFabricObject)e.visible=!0;this._visible=!0}else{for(let e of this._arrFabricObject)e.visible=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(e){return e.styleId?e.styleId:this.mapMediaType_Style.get(e._mediaType)[e.styleSelector].styleId}_getItemCurrentStyle(e){if(e.styleId)return this._getDrawingStyle(e.styleId);return e._mapStyle.get(e.styleSelector)||null}_changeMediaTypeCurStyleInStyleSelector(e,t,i,r){let n;switch(e){case"rect":n=this.fabricCanvas.getObjects("rect");break;case"arc":n=this.fabricCanvas.getObjects("circle");break;case"polygon":n=this.fabricCanvas.getObjects("polygon");break;case"image":n=this.fabricCanvas.getObjects("image");break;case"text":n=this.fabricCanvas.getObjects("textbox");break;case"line":n=this.fabricCanvas.getObjects("line");break;case"path":n=this.fabricCanvas.getObjects("path")}for(let e of n){if(!this._arrFabricObject.includes(e))continue;const r=e.getDrawingItem();r.styleSelector===t&&this._changeItemStyle(r,i,!0)}r||this.fabricCanvas.renderAll()}_changeItemStyle(e,t,i){if(!e||!t)return;const r=e._getFabricObject();"number"==typeof e.styleId&&(t=this._getDrawingStyle(e.styleId)),r.strokeWidth=t.lineWidth,"fill"===t.paintMode?(r.fill=t.fillStyle,r.stroke=t.fillStyle):"stroke"===t.paintMode?(r.fill="transparent",r.stroke=t.strokeStyle):"strokeAndFill"===t.paintMode&&(r.fill=t.fillStyle,r.stroke=t.strokeStyle),r.fontFamily&&(r.fontFamily=t.fontFamily),r.fontSize&&(r.fontSize=t.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(e,t,i){if(!e||!t)return;const r=e.getChildItems();if("add"===i){if(r.includes(t))return;const i=t._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");t._zIndex=null}else{let i;if(t.styleId)i=this._getDrawingStyle(t.styleId);else{i=this.mapMediaType_Style.get(t._mediaType)[e.styleSelector];const r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected,!0)},n=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default,!0)};t._on("selected",r),t._on("deselected",n),t._funcChangeStyleToSelected=r,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,i,!0)}e._fabricObject.addWithUpdate(t._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(t))return;t._zIndex=null,t._drawingLayer=null,t._drawingLayerId=null,t._off("selected",t._funcChangeStyleToSelected),t._off("deselected",t._funcChangeStyleToDefault),t._funcChangeStyleToSelected=null,t._funcChangeStyleToDefault=null,e._fabricObject.removeWithUpdate(t._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(e,t){let i=e._getFabricObject();const r=this.fabricCanvas.getObjects();let n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===e._mediaType){n=e.getChildItems();for(let e of n)if(e._drawingLayer&&e._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(t&&"object"==typeof t&&!Array.isArray(t))for(let e in t)i.set(e,t[e]);if(n){for(let e of n){const t=this.mapMediaType_Style.get(e._mediaType);for(let i of J.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)s=this._getDrawingStyle(e.styleId);else{s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e._on("selected",i),e._on("deselected",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of J.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)s=this._getDrawingStyle(e.styleId);else{s=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected)},r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default)};e._on("selected",i),e._on("deselected",r),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=r}this._changeItemStyle(e,s)}e._zIndex=this.id,e._drawingLayer=this,e._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let t=0;t{for(let t of this._arrDrawingLayer)if(t.getId()===e)return!0;return!1};if(void 0===t){for(let e=100;;e++)if(!i(e)){t=e;break}}else if(i(t))throw new Error("Existed drawing layer id.");const r=new ne(e,t,this._mapDrawingStyles,{enableRetinaScaling:!1});return r._manager=this,this._arrDrawingLayer.push(r),this._switchPointerEvent(),r}deleteDrawingLayer(e){const t=this.getDrawingLayer(e);if(!t)return;const i=this._arrDrawingLayer;t.dispose(),i.splice(i.indexOf(t),1),this._switchPointerEvent()}clearDrawingLayers(){for(let e of this._arrDrawingLayer)e.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(e){for(let t of this._arrDrawingLayer)if(t.getId()===e)return t;return null}getDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const e=this._arrDrawingLayer[0].fabricCanvas.getActiveObjects(),t=[];for(let i of e)t.push(i.getDrawingItem());return t}setDimensions(e,t){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(e,t)}setObjectFit(e){for(let t of this._arrDrawingLayer)t&&t._setObjectFit(e)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(e){this._arrDrawingLayer.length&&(this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.display=e?"block":"none")}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let e of this._arrDrawingLayer)e.getMode()}}class oe{constructor(e){this._controlTarget=null,this._arrUsers=[],this._mapAction_UserArgs=new Map,this._mapProperty_UserValue=new Map,this._mapAction_Callbacks=new Map,this._controlTarget=e}setControlTarget(e){this._controlTarget=e}getControlTarget(){return this._controlTarget}register(e){this._arrUsers.includes(e)||this._arrUsers.push(e)}logout(e){const t=this._arrUsers.indexOf(e);-1!==t&&(this.clearUserDisiredAction({user:e}),this.clearUserDisiredValue({user:e}),this._arrUsers.splice(t,1))}getRegisteredUsers(){return this._arrUsers}ifUserExisted(e){return this._arrUsers.includes(e)}setDisiredValue(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");r&&(this._controlTarget[t]=i),this._mapProperty_UserValue.get(t)?this._mapProperty_UserValue.get(t).set(e,i):this._mapProperty_UserValue.set(t,new Map([[e,i]]))}clearUserDisiredValue(e){if(e&&(e.user||e.property)){if(e.property&&e.user){const t=this._mapProperty_UserValue.get(e.property);if(!t)return;t.delete(e.user)}else if(e.property)this._mapProperty_UserValue.delete(e.property);else if(e.user)for(let t of this._mapProperty_UserValue.values())t.delete(e.user)}else this._mapProperty_UserValue=new Map}getValue(e){if(!this._controlTarget)throw new Error("Control target is not set.");return this._controlTarget[e]}getPropertyDisiredValue(e){if(this._mapProperty_UserValue.get(e)){const t=[],i=this._mapProperty_UserValue.get(e);for(let e of i.values())t.push(e);return t}return null}setDisiredAction(e,t,i,r){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");return i||(i=[]),r?this._controlTarget[t](...i):(this._mapAction_UserArgs.get(t)?this._mapAction_UserArgs.get(t).set(e,i):this._mapAction_UserArgs.set(t,new Map([[e,i]])),this._render(t))}clearUserDisiredAction(e){if(e&&(e.user||e.actionName)){if(e.actionName&&e.user){const t=this._mapAction_UserArgs.get(e.actionName);if(!t)return;t.delete(e.user)}else if(e.actionName)this._mapAction_UserArgs.delete(e.actionName);else if(e.user)for(let t of this._mapAction_UserArgs.values())t.delete(e.user);this.render()}else this._mapAction_UserArgs=new Map}addCallback(e,t){const i=this._mapAction_Callbacks.get(e);i?i.push(t):this._mapAction_Callbacks.set(e,[t])}removeCallback(e,t){const i=this._mapAction_Callbacks.get(e);if(!i)return;const r=i.indexOf(t);-1!==r&&i.splice(r,1)}clearCallback(e){e?this._mapAction_Callbacks.delete(e):this._mapAction_Callbacks.clear()}_fireCallback(e){const t=this._mapAction_Callbacks.get(e);if(t)for(let e of t){if(!e)return;setTimeout(e.bind(this._controlTarget),0)}}_render(e){const t=this._mapAction_UserArgs.get(e);if(!t)throw new Error("Unrecorded action.");if(t.size===this._arrUsers.length){let i=[];for(let e of t.values())e.length>0&&(i=e);if(this._controlTarget[e]){const t=this._controlTarget[e](...i);return this._mapAction_UserArgs.delete(e),this._fireCallback(e),t}}}render(e){if(e)return this._render(e);for(let e of this._mapAction_UserArgs.keys())this._render(e)}}class ae{static multiply(e,t){const i=[];for(let r=0;r<3;r++){const n=t.slice(3*r,3*r+3);for(let t=0;t<3;t++){const r=[e[t],e[t+3],e[t+6]].reduce(((e,t,i)=>e+t*n[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,t,i){return ae.multiply(e,[1,0,0,0,1,0,t,i,1])}static rotate(e,t){var i=Math.cos(t),r=Math.sin(t);return ae.multiply(e,[i,-r,0,r,i,0,0,0,1])}static scale(e,t,i){return ae.multiply(e,[t,0,0,0,i,0,0,0,1])}}var he;!function(e){e.GREY="grey",e.GREY32="grey32",e.RGBA="rgba",e.RBGA="rbga",e.GRBA="grba",e.GBRA="gbra",e.BRGA="brga",e.BGRA="bgra"}(he||(he={}));const le=(e,t,i,r)=>{let n=t+Math.round((e-t)/i)*i;return r&&(n=Math.min(n,r)),n};class ce{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this._predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this._mapCameraResolutions=new Map,this._bWebGLSupported=!0,this.extraBindings=[],this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode&&!this.getDrawingLayers().some((e=>"editor"==e.getMode()))){if(!this._singleFrameModeIpt){const e=document.createElement("input");this._singleFrameModeIpt=e,e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.addEventListener("change",(async()=>{const t=e.files[0];e.value="";const i=await(async e=>{let t=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(t=await createImageBitmap(e),t)return t}catch(e){}var r;return t||(i=await(r=e,new Promise(((e,t)=>{let i=URL.createObjectURL(r),n=new Image;n.dbrObjUrl=i,n.src=i,n.onload=()=>{e(n)},n.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})(t),r=i instanceof HTMLImageElement?i.naturalWidth:i.width,n=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=n;const s=e=>{const t=Date.now();if(0===r||0===n)return null;if(e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");const i=this._scanRegion,s=this.getFrameSize(r,n,i,this.maxCvsSideLength);if(!s)return null;let o=!0;r===s.sWidth&&n===s.sHeight&&(o=!1);const a=this.mapPixelFormatString_Enum.get(this.framePixelFormat.toLowerCase()),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:s.sx,sy:s.sy,width:s.dWidth,height:s.dHeight,colorMode:null,pixelFormat:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:s.sWidth,_sHeight:s.sHeight,_bUseWebGL:null},l=this._getImageData(e,r,n,s,null,{pixelFormat:a});if(!l)return null;const c=Date.now();return h.data=l.data,h.pixelFormat=h.colorMode=l.pixelFormat,h._bUseWebGL=l._bUseWebGL,h.timeSpent=c-t,h.timeStamp=c,l.pixelFormat===he.GREY?h.stride=h.width:h.stride=4*h.width,h};(e=>{let t=this._cvsSingleFrameMode;if(!t){if(t=document.createElement("canvas"),!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(t),t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit="contain",t.style.pointerEvents="none",this._cvsSingleFrameMode=t}t.width==r&&t.height==n||(t.width=r,t.height=n);const i=t.getContext("2d");i.clearRect(0,0,t.width,t.height),i.drawImage(e,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);let o;this._updateDrawingLayersSize();try{o=s(i)}catch(e){throw e}const a=this.mapCameraEvents.get("singleframeacquired");for(let e of a)if(e)try{const t={data:new Uint8Array(o.data),region:JSON.parse(JSON.stringify(o.region)),sx:o.sx,sy:o.sy,width:o.width,height:o.height,stride:o.stride,colorMode:o.colorMode,pixelFormat:o.pixelFormat,timeSpent:o.timeSpent,timeStamp:o.timeStamp,isCropped:o.isCropped,toCanvas:o.toCanvas,_sWidth:o._sWidth,_sHeight:o._sHeight,_bUseWebGL:o._bUseWebGL};await e.apply(this,[t])}catch(e){console.error(e)}})),e.style.position="fixed",e.style.left="-1px",e.style.top="-1px",e.style.width="1px",e.style.height="1px",e.style.backgroundColor="transparent",e.style.color="transparent",document.body.appendChild(e)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._framePixelFormat=void 0,this._defaultFramePixelFormat="rgba",this.mapPixelFormatString_Enum=new Map([["grey",he.GREY],["grey32",he.GREY32],["rgba",he.RGBA],["rbga",he.RBGA],["grba",he.GRBA],["gbra",he.GBRA],["brga",he.BRGA],["bgra",he.BGRA]]),this.shaderPixelFormat=he.RGBA,this.maxVideoCvsLength=3,this._reusedCvs=null,this._reusedWebGLCvs=null,this._tempDataContainer=null,this._webGLTexture=null,this._webGLProgramInfo=null,this._webGLBuffers=null,this._softwareScale=1,this._scaleCenter={x:0,y:0},this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,_focusArea:null},this._tapFocusEnabled=!0,this._focusSupported=!0,this._tapDoFocus=async e=>{if(this._touchMoved)return void(this._touchMoved=!1);if(!this._tapFocusEnabled)return;if(!this._bOpen)return;if(this.singleFrameMode)return;if(!this._video||this._video.paused)return;if(!this._videoTrack)return;if(!this._focusSupported)return;if(this.getDrawingLayers().some((e=>"editor"==e.getMode())))return;if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let t,i,r,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),e instanceof MouseEvent)t=e.clientX,i=e.clientY;else{if(!(e instanceof TouchEvent))throw new Error("Unknown event type.");if(!e.changedTouches.length)return;t=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY}const s=this.getVideoFit(),o=this._video.videoWidth,a=this._video.videoHeight,h=this._elContainer.getBoundingClientRect(),l=h.left,c=h.top,u=window.getComputedStyle(this._elContainer),d=parseFloat(u.width),f=parseFloat(u.height),g=d/f,_=o/a;let p=1;if("contain"===s)_>g?(p=d/o,r=(t-l)/p,n=(i-c-(f-d/_)/2)/p):(p=f/a,n=(i-c)/p,r=(t-l-(d-f*_)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");_>g?(p=f/a,n=(i-c)/p,r=(t-l+(f*_-d)/2)/p):(p=d/o,r=(t-l)/p,n=(i-c+(d/_-f)/2)/p)}const m={x:r+"px",y:n+"px"},v=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=v;await this._setLocalFocus(m,v,y,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance),this._focusParameters.taskBackToContinous=setTimeout((()=>{this._videoTrack&&this._videoTrack.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime)},this._touchMoved=!1,this._touchMoveEvent=()=>{this._touchMoved=!0},this._recordedStates={},this.playCallbackInfo=null,this._toCanvas=function(){const e=document.createElement("canvas");let t;if(e.width=this.width,e.height=this.height,"grey"===(this.pixelFormat||this.colorMode)){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}await this.setResolution(e,t),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this.singleFrameMode)if("visible"===document.visibilityState){if(ce._onLog&&ce._onLog("DCE: document visible."),this._bOpen&&this._vc_bPlayingVideoBeforeHide)if(this.videoSrc)this._video.play();else if(this._video.srcObject){const e=this._video.srcObject.getTracks()[0];this._video.srcObject.active&&e&&!e.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(ce._onLog&&ce._onLog("DCE: document hidden."),["iPhone","iPad"].includes(H.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let e of this._arrScanRegionOverlays)e&&(e.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&(e.style.display="",this._updateScanRegionOverlay(e));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null}static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:Y,worker:X,getUserMedia:z,camera:await Z(),browser:H.browser,version:H.version,OS:H.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");ce._engineResourcePath=(e=>{if(null==e&&(e="./"),!j){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(e){let t;try{t=window[e];const i="__storage_test__";return t.setItem(i,i),t.removeItem(i),!0}catch(e){return e instanceof DOMException&&(22===e.code||1014===e.code||"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&t&&0!==t.length}}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"data"in e&&"region"in e&&"sx"in e&&"sy"in e&&"width"in e&&"height"in e&&("colorMode"in e||"pixelFormat"in e)&&"timeSpent"in e&&"timeStamp"in e&&"isCropped"in e&&"toCanvas"in e&&"_sWidth"in e&&"_sHeight"in e&&"_bUseWebGL"in e}static async testCameraAccess(){try{if(!navigator||!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return{ok:!1,message:"Insecure context."};(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()}))}catch(e){if("OverconstrainedError"===e.name||"NotFoundError"===e.name)return{ok:!1,message:"No camera detected."};if("NotAllowedError"===e.name)return{ok:!1,message:"No permission to access camera."};if("AbortError"===e.name)return{ok:!1,message:"Some problem occurred which prevented the device from being used."};if("NotReadableError"===e.name)return{ok:!1,message:"A hardware error occurred."};if("SecurityError"===e.name)return{ok:!1,message:"User media support is disabled."};throw e}return{ok:!0,message:"Successfully accessed the camera."}}set maxCvsSideLength(e){if(e<=0)throw new Error("Invalid value.");this._maxCvsSideLength=e}get maxCvsSideLength(){if(void 0!==this._maxCvsSideLength)return this._maxCvsSideLength;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxCvsSideLength");if(e&&1===e.length)return e[0]}return this._defaultMaxCvsSideLength}static set defaultUIElementURL(e){ce._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=ce._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",ce.engineResourcePath)}getUIElement(){return this.UIElement}async setUIElement(e){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof e||e instanceof String){if(!e.trim().startsWith("<")){let t=await fetch(e);if(!t.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+t.statusText);e=await t.text()}if(!e.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let t=document.createElement("div");t.innerHTML=e;for(let e=0;e100||e.regionTop>100||e.regionRight>100||e.regionBottom>100)))}set scanRegion(e){if(!this._checkValidRegion(e))throw new Error("Invalid region.");this._scanRegion=JSON.parse(JSON.stringify(e)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e)}setScanRegion(e){this.scanRegion=e}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}_calculateCvsSize(){if(!this._bOpen)return null;let e,t,i;if(this.singleFrameMode)e=this._imgWidth,t=this._imgHeight,i="contain";else{if(!this._video)return null;e=this._video.videoWidth,t=this._video.videoHeight,i=this.getVideoFit()}return{width:e,height:t,objectFit:i}}addScanRegionOverlayCanvas(){this._assertOpen();const e=document.createElement("canvas");if(this._updateScanRegionOverlay(e),!this._scanRegionOverlayContainer){const e=document.createElement("div");if(this._scanRegionOverlayContainer=e,e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e.style.overflow="hidden",e.style.pointerEvents="none",this._layerBaseCvs)this._layerBaseCvs.parentElement.after(e);else if(this._cvsScanRegion)this._cvsScanRegion.after(e);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(e);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e)}this._recordedStates.overlayShow=!0}return this._scanRegionOverlayContainer.append(e),this._arrScanRegionOverlays.push(e),e}removeScanRegionOverlayCanvas(e){const t=this._arrScanRegionOverlays.indexOf(e);-1!==t&&(e.remove(),this._arrScanRegionOverlays.splice(t,1))}_updateScanRegionOverlay(e){if(!e)return;const t=this._calculateCvsSize();if(!t)return;const{width:i,height:r,objectFit:n}=t;if(i<=0||r<=0)return e.width=0,void(e.height=0);const s=this._getRegionInPixels(i,r,this._scanRegion),o=this.getFrameSize(i,r,this._scanRegion,this.maxCvsSideLength),a=o.dWidth,h=o.dHeight;e.width==a&&e.height==h||(e.width=a,e.height=h);const l=window.getComputedStyle(this._elContainer),c=parseFloat(l.width),u=parseFloat(l.height),d=c/u,f=i/r;let g,_,p,m,v=1;"contain"===n?(f>d?(v=c/i,g=0,_=(u-r*v)/2):(v=u/r,g=(c-i*v)/2,_=0),g+=s.regionLeft*v,_+=s.regionTop*v,p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):"cover"===n?(f>d?(v=u/r,g=s.regionLeft*v-(i*v-c)/2,_=s.regionTop*v):(v=c/i,g=s.regionLeft*v,_=s.regionTop*v-(r*v-u)/2),p=(s.regionRight-s.regionLeft)*v,m=(s.regionBottom-s.regionTop)*v):(g=0,_=0,p=0,m=0),e.style.position="absolute",e.style.left=g+"px",e.style.top=_+"px",e.style.width=p+"px",e.style.height=m+"px"}showScanRegionOverlays(){this._scanRegionOverlayContainer&&("none"==this._scanRegionOverlayContainer.style.display&&(this._scanRegionOverlayContainer.style.display=""),this._recordedStates.overlayShow=!0)}hideScanRegionOverlays(){this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none",this._recordedStates.overlayShow=!1)}setViewDecorator(e,t){if(!e)return void(this._cvsViewDecorator&&(this._cvsViewDecorator.remove(),this._cvsViewDecorator=null));if(!t)throw new Error("Invalid area.");this._assertOpen();let i=[];if("string"==typeof e?i.push(e):Array.isArray(e)&&(i=JSON.parse(JSON.stringify(e))),!this._cvsViewDecorator){if(this._cvsViewDecorator=document.createElement("canvas"),this._scanRegionOverlayContainer)this._scanRegionOverlayContainer.after(this._cvsViewDecorator);else if(this._layerBaseCvs)this._layerBaseCvs.parentElement.after(this._cvsViewDecorator);else if(this._cvsScanRegion)this._cvsScanRegion.after(this._cvsViewDecorator);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(this._cvsViewDecorator);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(this._cvsViewDecorator);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(this._cvsViewDecorator)}this._recordedStates.decoratorShow=!0}this._decoratorArea=JSON.parse(JSON.stringify(t)),this._decoratorType.length=0;const r=["rectangle","focus"],n=["crossline","crosshair"];let s=!1,o=!1;for(let e of i)e=e.toLowerCase(),r.includes(e)&&!s&&(s=!0,this._decoratorType.push(e)),n.includes(e)&&!o&&(o=!0,!this._decoratorType.includes(e)&&this._decoratorType.push(e));this._updateViewDecorator()}getViewDecorator(){return{type:JSON.parse(JSON.stringify(this._decoratorType)),area:JSON.parse(JSON.stringify(this._decoratorArea)),canvas:this._cvsViewDecorator}}showViewDecorator(){this._cvsViewDecorator&&("none"==this._cvsViewDecorator.style.display&&(this._cvsViewDecorator.style.display=""),this._recordedStates.decoratorShow=!0)}hideViewDecorator(){this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none",this._recordedStates.decoratorShow=!1)}setViewDecoratorLineWidth(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("lineWidth"))throw new Error(`It is not allowed to change the property 'lineWidth' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].lineWidth=t,this._updateViewDecorator()}setViewDecoratorStrokeStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("strokeStyle"))throw new Error(`It is not allowed to change the property 'strokeStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].strokeStyle=t,this._updateViewDecorator()}setViewDecoratorFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("fillStyle"))throw new Error(`It is not allowed to change the property 'fillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].fillStyle=t,this._updateViewDecorator()}setViewDecoratorMaskFillStyle(e,t){if("string"!=typeof e)throw new Error("The 'type' should be a string.");if(e=e.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(e))throw new Error(`The type of '${e}' doesn't exist.`);if(!this._viewDecoratorInfo[e].hasOwnProperty("maskFillStyle"))throw new Error(`It is not allowed to change the property 'maskFillStyle' when the decorator type is '${e}'.`);this._viewDecoratorInfo[e].maskFillStyle=t,this._updateViewDecorator()}_updateViewDecorator(){if(!this._bOpen)return;if(!this._cvsViewDecorator||!this._decoratorArea)return;let e;if(this.singleFrameMode)e="contain";else{if(!this._video)return;e=this.getVideoFit()}const t=this._cvsViewDecorator;t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.objectFit=e,t.style.pointerEvents="none";const i=this.getVisibleRegion(!0),r=i.regionRight-i.regionLeft,n=i.regionBottom-i.regionTop;if(t.width==r&&t.height==n||(t.width=r,t.height=n),r<=0||n<=0)return;const s=t.getContext("2d");s.clearRect(0,0,t.width,t.height);const o=this._decoratorArea.x/100*r,a=this._decoratorArea.y/100*n,h=this._decoratorArea.width/100*r,l=this._decoratorArea.height/100*n;for(let e of this._decoratorType){if("rectangle"===e){s.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,s.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const e=s.lineWidth/2;s.strokeRect(Math.round(o-e),Math.round(a-e),Math.round(h+s.lineWidth),Math.round(l+s.lineWidth))}if("focus"===e){s.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,s.fillRect(0,0,t.width,t.height),s.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.fillStyle=this._viewDecoratorInfo.focus.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),s.lineWidth=this._viewDecoratorInfo.focus.lineWidth,s.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const e=s.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];s.beginPath();for(let e=0;e{const e=parseFloat(window.getComputedStyle(this._elContainer).width),t=parseFloat(window.getComputedStyle(this._elContainer).height);let s,o={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?e/tthis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){if(void 0!==this._maxNumberOfFramesInBuffer)return this._maxNumberOfFramesInBuffer;if(this._controler){const e=this._controler.getPropertyDisiredValue("maxNumberOfFramesInBuffer");if(e&&1===e.length)return e[0]}return this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(e){this._refreshInterval=e}get refreshInterval(){if(void 0!==this._refreshInterval)return this._refreshInterval;if(this._controler){const e=this._controler.getPropertyDisiredValue("refreshInterval");if(e&&1===e.length)return e[0]}return this._defaultRefreshInterval}static async createInstance(e){let t=new ce;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,ce.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{ce.onWarning&&ce.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{ce.onWarning&&ce.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),t._drawingLayersManager=new se,t}static async playVideo(e,t,i){return new Promise(((r,n)=>{e||n(new Error("Invalid video element.")),t||n(new Error("Invalid source.")),e.onloadedmetadata=async()=>{e.onloadedmetadata=null,await e.play(),r(e)},"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,void 0!==i&&setTimeout((()=>n(new Error("Failed to play video. Timeout."))),i)}))}static findBestRearCamera(e){if(!e||!e.length)return null;const t=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"];for(let i of e){const e=i.label.toLowerCase();if(e&&t.some((t=>e.includes(t)))&&/\b0(\b)?/.test(e))return i.deviceId}return["Android","HarmonyOS"].includes(H.OS)?e[e.length-1].deviceId:null}async play(e,t,i,r){let n;if(this._video&&this.videoSrc){ce._onLog&&(n=Date.now(),ce._onLog("DCE: start loading static video: "+n));const e=await ce.playVideo(this._video,this.videoSrc,4e3);if(ce._onLog&&ce._onLog("DCE: finish loading static video. Costs: "+(Date.now()-n)),!this._video)return e.pause(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};const t={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};this.playCallbackInfo=JSON.parse(JSON.stringify(t));const i=this.mapCameraEvents.get("played");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[i])}),0)}return this._recordedStates.videoPlaying=!0,t}if(this.singleFrameMode)return r&&r.notTriggerSingleFrameClick||this._clickIptSingleFrameMode(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};if(!this._video)throw new Error("'video' is null or undefined.");const s=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,s{var r;try{this._video&&this._video.srcObject&&this.stop(),ce._onLog&&ce._onLog("DCE: ======before video========");const n=()=>{if(!this._video)throw a&&a.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},s=this.getVideoSettings();let o,a;if("boolean"==typeof s.video&&(s.video={}),e)delete s.video.facingMode,s.video.deviceId={exact:e};else if(s.video.deviceId);else if(this._lastDeviceId)delete s.video.facingMode,s.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&ce.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete s.video.facingMode,s.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),t=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&t&&(s.video.width=e,s.video.height=t)}else if(this.ifSkipCameraInspection);else if(s.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=s.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){o=!0;const e=ce.findBestRearCamera(this._allCameras);e&&(delete s.video.facingMode,s.video.deviceId={ideal:e})}}t&&(s.video.width={ideal:t}),i&&(s.video.height={ideal:i}),ce._onLog&&ce._onLog("DCE: ======try getUserMedia========");let h=[0,500],l=null;const c=async e=>{for(let t of h){t&&await new Promise((e=>setTimeout(e,t))),n();try{ce._onLog&&ce._onLog("DCE: ask "+JSON.stringify(e)),a=await navigator.mediaDevices.getUserMedia(e);break}catch(e){l=e,ce._onLog&&ce._onLog("DCE: "+e.message||e)}}};let u;if(await c(s),a||(ce._onLog&&ce._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(s)),"object"==typeof u.video&&(["iPhone","iPad"].includes(H.OS)?(t>=1280||i>=1280?u.video.width=1280:t>=640||i>=640?u.video.width=640:(t<640||i<640)&&(u.video.width=320),delete u.video.height):o&&!s.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0),ce._onLog&&ce._onLog("DCE: "+u),await c(u)),a||(h=[1e3,2e3],await c(s)),a||await c(u),!a)throw l;const d=()=>{const e=a.getVideoTracks();let t,i;if(e.length&&(t=this._videoTrack=e[0]),this._video&&t){const e=t.getSettings();if(e)for(let r of this._allCameras)if(e.deviceId===r.deviceId){r._checked=!0,r.label=t.label,i=r;break}}this._currentCamera=i};if(await this.getAllCameras(!1),n(),o){d();const e=ce.findBestRearCamera(this._allCameras),t=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;e&&e!=t&&(a.getTracks().forEach((e=>{e.stop()})),h=[0,500,1e3,2e3],await c(s))}ce._onLog&&ce._onLog("DCE: ======play video========"),n(),await ce.playVideo(this._video,a,4e3),n(),ce._onLog&&ce._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=f,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),ce._onLog&&ce._onLog("DCE: got "+f),d(),this._renderSelCameraInfo();const g={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};g.deviceId&&(this._lastDeviceId=g.deviceId,this.ifSaveLastUsedCamera&&ce.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),s.video.width&&s.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(s.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(s.video.height)))));const _=this.mapCameraEvents.get("played");for(let e of _){if(!e)continue;const t=JSON.parse(JSON.stringify(g));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}return this.promisePlay=null,g}catch(e){throw this.promisePlay=null,this._bgLoading&&(this._bgLoading.style.display="none"),"NotFoundError"===e.name&&(DOMException?e=new DOMException("No camera available, please use a device with an accessible camera.",e.name):(e=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),e}})(),ce._onLog&&(n=Date.now(),ce._onLog("DCE: start opening camera: "+n));const o=await this.promisePlay;return ce._onLog&&ce._onLog("DCE: finish opening camera. Costs: "+(Date.now()-n)),this.playCallbackInfo=JSON.parse(JSON.stringify(o)),this._recordedStates.videoPlaying=!0,o}async resume(){this._assertOpen(),this._video&&(await this._video.play(),this._recordedStates.videoPlaying=!0),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&t.classList.contains("dce-opt-gotResolution")?this._optGotRsl=t:!this._btnClose&&t.classList.contains("dce-btn-close")?this._btnClose=t:!this._selMinLtr&&t.classList.contains("dlr-sel-minletter")?(this._selMinLtr=t,this._selMinLtr.options.length||(this._selMinLtr.innerHTML=[this._optGotMinLtr?"":'','','','','','','','','','',''].join(""),this._optGotMinLtr=this._optGotMinLtr||this._selMinLtr.options[0])):!this._optGotMinLtr&&t.classList.contains("dlr-opt-gotMinLtr")&&(this._optGotMinLtr=t);if(this.extraBindings&&this.extraBindings.length)for(let i of this.extraBindings)try{i(t)}catch(e){}}if(!this._video)throw this._unbindUI(),Error(`Can not find the video container element with class '${this.containerClassName}'`);this.singleFrameMode||this.videoSrc?(this.singleFrameMode&&(this._elContainer&&(this._elContainer.addEventListener("click",this._clickIptSingleFrameMode),this._elContainer.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._elContainer&&(["Android","HarmonyOS"].includes(H.OS)?(this._elContainer.addEventListener("touchend",this._tapDoFocus),this._elContainer.addEventListener("touchmove",this._touchMoveEvent)):this._elContainer.addEventListener("click",this._tapDoFocus)),this._selCam&&(this._selCam.style.display="block",this._selCam.addEventListener("change",this._onCameraSelChange)),this._selRsl&&(this._selRsl.style.display="block",this._selRsl.addEventListener("change",this._onResolutionSelChange)),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._bgLoading&&(this._bgLoading.style.display="block")),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&(this._resizeObserver||(this._resizeObserver=new ResizeObserver((e=>{for(let t of e)t.target===this._elContainer&&this._updateLayers()}))),this._elContainer&&this._resizeObserver.observe(this._elContainer)),window.addEventListener("resize",this._updateLayers)}_unbindUI(){this.singleFrameMode?(this._elContainer&&(this._elContainer.removeEventListener("click",this._clickIptSingleFrameMode),this._elContainer.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._elContainer&&(this._elContainer.removeEventListener("click",this._tapDoFocus),this._elContainer.removeEventListener("touchend",this._tapDoFocus),this._elContainer.removeEventListener("touchmove",this._touchMoveEvent)),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._drawingLayersManager.setVisible(!1),this._hideOriginalImageCvs(),this._videoContainer&&this._videoContainer.remove(),this._video=null,this._videoContainer=null,this._elContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._updateLayers)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}async open(e){this.UIElement||await this.setUIElement(ce.defaultUIElementURL),this._bindUI(),e&&this.appendAndShowUI();let t=await this.play();this.bOpen=!0,this._focusParameters.fds=null,this._focusParameters.kTimeout=void 0,this._focusSupported=!0,this._tapFocusEnabled&&!this.singleFrameMode&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,this._focusParameters.fds||(this._focusSupported=!1,this._tapFocusEnabled=!1));const i=this.mapCameraEvents.get("cameraopen");for(let e of i){if(!e)continue;const i=JSON.parse(JSON.stringify(t));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[i])}),0)}return t}close(e){if(!this._video)return;this.stop(),this._hideOriginalImage(!1),this.hideTip(),this._unbindUI(),e&&this.hideUI(),this.stopFetchingLoop(),this.bOpen=!1;const t=this.mapCameraEvents.get("cameraclose");for(let e of t){if(!e)continue;const t={width:0,height:0,deviceId:null};setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}stop(){this._video&&this._video.srcObject&&(ce._onLog&&ce._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((e=>{e.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(ce._onLog&&ce._onLog("DCE: ======stop existing video========"),this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0,this._reusedCvs&&this._reusedCvs.ctx2d&&this._reusedCvs.ctx2d.clearRect(0,0,this._reusedCvs.width,this._reusedCvs.height),this.forceLoseContext()}async getAllCameras(e=!0){let t=(await navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind));if(e&&t&&t.length&&!t[0].deviceId){let e=await navigator.mediaDevices.getUserMedia({video:!0});t=(await navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)),e.getTracks().forEach((e=>{e.stop()}))}const i=[],r=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&r.push(e);for(let e=0;e{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}if(r!==s.width||n!==s.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const e=this.mapCameraEvents.get("resolutionchange");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(s));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return s}getResolution(){if(this._bOpen)return[this._video.videoWidth,this._video.videoHeight];{let e=0,t=0;const i=this.videoSettings.video.width,r=this.videoSettings.video.height;return i&&(e=i.exact||i.ideal||i),r&&(t=r.exact||r.ideal||r),[e,t]}}async setResolution(e,t){let i,r;if(e instanceof Array?(i=e[0],r=e[1]):(i=e,r=t),this.videoSettings.video.width={ideal:i},this.videoSettings.video.height={ideal:r},!this._bOpen||this._video.paused)return null;const n=this._video.videoWidth,s=this._video.videoHeight,o=await this.play(null,i,r);if(n!==o.width||s!==o.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&this._updateScanRegionOverlay(e);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const e=this.mapCameraEvents.get("resolutionchange");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(o));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return o}async getResolutions(e){let t="";const i=(e,t)=>{const i=this._mapCameraResolutions.get(e);if(!i||!i.length)return!1;for(let e of i)if(e[0]===t.width&&e[1]===t.height)return!0;return!1},r=async(e,t,i)=>{const r={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(e){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const e=s[0].getSettings();o={width:e.width,height:e.height}}catch(e){const t=document.createElement("video");t.srcObject=n,o={width:t.videoWidth,height:t.videoHeight},t.srcObject=null}return s.forEach((e=>{e.stop()})),o};if(!this._bOpen){const n=this.videoSettings.video.deviceId;if(!n)return null;if(t=n.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:n.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!t)return null;let s=this._mapCameraResolutions.get(t);if(s&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),s=this._mapCameraResolutions.get(t);for(let e of this._predefinedResolutions){const n=await r(t,e.width,e.height);n&&!i(t,n)&&s.push([n.width,n.height])}return s}if(this._currentCamera){t=this._currentCamera.deviceId;let r=this._mapCameraResolutions.get(t);if(r&&!e)return this._mapCameraResolutions.get(t);this._mapCameraResolutions.set(t,[]),r=this._mapCameraResolutions.get(t);const n=this.getConstraints();for(let e of this._predefinedResolutions){await this._videoTrack.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const n=this._videoTrack.getSettings(),s={width:n.width,height:n.height};i(t,s)||r.push([s.width,s.height])}return await this._videoTrack.applyConstraints(n),r}return null}on(e,t){if(!t)return;const i=this.mapCameraEvents.get(e.toLowerCase());if(!i)throw new Error(`Event '${e}' does not exist.`);i.includes(t)||i.push(t)}off(e,t){const i=this.mapCameraEvents.get(e.toLowerCase());if(!i)throw new Error(`Event '${e}' does not exist.`);const r=i.indexOf(t);-1!==r&&i.splice(r,1)}offAll(e){if(e){if("string"==typeof e){const t=this.mapCameraEvents.get(e);t&&(t.length=0)}}else for(let e of this.mapCameraEvents.values())e&&(e.length=0)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(e){if(this.videoSettings=JSON.parse(JSON.stringify(e)),this._lastDeviceId=null,this._bOpen)return this.play()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return await this._videoTrack.applyConstraints(e)}async turnOnTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}async turnOffTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}async setColorTemperature(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let t=this.getCapabilities().colorTemperature;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({advanced:[{colorTemperature:e,whiteBalanceMode:"manual"}]})}getColorTemperature(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let t=this.getCapabilities().exposureCompensation;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({advanced:[{exposureCompensation:e}]})}getExposureCompensation(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setHardwareScale()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");if(!this._videoTrack)return;const t=this.getCapabilities().zoom;if(!t)throw new Error("Not supported.");return et.max&&(e=t.max),e=le(e,t.min,t.step,t.max),await this._videoTrack.applyConstraints({advanced:[{zoom:e}]}),e}_getHardwareScale(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(e,t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setSoftwareScale()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");t&&this._setScaleCenter(t),this._softwareScale=e,this._scaleVideo(e,t)}_getSoftwareScale(){return this._softwareScale}_setScaleCenter(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setScaleCenter()' is unavailable in singleFrameMode.");if(!e||"string"!=typeof e.x||"string"!=typeof e.y)throw new Error("Invalid center.");const t=this._video.videoWidth,i=this._video.videoHeight;let r=0,n=0;if(e.x.endsWith("px"))r=parseFloat(e.x);else{if(!e.x.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(e.x)/100*t}if(e.y.endsWith("px"))n=parseFloat(e.y);else{if(!e.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(e.y)/100*i}if(NaN==r||NaN==n)throw new Error("Invalid scale center.");this._scaleCenter={x:r,y:n}}_resetScaleCenter(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_resetScaleCenter()' is unavailable in singleFrameMode.");const e=this._video.videoWidth,t=this._video.videoHeight;this._scaleCenter={x:e/2,y:t/2}}_isVideoCenter(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_isVideoCenter()' is unavailable in singleFrameMode.");return e&&e.x==this._video.videoWidth/2&&e.y==this._video.videoHeight/2}async _setZoom(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(e<1)throw new RangeError("Invalid value.");this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const t=await this._setHardwareScale(e);let i=this._getHardwareScale();1==i&&1!=t&&(i=t),e>i?this._setSoftwareScale(e/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(e)}catch(t){if("Not supported."!==(t.message||t))throw t;this._setSoftwareScale(e)}}async setZoom(e){if("number"!=typeof e&&"object"!=typeof e)throw new TypeError("Illegal type of argument.");if("number"==typeof e)return this._setZoom(e);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(e){if("number"!=typeof e.factor)throw new TypeError("Illegal type of 'factor'.");if(e.factor<1)throw new RangeError("Invalid value.");e.centerPoint?this._setScaleCenter(e.centerPoint):this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const t=await this._setHardwareScale(e.factor);let i=this._getHardwareScale();1==i&&1!=t&&(i=t),e.factor>i?this._setSoftwareScale(e.factor/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(e.factor)}catch(t){if("Not supported."!==(t.message||t))throw t;this._setSoftwareScale(e.factor)}}}getZoom(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?{factor:this._getHardwareScale()*this._softwareScale}:null}async resetZoom(){await this.setZoom({factor:1})}async setFrameRate(e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let t=this.getCapabilities().frameRate;if(!t)throw Error("Not supported.");return et.max&&(e=t.max),await this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:e})}getFrameRate(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(e,t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if("string"!=typeof e)throw Error("Invalid focus mode.");e=e.toLowerCase();const i=this.getCapabilities().focusMode,r=this.getCapabilities().focusDistance;if(!i)throw Error("Not supported.");if(!i.includes(e))throw Error("Unsupported mode.");if(t>=0){if(!r)throw Error("Manual focus unsupported.");return tr.max&&(t=r.max),t=le(t,r.min,r.step,r.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:e,focusDistance:t}]})}return await this._videoTrack.applyConstraints({advanced:[{focusMode:e}]})}async setFocus(e,t){if("string"==typeof e)return this._setFocus(e,t);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if(!e)return;const i=this.getCapabilities(),r=i.focusMode,n=i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof e.mode)throw Error("Invalid focus mode.");const s=e.mode.toLowerCase();if(!r.includes(s))throw Error("Unsupported focus mode.");if("manual"!==s)return this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:s}]});if(!n)throw Error("Manual focus unsupported.");if(e.hasOwnProperty("distance")){let t=e.distance;return tn.max&&(t=n.max),t=le(t,n.min,n.step,n.max),this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:s,focusDistance:t}]})}if(!e.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const t=e.area.centerPoint;let i=e.area.width,r=e.area.height;if(!i||!r){const e=this._video.videoWidth,t=this._video.videoHeight;i||(i=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters._focusArea={centerPoint:{x:t.x,y:t.y},width:i,height:r},await this._setLocalFocus(t,i,r)}}getFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const e=this._videoTrack.getSettings().focusMode;return e?"continuous"===e?{mode:e}:{mode:e,distance:this._videoTrack.getSettings().focusDistance}:null}getFocusSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const e=this._videoTrack.getSettings(),t=e.focusMode;return t?"manual"===t?this._focusParameters._focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters._focusArea))}:{mode:"manual",distance:e.focusDistance}:{mode:t}:null}async _setFocusAndGetContract(e,t){const i=e=>{if(!this._bOpen||!this._videoTrack||this.video.paused||e.focusTaskId!=this._focusParameters.curFocusTaskId){this._bOpen&&this._videoTrack&&!this.video.paused||(this._focusParameters.isDoingFocus=0);const t=new Error(`Focus task ${e.focusTaskId} canceled.`);throw t.name="DeprecatedTaskError",t}1===this._focusParameters.isDoingFocus&&Date.now()-e.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;t=le(t,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:"manual",focusDistance:t}]}),i(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/t),Math.abs(1/this._focusParameters.fds.max-1/t))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/t)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=t,await new Promise((e=>{setTimeout(e,r)})),i(e);let n=e.focusL-e.focusW/2,s=e.focusT-e.focusH/2,o=e.focusW,a=e.focusH;if(n>=this.video.videoWidth||s>=this.video.videoHeight)throw new Error("Invalid area.");n+o>this.video.videoWidth&&(o=this.video.videoWidth-n),s+a>this.video.videoHeight&&(a=this.video.videoHeight-s);const h=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:n,sy:s,sWidth:o,sHeight:a,dWidth:o,dHeight:a},null,{pixelFormat:he.RGBA});if(!h)return this._setFocusAndGetContract(e,t);const l=h.data;let c=0;for(let e=0,t=l.length-8;eo&&oc)return await this._doFocusDetail(e,s,o,r,n,l,c)}else{let a=await this._setFocusAndGetContract(e,l);if(o>a)return await this._doFocusDetail(e,s,o,r,n,l,a);if(o==a)return await this._doFocusDetail(e,s,o,l,a);let c=await this._setFocusAndGetContract(e,h);if(c>o&&o{try{(null==t||tthis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=le(Math.sqrt(i*(t||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=le(Math.sqrt((t||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=le(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await this._setFocusAndGetContract(e,s),a=await this._setFocusAndGetContract(e,n),h=await this._setFocusAndGetContract(e,r);if(a>h&&ho&&a>o){let t=await this._setFocusAndGetContract(e,i);const n=await this._doFocusDetail(e,r,h,i,t,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const t=await this._doFocusDetail(e,r,h,s,o);return this._focusParameters.isDoingFocus=0,t}return d(e,t,i)}catch(e){if("DeprecatedTaskError"!==e.name)throw e}};return d(u,r,n)}async enableTapToFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'enableTapToFocus()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error("Video is not playing.");if(!this._focusSupported)throw new Error("Tapping to focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,this._tapFocusEnabled=!1,new Error("Tapping to focus unsupported.");this._tapFocusEnabled=!0}disableTapToFocus(){this._tapFocusEnabled=!1}isTapToFocusEnabled(){return this._tapFocusEnabled}_updateVideoContainerStyle(){if(!this._video)return;if(this.singleFrameMode)return;const e=this._getSoftwareScale(),t=this._videoContainer;if("contain"===this.videoFit&&e>1){const e=this._video.videoWidth,i=this._video.videoHeight,r=window.getComputedStyle(this._elContainer),n=parseFloat(r.width),s=parseFloat(r.height),o=e/i;if(n/sa?o/(i/e):s/(r/e));const c=l*(1-1/e)*(i/2-this._scaleCenter.x),u=l*(1-1/e)*(r/2-this._scaleCenter.y);this._video.style.transform=`translate(${c}px, ${u}px) scale(${e})`}this._updateVideoContainerStyle()}}getFrameSize(e,t,i,r){if(!e||!t)return null;let n,s,o,a,h=e,l=t;const c={regionLeft:0,regionTop:0,regionRight:h,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*h/100,c.regionTop=i.regionTop*l/100,c.regionRight=i.regionRight*h/100,c.regionBottom=i.regionBottom*l/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),n=Math.round(c.regionLeft),s=Math.round(c.regionTop),h=Math.round(c.regionRight-c.regionLeft),l=Math.round(c.regionBottom-c.regionTop)):(n=0,s=0,h=Math.round(h),l=Math.round(l));const u=Math.max(h,l);if(r&&r>0&&u>r){const e=r/u;h>l?(o=r,a=Math.round(l*e)):(o=Math.round(h*e),a=r)}else o=h,a=l;return o<=0||a<=0?null:{sx:n,sy:s,sWidth:h,sHeight:l,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoData()}getImage(){return this.getFrame()}_drawImage(e,t,i,r,n,s,o){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!i||!r)return null;if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let a;ce._onLog&&(a=Date.now(),ce._onLog("DCE: _drawImage(), START: "+a));let h=0,l=0,c=i,u=r,d=0,f=0,g=i,_=r;n&&(n.sx&&(h=Math.round(n.sx)),n.sy&&(l=Math.round(n.sy)),n.sWidth&&(c=Math.round(n.sWidth)),n.sHeight&&(u=Math.round(n.sHeight)),n.dx&&(d=Math.round(n.dx)),n.dy&&(f=Math.round(n.dy)),n.dWidth&&(g=Math.round(n.dWidth)),n.dHeight&&(_=Math.round(n.dHeight)));let p=he.RGBA;o&&o.pixelFormat&&(p=o.pixelFormat);const m=e;if(o&&o.bUseWebGL){ce._onLog&&ce._onLog("DCE: _drawImage() in WebGL."),(m.width{const t=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,t),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),e.STATIC_DRAW);const i=e.createBuffer();return e.bindBuffer(e.ARRAY_BUFFER,i),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),e.STATIC_DRAW),{positions:t,texCoords:i}},i=e=>{const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t},r=(e,t)=>{const i=e.createProgram();if(t.forEach((t=>e.attachShader(i,t))),e.linkProgram(i),!e.getProgramParameter(i,e.LINK_STATUS)){const t=new Error(`An error occured linking the program: ${e.getProgramInfoLog(i)}.`);throw t.name="WebGLError",t}return e.useProgram(i),i},n=(e,t,i)=>{const r=e.createShader(t);if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){const t=new Error(`An error occured compiling the shader: ${e.getShaderInfoLog(r)}.`);throw t.name="WebGLError",t}return r},s="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(o=p.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(e,[n(e,e.VERTEX_SHADER,s),n(e,e.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:h,attribLocations:{vertexPosition:e.getAttribLocation(h,"a_position"),texPosition:e.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:e.getUniformLocation(h,"u_image"),uColorFactor:e.getUniformLocation(h,"uColorFactor"),uMatrix:e.getUniformLocation(h,"u_matrix"),uTextureMatrix:e.getUniformLocation(h,"u_textureMatrix")}},this._webGLBuffers=t(e),this._webGLTexture=i(e),this.shaderPixelFormat=p}const n=(e,t,i)=>{e.bindBuffer(e.ARRAY_BUFFER,t),e.enableVertexAttribArray(i),e.vertexAttribPointer(i,2,e.FLOAT,!1,0,0)},o=(e,t,i)=>{const r=e.RGBA,n=e.RGBA,s=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,r,n,s,i)},v=(e,t,s,o)=>{e.clearColor(0,0,0,1),e.clearDepth(1),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),n(e,s.positions,t.attribLocations.vertexPosition),n(e,s.texCoords,t.attribLocations.texPosition),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,o),e.uniform1i(t.uniformLocations.uSampler,0),e.uniform1f(t.uniformLocations.uColorFactor,[he.GREY,he.GREY32].includes(p)?1:0);let a,m,v=ae.translate(ae.identity(),-1,-1);v=ae.scale(v,2,2),v=ae.scale(v,1/e.canvas.width,1/e.canvas.height),a=ae.translate(v,d,f),a=ae.scale(a,g,_),e.uniformMatrix3fv(t.uniformLocations.uMatrix,!1,a),m=ae.translate(ae.identity(),h/i,l/r),m=ae.scale(m,c/i,u/r),e.uniformMatrix3fv(t.uniformLocations.uTextureMatrix,!1,m),e.drawArrays(e.TRIANGLES,0,6)};let y;if(o(e,this._webGLTexture,t),v(e,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),s){if(s.lengtht||r.sy>i||r.sx+r.sWidth>t||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let o;ce._onLog&&(o=Date.now(),ce._onLog("DCE: _getImageData(), START: "+o));const a=Math.round(r.sx),h=Math.round(r.sy),l=Math.round(r.sWidth),c=Math.round(r.sHeight),u=Math.round(r.dWidth),d=Math.round(r.dHeight);let f=he.RGBA;s&&s.pixelFormat&&(f=s.pixelFormat);let g,_,p,m=this._bWebGLSupported;s&&0==s.bUseWebGL&&(m=!1),m?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),g=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),g=this._reusedCvs);try{if(m)if(ce._onLog&&ce._onLog("DCE: _getImageData() in WebGL."),n)if(f===he.GREY){if(p=new Uint8Array(u*d*4),_=this._drawImage(g,e,t,i,{sx:a,sy:h,sWidth:l,sHeight:c,dWidth:u,dHeight:d},p,{pixelFormat:f,bUseWebGL:m}),p=this._transformPixelFormat(p,_.pixelFormat,f),n){if(n.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");e=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return e}_fetchingLoop(e){if(this.isDisposed&&this.disposed)return;if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();const t=()=>{ce._onLog&&ce._onLog("DCE: start fetching a frame into buffer: "+Date.now());const e=this.getCurrentRegion();let t=this._getVideoData(null,{region:e});if(!t)return void ce._onLog;for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t);const i=this.mapCameraEvents.get("frameaddedtobuffer");for(let e of i)e&&setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this)}),0)},i=()=>{this.isDisposed&&this.disposed||(this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.isDisposed&&this.disposed||(this._bOpen&&this.isFetchingLoopStarted()?(t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,ce._onLog&&ce._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(ce._onLog&&ce._onLog("DCE: stop fetching loop: "+Date.now()),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1,this._recordedStates.fetchingLoopStart=!1)}getFrameFromBuffer(e){return this._frameQueue&&this._frameQueue.length?e?ee.getId()>=0))}getSelectedDrawingItems(){return this._drawingLayersManager.getSelectedDrawingItems()}createDrawingStyle(e){return this._drawingLayersManager.createDrawingStyle(e)}getDrawingStyle(e){return this._drawingLayersManager.getDrawingStyle(e)}getDrawingStyles(){return this._drawingLayersManager.getDrawingStyles()}updateDrawingStyle(e,t){return this._drawingLayersManager.updateDrawingStyle(e,t)}clearDrawingLayers(){const e=this.getDrawingLayers();for(let t of e)this.deleteDrawingLayer(t.getId())}showTip(e,t,i,r,n=3e3,s=!0){this._assertOpen(),this._tipArgs.x=e,this._tipArgs.y=t,this._tipArgs.width=i,this._tipArgs.autoShowSuggestedTip=!!s,this._drawingLayerOfTip||(this._drawingLayerOfTip=this._createDrawingLayer(-1)),this._tipStyleId||(this._tipStyleId=this.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip.clearDrawingItems();const o=new re(r||"",e,t,i,this._tipStyleId);o._fabricObject.paddingTop=15,o._fabricObject.calcTextHeight=function(){for(var e=0,t=0,i=this._textLines.length;t0&&(this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}_hideTip(){this._drawingLayerOfTip&&(this.deleteDrawingLayer(this._drawingLayerOfTip.getId()),this._drawingLayerOfTip=null,this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId))}hideTip(){this._hideTip(),this._tipArgs.x=null,this._tipArgs.y=null,this._tipArgs.width=null,this._tipArgs.autoShowSuggestedTip=null}updateTipMessage(e){if(!this._drawingLayerOfTip)throw new Error("The Tip is not showing.");this._drawingLayerOfTip.getDrawingItems()[0].setAttribute("text",e),this._drawingLayerOfTip.renderAll(),this._tipArgs.duration>0&&(this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId),this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}suggestTip(e,t){this._tipArgs.autoShowSuggestedTip&&(this._drawingLayerOfTip?this.updateTipMessage(t):void 0!==this._tipArgs.x&&this.showTip(this._tipArgs.x,this._tipArgs.y,this._tipArgs.width,t,this._tipArgs.duration)),this.onTipSuggested&&setTimeout((()=>{this.isDisposed&&this.disposed||this.onTipSuggested.apply(this,[e,t])}),0)}_createControler(){if(this._controler||(this._controler=new oe(this)),this._controler)return this._controler}_destroyControler(){this._controler=null}setOriginalImage(e,t,i){if(!e||!t||!i)throw new Error("Invalid arguments");this._originalImageData={imageData:e,width:t,height:i};let r=this._cvsOriginalImage;r||(r=document.createElement("canvas"),r.style.position="absolute",r.style.width="100%",r.style.height="100%",r.style.left="0",r.style.top="0",r.style.backgroundColor="white",r.style.objectFit="contain",this._cvsOriginalImage=r),r.width===t&&r.height===i||(r.width=t,r.height=i);const n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),e instanceof Uint8Array||e instanceof Uint8ClampedArray?(e instanceof Uint8Array&&(e=new Uint8ClampedArray(e.buffer)),n.putImageData(new ImageData(e,t,i),0,0)):e instanceof HTMLCanvasElement&&n.drawImage(e,0,0),document.body.contains(r)&&""===r.style.display&&this._updateDrawingLayersSize({width:t,height:i,objectFit:"contain"})}getOriginalImage(){return this._originalImageData?Object.assign({},this._originalImageData):null}async deleteOriginalImage(){await this.hideOriginalImage(),this._cvsOriginalImage&&(this._cvsOriginalImage.remove(),this._cvsOriginalImage=null),this._originalImageData=null}_showOriginalImageCvs(){this._cvsOriginalImage&&"none"==this._cvsOriginalImage.style.display&&(this._cvsOriginalImage.style.display="")}_hideOriginalImageCvs(){this._cvsOriginalImage&&(this._cvsOriginalImage.style.display="none")}showOriginalImage(){if(!this._originalImageData)throw new Error("No original image is set.");const e=this._cvsOriginalImage;if(""===e.style.display&&document.body.contains(e))return;const{width:t,height:i}=this._originalImageData;if(this._updateDrawingLayersSize({width:t,height:i,objectFit:"contain"}),this._bOpen&&(this._video&&!this._video.paused&&this._video.pause(),this._bFetchingLoopStarted&&(this.stopFetchingLoop(),this._recordedStates.fetchingLoopStart=!0),this.ifShowScanRegionMask&&this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this.ifShowScanRegionLaser&&this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none"),this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none"),this._selCam&&(this._selCam.parentElement.style.display="none")),!document.body.contains(e))if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(e);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e)}this._showOriginalImageCvs()}async _hideOriginalImage(e){this._originalImageData&&this._cvsOriginalImage&&"none"!==this._cvsOriginalImage.style.display&&(this._updateDrawingLayersSize(),this._bOpen&&e&&(this._video&&this._recordedStates.videoPlaying&&await this.play(null,null,null,{notTriggerSingleFrameClick:!0}),this._recordedStates.fetchingLoopStart&&!this.singleFrameMode&&this.startFetchingLoop(),this.ifShowScanRegionMask&&this._cvsScanRegion&&this._recordedStates.maskShow&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this._divScanLight&&this._recordedStates.laserShow&&this.showScanRegionLaser(),this._cvsViewDecorator&&this._recordedStates.decoratorShow&&this.showViewDecorator(),this._scanRegionOverlayContainer&&this._recordedStates.overlayShow&&this.showScanRegionOverlays()),this._selCam&&(this._selCam.parentElement.style.display=""),this._hideOriginalImageCvs())}async hideOriginalImage(){return this._hideOriginalImage(!0)}dispose(e){this.UIElement&&(this._uiOriginalState&&this._uiOriginalState.inDom?this.UIElement.style.display=this._uiOriginalState.display:this.UIElement.style.display="none"),this.clearDrawingLayers(),this.close(),this.forceLoseContext(),this.setViewDecorator(null,null),this._scanRegionOverlayContainer&&this._scanRegionOverlayContainer.remove(),this._arrScanRegionOverlays.length=0,e&&this.UIElement&&this.UIElement.remove(),this.__proto__=null;for(let e in this)delete this[e];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"isDisposed",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}ce._jsVersion="3.3.1",ce._jsEditVersion="20230217",ce._version="JS "+ce._jsVersion+"."+ce._jsEditVersion,ce.browserInfo=H,ce._hasEngineResourceLoaded=!1,ce._engineResourcePath=K,ce._defaultUIElementURL="@engineResourcePath/dce.ui.html";const ue={DT_Arc:class extends J{constructor(e,t,i,r,n,s){super(new N.Circle({left:e,top:t,radius:i,startAngle:r,endAngle:n}),s),this._mediaType="arc"}},DT_Polygon:te,DT_Rect:class extends J{constructor(e,t,i,r,n){super(new N.Rect({left:e,top:t,width:i,height:r}),n)}},DT_Image:class extends J{constructor(e,t,i,r){super(new N.Image(e,{left:t,top:i}),r),this.image=e}_extendSet(e,t){if("image"===e){if(t instanceof HTMLImageElement)return this._fabricObject.setElement(t),this.image=t,!0;if(t instanceof HTMLCanvasElement){const e=new Image;return e.src=t.toDataURL(),this._fabricObject.setElement(e),this.image=t,!0}throw new Error("Unsupported value.")}}_extendGet(e){if("image"===e)return this.image}},DT_Text:re,DT_Line:class extends te{constructor(e,t,i){super([e,t],i),this._mediaType="line"}_extendSet(e,t){if("startPoint"===e||"endPoint"===e){t="startPoint"===e?[t,this.get("endPoint")]:[this.get("startPoint"),t];const i=this._fabricObject;if(i.group){const e=i.group;i.points=t.map((t=>({x:t.x-e.left-e.width/2,y:t.y-e.top-e.height/2}))),e.addWithUpdate()}else i.points=t;const r=i.points.length-1;return i.controls=i.points.reduce((function(e,t,i){return e["p"+i]=new N.Control({positionHandler:q,actionHandler:ee(i>0?i-1:r,$),actionName:"modifyPolygon",pointIndex:i}),e}),{}),i._setPositionDimensions({}),!0}}_extendGet(e){if("startPoint"===e||"endPoint"===e){const t=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let e in i.oCoords)t.push({x:i.oCoords[e].x,y:i.oCoords[e].y});else for(let e of i.points){let r=e.x-i.pathOffset.x,n=e.y-i.pathOffset.y;const s=N.util.transformPoint({x:r,y:n},i.calcTransformMatrix());t.push({x:s.x,y:s.y})}return"startPoint"===e?t[0]:t[1]}}},DT_Group:class extends J{constructor(e){super(new N.Group(e.map((e=>e._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.styleSelector="selected";const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.styleSelector="default";const e=this._fabricObject._objects;for(let t of e)setTimeout((()=>{t&&t.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)}))}getChildItems(){return this._fabricObject._objects.map((e=>e.getDrawingItem()))}addChildItem(e){if(!e||!e.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"add"):this._fabricObject.addWithUpdate(e._getFabricObject())}removeChildItem(e){e&&e.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,e,"remove"):this._fabricObject.removeWithUpdate(e._getFabricObject()))}}};function de(e,t,i){return(i.x-e.x)*(t.y-e.y)==(t.x-e.x)*(i.y-e.y)&&Math.min(e.x,t.x)<=i.x&&i.x<=Math.max(e.x,t.x)&&Math.min(e.y,t.y)<=i.y&&i.y<=Math.max(e.y,t.y)}function fe(e){return Math.abs(e)<1e-6?0:e<0?-1:1}function ge(e,t,i,r){let n=e[0]*(i[1]-t[1])+t[0]*(e[1]-i[1])+i[0]*(t[1]-e[1]),s=e[0]*(r[1]-t[1])+t[0]*(e[1]-r[1])+r[0]*(t[1]-e[1]);return!((n^s)>=0&&0!==n&&0!==s)&&(n=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),s=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),!((n^s)>=0&&0!==n&&0!==s))}class _e extends L{constructor(){super(),this._barcodeFillStyle="rgba(254,180,32,0.3)",this._barcodeStrokeStyle="rgba(254,180,32,0.9)",this._barcodeLineWidth=1,this._barcodeFillStyleBeforeVerification="rgba(248,252,0,0.2)",this._barcodeStrokeStyleBeforeVerification="transparent",this._barcodeLineWidthBeforeVerification=2,this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${ce.getVersion()})`}static _fireHTTPSWarnning(){_e.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{_e.onWarning&&_e.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return ce.testCameraAccess()}_fireResolutionWarning(){if(!this.singleFrameMode&&this.onWarning&&this.dce.isOpen()){const e=this.dce.getConstraints();e&&e.width<1280&&e.height<720&&setTimeout((()=>{this.onWarning&&this.onWarning({id:3,message:"Camera resolution too low, please use a higher resolution (720P or better)."})}),0)}}getUIElement(){return this.dce.getUIElement()}async setUIElement(e){await this.dce.setUIElement(e)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(e){this.dce.singleFrameMode=e,e&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let e=await this.getScanSettings();e.oneDTrustFrameCount=1,await this.updateScanSettings(e)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(e){this.onUniqueRead=e}get video(){return this.dce&&this.dce.video}set videoSrc(e){this.dce&&(this.dce.videoSrc=e)}get videoSrc(){return this.dce&&this.dce.videoSrc}set onTipSuggested(e){this.dce&&(this.dce.onTipSuggested=e)}get onTipSuggested(){return this.dce&&this.dce.onTipSuggested}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set barcodeFillStyle(e){this._barcodeFillStyle=e,this.dce&&this.dce.updateDrawingStyle(3,{fillStyle:e})}get barcodeFillStyle(){return this._barcodeFillStyle}set barcodeStrokeStyle(e){this._barcodeStrokeStyle=e,this.dce&&this.dce.updateDrawingStyle(3,{strokeStyle:e})}get barcodeStrokeStyle(){return this._barcodeStrokeStyle}set barcodeLineWidth(e){this._barcodeLineWidth=e,this.dce&&this.dce.updateDrawingStyle(3,{lineWidth:e})}get barcodeLineWidth(){return this._barcodeLineWidth}set barcodeFillStyleBeforeVerification(e){this._barcodeFillStyleBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{fillStyle:e})}get barcodeFillStyleBeforeVerification(){return this._barcodeFillStyleBeforeVerification}set barcodeStrokeStyleBeforeVerification(e){this._barcodeStrokeStyleBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{strokeStyle:e})}get barcodeStrokeStyleBeforeVerification(){return this._barcodeStrokeStyleBeforeVerification}set barcodeLineWidthBeforeVerification(e){this._barcodeLineWidthBeforeVerification=e,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{lineWidth:e})}get barcodeLineWidthBeforeVerification(){return this._barcodeLineWidthBeforeVerification}set regionMaskFillStyle(e){this.dce.setScanRegionMaskStyle({fillStyle:e})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(e){this.dce.setScanRegionMaskStyle({strokeStyle:e})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(e){this.dce.setScanRegionMaskStyle({lineWidth:e})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(e){this._region=e,this.dce&&(e?e instanceof Array||this.dce.setScanRegion(e):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e,this.dce.framePixelFormat=e?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(L._onLog&&L._onLog("createDCEInstance()"),ce.defaultUIElementURL=null,this.dce=await ce.createInstance(),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=ue,["iPhone","iPad","Android","HarmonyOS"].includes(L.browserInfo.OS)||this.dce.setResolution(1920,1080),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"}),this.barcodeLineWidth=this._barcodeLineWidth,this.dce.on("cameraChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async e=>{if(!e)return;if(!e.data)return;let t;this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:i,sx:r,sy:n,width:s,height:o,stride:a,pixelFormat:h,timeStamp:l,_sWidth:c,_sHeight:u}=e,d={timeStamp:l};if("grey"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_GrayScaled,0,d);else if("rgba"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_ARGB_8888,0,d)}if(await this.clearMapDecodeRecord(),L.recalculateResultLocation(t,r,n,c,u,s,o),this._drawResults(t),this.onFrameRead&&this.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onFrameRead(e)}if(this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))})))}set maxCvsSideLength(e){this._maxCvsSideLength=e,this.dce.maxCvsSideLength=e}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(e){let t=new _e;t._instanceID=await _e.createInstanceInWorker(!0),await t.createDCEInstance(),"string"==typeof e&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return await t.dce.setUIElement(_e.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),_e._fireHTTPSWarnning(),t.singleFrameMode||await t.updateRuntimeSettings("single"),t}async decodeCurrentFrame(e){this._assertOpen();let t=null;e&&e.region&&(t=e.region);const i=this.dce._getVideoData(null,{region:t});return this._decode_DCEFrame(i)}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=9}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=512,t.deblurLevel=3,t.localizationModes=[2,16,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=9,t.timeout=1e5}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=512,t.deblurLevel=5,t.scaleDownThreshold=1e5,t.localizationModes=[2,16,4,8,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=9,t.timeout=1e5}else if("single"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region)}else if("dense"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=0,t.deblurLevel=7,t.scaleDownThreshold=1e5,t.localizationModes=[2,8,0,0,0,0,0,0],t.minResultConfidence=0,t.barcodeZoneMinDistanceToImageBorders=9,t.timeout=1e5}else if("distance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,e.region&&(t.region=e.region),t.expectedBarcodesCount=0,t.scaleDownThreshold=1e5,t.localizationModes=[2,8,0,0,0,0,0,0],t.barcodeZoneMinDistanceToImageBorders=9,t.timeout=1e5}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let i=e.region;[i.regionLeft,i.regionTop,i.regionLeft,i.regionBottom,i.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:i.regionLeft||0,regionTop:i.regionTop||0,regionRight:i.regionRight||0,regionBottom:i.regionBottom||0,regionMeasuredByPercentage:i.regionMeasuredByPercentage||0})}}if(!L._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(v.BF_ONED|v.BF_QR_CODE|v.BF_PDF417|v.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let e=t.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(e)):this.userDefinedRegion=null,e instanceof Array)if(e.length){for(let t=0;t{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){i(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),L._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})})),"string"==typeof e&&["speed","balance","coverage","dense","distance"].includes(e)&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","1"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","0"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","0"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(e){this.dce.off("played",this._onPlayed),this._onPlayed=e,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(e){const t=await this.dce.selectCamera(e);return this._fireResolutionWarning(),t}getResolution(){return this.dce.getResolution()}async setResolution(e,t){const i=await this.dce.setResolution(e,t);return this._fireResolutionWarning(),i}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(e){return this.dce.updateVideoSettings(e)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(e){return this.dce&&this.dce.setVideoFit(e)}getVideoFit(){return this.dce&&this.dce.getVideoFit()}set ifShowScanRegionMask(e){this.dce&&(this.dce.ifShowScanRegionMask=e)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}set ifSaveLastUsedCamera(e){this.dce&&(this.dce.ifSaveLastUsedCamera=e)}get ifSaveLastUsedCamera(){return this.dce&&this.dce.ifSaveLastUsedCamera}set ifSkipCameraInspection(e){this.dce&&(this.dce.ifSkipCameraInspection=e)}get ifSkipCameraInspection(){return this.dce&&this.dce.ifSkipCameraInspection}stop(){this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.dce.stop(),this.dce.ifShowScanRegionLaser=!1,this.dce.hideViewDecorator(),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this.dce.pause()}async play(e,t,i){this.dce.ifShowScanRegionLaser=!0;const r=await this.dce.play(e,t,i);return this._fireResolutionWarning(),r}pauseScan(e){this._assertOpen(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(e){return this.dce.applyConstraints(e)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(e){return this.dce.setColorTemperature(e)}getColorTemperature(){return this.dce.getColorTemperature()}async setExposureCompensation(e){return this.dce.setExposureCompensation(e)}getExposureCompensation(){return this.dce.getExposureCompensation()}async setZoom(e){return this.dce.setZoom(e)}getZoomSettings(){return this.dce.getZoomSettings()}resetZoom(){return this.dce.resetZoom()}async setFrameRate(e){return this.dce.setFrameRate(e)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(e,t){return this.dce.setFocus(e,t)}getFocus(){return this.dce.getFocus()}getFocusSettings(){return this.dce.getFocusSettings()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(!this.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return L._onLog&&L._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));L._onLog&&L._onLog("======= once read ======="),L._onLog&&(this._timeStartDecode=Date.now());const e=this._getVideoFrame();if(!e)return L._onLog&&L._onLog("Get invalid frame."),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{e._bUseWebGL||"grey"!==e.pixelFormat||(this.dce.framePixelFormat="rgba");let t=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{data:i,sx:r,sy:n,width:s,height:o,stride:a,pixelFormat:h,timeStamp:l,_sWidth:c,_sHeight:u}=e,d={timeStamp:l};if("grey"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_GrayScaled,0,d);else if("rgba"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,o,a,_.IPF_ARGB_8888,0,d)}if(L.recalculateResultLocation(t,r,n,c,u,s,o),0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration)),this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan&&(this.autoZoom||this.autoFocus||this.autoSuggestTip))if(t.length)this.autoZoomInFrameArray.length=0,this.autoZoomOutFrameCount=0,this.frameArrayInIdealZoom.length=0,this.suggestTipFrameArray.length=0,this.autoZoom&&this.autoFocus&&(this.nextActionInIdealZoom="focus"),this.autoFocusFrameArray.length=0,this.noIntermediateResultsCount=0;else{const e=await this.getIntermediateResults(),t=(e,t,i,r,n,s,o)=>{let a=s/r,h=o/n;e.x1=e.x1/a+t,e.x2=e.x2/a+t,e.x3=e.x3/a+t,e.x4=e.x4/a+t,e.y1=e.y1/h+i,e.y2=e.y2/h+i,e.y3=e.y3/h+i,e.y4=e.y4/h+i},i=e=>{if(!e)return null;const i={};let a,h,l,d,f;{const e=this.video.videoWidth*(1-this.autoZoomDetectionArea)/2,t=this.video.videoWidth*(1+this.autoZoomDetectionArea)/2,i=t,r=e,n=this.video.videoHeight*(1-this.autoZoomDetectionArea)/2,s=n,o=this.video.videoHeight*(1+this.autoZoomDetectionArea)/2;f={x1:e,x2:t,x3:i,x4:r,y1:n,y2:s,y3:o,y4:o}}const g=(e,t)=>{const i=(e,t)=>{if(!e&&!t)throw new Error("Invalid arguments.");return function(e,t,i){let r=!1;const n=e.length;if(n<=2)return!1;for(let s=0;s0!=fe(a.y-i)>0&&fe(t-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}([{x:t.x1,y:t.y1},{x:t.x2,y:t.y2},{x:t.x3,y:t.y3},{x:t.x4,y:t.y4}],e.x,e.y)},r=(e,t)=>!!(ge([e[0],e[1]],[e[2],e[3]],[t.x1,t.y1],[t.x2,t.y2])||ge([e[0],e[1]],[e[2],e[3]],[t.x2,t.y2],[t.x3,t.y3])||ge([e[0],e[1]],[e[2],e[3]],[t.x3,t.y3],[t.x4,t.y4])||ge([e[0],e[1]],[e[2],e[3]],[t.x4,t.y4],[t.x1,t.y1]));return!!(i({x:e.x1,y:e.y1},t)||i({x:e.x2,y:e.y2},t)||i({x:e.x3,y:e.y3},t)||i({x:e.x4,y:e.y4},t))||(!!(i({x:t.x1,y:t.y1},e)||i({x:t.x2,y:t.y2},e)||i({x:t.x3,y:t.y3},e)||i({x:t.x4,y:t.y4},e))||!!(r([t.x1,t.y1,t.x2,t.y2],e)||r([t.x2,t.y2,t.x3,t.y3],e)||r([t.x3,t.y3,t.x4,t.y4],e)||r([t.x4,t.y4,t.x1,t.y1],e)))},_=[];for(let i of e){if(i.resultType!==y.IRT_TYPED_BARCODE_ZONE)continue;const e=i.scaleDownRatio;for(let a of i.results){if(!a)continue;const i={x1:a.x1=a.x1*e,x2:a.x2=a.x2*e,x3:a.x3=a.x3*e,x4:a.x4=a.x4*e,y1:a.y1=a.y1*e,y2:a.y2=a.y2*e,y3:a.y4=a.y3*e,y4:a.y4=a.y4*e};t(i,r,n,c,u,s,o),g(f,i)&&_.push(a)}}const p=(e=>{if(!e||!e.length)return null;const t=e=>{const t=(e.x1+e.x2+e.x3+e.x4)/4,i=(e.y1+e.y2+e.y3+e.y4)/4;return(t-s/2)*(t-s/2)+(i-o/2)*(i-o/2)};let i,r=e.filter((e=>e.barcodeFormat==v.BF_QR_CODE||e.barcodeFormat==v.BF_DATAMATRIX));if(r.length||(r=e.filter((e=>e.barcodeFormat==v.BF_ONED)),r.length||(r=e)),!r.length)return null;i=r[0];let n=t(i);if(1!=r.length)for(let e=1;e1.1*i.confidence?(i=r[e],n=s):r[e].confidence>.9*i.confidence&&s!0===e)).length>=this.suggestTipFrameLimit[1]){this.suggestTipFrameArray.length=0;const e=a.x3-a.x1,t=a.y3-a.y1;a.result.moduleSizet?e>s*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):e>.6*s&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."):e<=t&&(t>o*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):t>.6*o&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."))}if(this.autoZoom){const e=this.autoZoomIdealArea[1];let i=(1-this.autoZoomTargetBorder)/2;const h=a.x1/c,l=(c-a.x3)/c,d=a.y1/u,f=(u-a.y3)/u;if(h>e&&l>e&&d>e&&f>e&&a.result.moduleSize{}))),this.autoZoomInFrameArray.filter((e=>!0===e)).length>=this.autoZoomInFrameLimit[1]){this.autoZoomInFrameArray.length=0;const e=[(.5-i)/(.5-h),(.5-i)/(.5-l),(.5-i)/(.5-d),(.5-i)/(.5-f)].filter((e=>e>0)),t=Math.min(...e,this.autoZoomInIdealModuleSize/a.result.moduleSize),r=this.dce.getZoomSettings().factor;let n=Math.max(Math.pow(r*t,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);n=Math.min(n,t);const s=r*n;await this.setZoom({factor:s}),this.dce.clearFrameBuffer()}}else if(this.autoZoomInFrameArray.length=0,this.frameArrayInIdealZoom.push(!0),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.frameArrayInIdealZoom.filter((e=>!0===e)).length>=this.frameLimitInIdealZoom[1])if(this.frameArrayInIdealZoom.length=0,"focus"===this.nextActionInIdealZoom&&this.autoFocus){t(a,r,n,c,u,s,o);try{await this.setFocus({mode:"manual",area:{centerPoint:{x:(a.x1+a.x3)/2+"px",y:(a.y1+a.y3)/2+"px"},width:a.x3-a.x1+"px",height:a.y3-a.y1+"px"}})}catch(e){}this.dce.clearFrameBuffer(),this.nextActionInIdealZoom="zoomOut"}else{if("zoomOut"!==this.nextActionInIdealZoom&&this.autoFocus)throw new Error("Invalid action.");if(this.enableZoomOutInIdealZoom){i=this.autoZoomIdealArea[1]+this.autoZoomOutStepRate_2;const e=[(.5-i)/(.5-h),(.5-i)/(.5-l),(.5-i)/(.5-d),(.5-i)/(.5-f)].filter((e=>e>0));let t=Math.min(...e)*this.dce.getZoomSettings().factor;await this.setZoom({factor:t}),this.dce.clearFrameBuffer(),this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((e=>{})))}}}else if(this.autoFocus&&(this.autoFocusFrameArray.push(!0),this.autoFocusFrameArray.splice(0,this.autoFocusFrameArray.length-this.autoFocusFrameLimit[0]),this.autoFocusFrameArray.filter((e=>!0===e)).length>=this.autoFocusFrameLimit[1])){this.autoFocusFrameArray.length=0;try{t(a,r,n,c,u,s,o),await this.setFocus({mode:"manual",area:{centerPoint:{x:(a.x1+a.x3)/2+"px",y:(a.y1+a.y3)/2+"px"},width:a.x3-a.x1+"px",height:a.y3-a.y1+"px"}})}catch(e){}this.dce.clearFrameBuffer()}}else if(this.noIntermediateResultsCount++,this.suggestTipFrameArray.push(!1),this.autoZoom){if(this.autoZoomInFrameArray.push(!1),this.autoZoomInFrameArray.splice(0,this.autoZoomInFrameArray.length-this.autoZoomInFrameLimit[0]),this.autoZoomOutFrameCount++,this.frameArrayInIdealZoom.push(!1),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.autoZoomOutFrameCount>=this.autoZoomOutFrameLimit){this.autoZoomOutFrameCount=0;const e=this.getZoomSettings().factor;if(e>this.autoZoomOutMinValue){const t=Math.max((e-1)*this.autoZoomOutStepRate,this.autoZoomOutMinStep),i=Math.max(e-t,this.autoZoomOutMinValue);await this.setZoom({factor:i}),this.dce.clearFrameBuffer()}}this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((e=>{})))}else this.autoFocus&&(this.autoFocusFrameArray.length=0,this.setFocus({mode:"continuous"}).catch((e=>{})))}return t})().then((e=>{if(L._onLog&&L._onLog(e),this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;const r=()=>{let r=0;if(this.region instanceof Array){let n=0,s=0;n=i+1>=this.region.length?0:i+1,s=n+1>=this.region.length?0:n+1,r=e[n]&&e[n].length&&t[s]&&t[s].length?Math.min(...e[n])-Math.max(...t[s]):0}else if(t&&t.length){let i=Math.min(...e),n=Math.max(...t);i&&n&&(r=i-n)}else r=0;return r>0?r:0};(()=>{if(this.region instanceof Array){for(e[i]&&e[i]instanceof Array||(e[i]=[]);e[i].length>=5;)e[i].shift();e[i].push(this._lastInnerDecodeDuration)}else{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=r()+this.intervalTime,L._onLog&&L._onLog("Next fetching frame loop interval: "+this._intervalGetVideoFrame)}if(this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onFrameRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onFrameRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){L._onLog&&L._onLog("Get frame in parallel.");let t=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,t||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;e=this.dce.getFrameFromBuffer();const i=e=>{if(!e)return;let t=e.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(t)};i(e)}else L._onLog&&L._onLog("Get frame in serial."),this.dce.stopFetchingLoop(),e=this.dce.getFrame();return e}async open(){this._bindUI();const e=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}close(){this.dce.close(),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}async show(){this._bindUI();const e=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const e=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),e}hide(){this.dce.close(!0),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}showTip(e,t,i,r,n=3e3,s=!0){this.dce&&this.dce.showTip(e,t,i,r,n,s)}hideTip(){this.dce&&this.dce.hideTip()}updateTipMessage(e){this.dce&&this.dce.updateTipMessage(e)}async enableTapToFocus(){this.dce&&this.dce.enableTapToFocus()}disableTapToFocus(){this.dce&&this.dce.disableTapToFocus()}isTapToFocusEnabled(){return this.dce.isTapToFocusEnabled()}transformCoord(e){if(!this.isOpen())throw new Error("Unavailable when the camera is not open.");if(this.singleFrameMode&&!this.dce._cvsSingleFrameMode)throw new Error("No image is selected. ");const t=this.dce._elContainer.getBoundingClientRect();let i,r,n,s,o,a=t.left,h=t.top,l=a+window.scrollX,c=h+window.scrollY;this.singleFrameMode?(i=this.dce._cvsSingleFrameMode.width,r=this.dce._cvsSingleFrameMode.height,n=parseFloat(window.getComputedStyle(this.dce._cvsSingleFrameMode).width),s=parseFloat(window.getComputedStyle(this.dce._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,r=this.video.videoHeight,n=parseFloat(window.getComputedStyle(this.dce._elContainer).width),s=parseFloat(window.getComputedStyle(this.dce._elContainer).height),o=this.getVideoFit());const u=n/s,d=i/r;let f,g,_,p,m=1;if("contain"===o)u{let t=!1;if(l)try{(await n.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===o.browser&&o.version>66||"Safari"===o.browser&&o.version>13||"OPR"===o.browser&&o.version>43||"Edge"===o.browser&&o.version;const u=(()=>{if(!e&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),d=" is not allowed to change after `createInstance` or `loadWasm` is called.",f=!e&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",g=!e&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",_=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let i=0;it&&"object"==typeof t&&"function"==typeof t.then;class w extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(C(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,C(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}}const b=["iPhone","iPad","Android","HarmonyOS"].includes(o.OS)?2048:4096;class x{constructor(){this._instanceID=void 0,this._ifSaveOriginalImageInACanvas=!1,this.oriCanvas=null,this.oriCanvasData=null,this.canvas=null,this.bFilterRegionInJs=!1,this._region=null,this._timeStartDecode=null,this._timeEnterInnerDBR=null,this._timeGetMessage=null,this.decodeRecords={},this.bDestroyed=!1,this._lastErrorCode=0,this._lastErrorString="",this._lastInnerDecodeDuration=0,this.intervalTime=0,this._intervalGetVideoFrame=0,this.array_getFrameTimeCost=[],this.array_decodeFrameTimeCost=[],this._indexCurrentDecodingFrame=0,this._arrPolygons=[],this._bPauseScan=!1,this._intervalDetectVideoPause=1e3,this._soundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",this.beepSound=new t({src:["data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"],onplayerror:(t,e)=>{console.warn(`Sound '${t}' playback failure: ${e}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=b,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`license`"+d);i._license=e})(x,t)}static get productKeys(){return this._license}static set productKeys(t){x.license=t}static get handshakeCode(){return this._license}static set handshakeCode(t){x.license=t}static get organizationID(){return this._license}static set organizationID(t){x.license=t}static set sessionPassword(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+d);i._sessionPassword=e})(x,t)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:a,worker:h,getUserMedia:l,camera:await c(),browser:o.browser,version:o.version,OS:o.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(t){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");x._engineResourcePath=(t=>{if(null==t&&(t="./"),!e){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get licenseServer(){return this._licenseServer}static set licenseServer(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+d);i._licenseServer=_(e)})(x,t)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+d);i._deviceFriendlyName=e||""})(x,t)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(t){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");x.__bUseFullFeature=t}static isImageSource(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&"getImage"in t}static isDSImage(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&("data"in t&&("width"in t&&("height"in t&&"pixelFormat"in t)))}static isDCEFrame(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&("data"in t&&("region"in t&&("sx"in t&&("sy"in t&&("width"in t&&("height"in t&&(("colorMode"in t||"pixelFormat"in t)&&("timeSpent"in t&&("timeStamp"in t&&("isCropped"in t&&("toCanvas"in t&&("_sWidth"in t&&("_sHeight"in t&&"_bUseWebGL"in t)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(t){this._ifSaveOriginalImageInACanvas=t}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(t){this._region=t,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var t;return null===(t=x._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",x.engineResourcePath)}static set defaultUIElementURL(t){x._defaultUIElementURL=t}static _fireHTTPSWarnning(){x.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{x.onWarning&&x.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new t({src:[this._soundSource],onplayerror:(t,e)=>{console.warn(`Sound '${t}' playback failure: ${e}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(t){this.bPlaySoundOnSuccessfulRead="never"!==t&&t}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(t){this.bVibrateOnSuccessfulRead="never"!==t&&t}set dce(t){this._dce=t}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(t){this._maxCvsSideLength=t,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",t)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;x._onLog&&x._onLog("_registerDCEControler()");const t=this.dce;this._dceControler=t._createControler();const e=this._dceControler;e.register(this),e.setDisiredValue(this,"refreshInterval",200),e.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(t){"ReferenceError"===t.name&&window&&(window.ResizeObserver=void 0)}const i=t.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===e._innerSetUI&&(await t.setUIElement(`${r.engineResourcePath}dce.ui.html`),e._innerSetUI=t.getUIElement()):(await t.setUIElement(`${r.engineResourcePath}dbr.ui.html`),e._innerSetUI=t.getUIElement())}catch(e){await t.setUIElement(r.defaultUIElementURL)}else i||await t.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async t=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let e=await this._decode_DCEFrame(t,{bCopyData:!1}),i=null;if(e&&e.length){const{sx:r,sy:s,width:n,height:o,_sWidth:a,_sHeight:h}=t;i=e.map((t=>({localizationResult:JSON.parse(JSON.stringify(t.localizationResult))}))),x.recalculateResultLocation(i,r,s,a,h,n,o)}if(this._drawResults(i,e),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let t of e)this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))},t.on("cameraChange",this.callbackCameraChange),t.on("resolutionChange",this.callbackResolutionChange),t.on("cameraClose",this.callbackCameraClose),t.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(x._onLog&&x._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(t,e){if(null==t)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(t&&t.isCameraEnhancer)this.dce=t,await this._registerDCEControler(),this._imgSource=null;else{if(!x.isImageSource(t))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=t}e&&e.resultsHighlightBaseShapes&&(this._drawingItemNamespace=e.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:t,l:e,ls:i,sp:r,rmk:s}=(t=>{const e=t;if(e._pLoad.isEmpty){let t,i,r=e._license||"",s=JSON.parse(JSON.stringify(e._licenseServer)),n=e._sessionPassword,o=0;if(r.startsWith("t")||r.startsWith("f"))o=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))o=1;else{o=2;const e=r.indexOf(":");if(-1!=e&&(r=r.substring(e+1)),r.startsWith("DLS2")){let e;try{let t=r.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===s.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),s=_(t)}!n&&e.sessionPassword&&(n=e.sessionPassword),t=e.remark}("200001"===r||r.startsWith("200001-"))&&(s&&s.length||(r="")),r||(o=1)}if(o&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==o)throw new Error(i);o=0,console.warn(i),e._lastErrorCode=-1,e._lastErrorString=i}return 1===o&&(r="",console.warn("Applying for a public trial license ...")),{lt:o,l:r,ls:s,sp:n,rmk:t}}throw new Error("Can't preprocess license again"+d)})(x);this._pLoad.task=async(n,a)=>{let h=x.engineResourcePath+x._workerName;x.engineResourcePath.startsWith(location.origin)||(h=await fetch(h).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),x._dbrWorker=new Worker(h),x._dbrWorker.onerror=t=>{let e=new Error(t.message);a(e)},x._dbrWorker.onmessage=async e=>{let i=e.data?e.data:e;switch(i.type){case"log":x._onLog&&x._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let e,r=!1;1===t&&(r=!0,i.message||(i.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),i.success?(x._dbrWorker.onerror=null,x._version=i.version+"(JS "+x._jsVersion+"."+x._jsEditVersion+")",x._onLog&&x._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(e=new Error(i.message),e.stack=i.stack+"\n"+e.stack,e.ltsErrorCode=i.ltsErrorCode,r||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&x.showDialog(i.success?"warn":"error",i.message),i.success?n():a(e);break}case"task":{let t=i.id,e=i.body;try{x._taskCallbackMap.get(t)(e),x._taskCallbackMap.delete(t)}catch(e){throw x._taskCallbackMap.delete(t),e}break}default:x._onLog&&x._onLog(e)}},x._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:x.engineResourcePath,bUseFullFeature:x._bUseFullFeature,bd:x._bWasmDebug,v:x._jsVersion,brtk:!!t,bptk:1===t,l:e,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:o,fn:x.deviceFriendlyName,ls:i,sp:r,rmk:s})}}await this._pLoad}static async showDialog(t,e){await(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let s=await r.text();if(!s.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let n=document.createElement("div");n.innerHTML=s;let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),s=e.indexOf("(",r),n=e.indexOf(")",s);if(-1==i||-1==r||-1==s||-1==n){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(s+1,n);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(n+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})(this,t,e)}static async createInstanceInWorker(t=!1){return await x.loadWasm(),await new Promise(((e,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(t=>{if(t.success)return e(t.instanceID);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),x._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:t})}))}static async createInstance(){let t=new x;return t._instanceID=await x.createInstanceInWorker(),x._fireHTTPSWarnning(),t}async clearMapDecodeRecord(){return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(t){x._onLog&&x._onLog("decode(source: any)"),x._onLog&&(this._timeStartDecode=Date.now());{let e={};return!this.region||this.region instanceof Array||(e.region=JSON.parse(JSON.stringify(this.region))),t instanceof Blob?await this._decode_Blob(t,e):t instanceof ArrayBuffer?await this._decode_ArrayBuffer(t,e):t instanceof Uint8Array||t instanceof Uint8ClampedArray?await this._decode_Uint8Array(t,e):t instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap?await this._decode_Image(t,e):t instanceof HTMLCanvasElement?await this._decode_Canvas(t,e):t instanceof HTMLVideoElement?await this._decode_Video(t,e):"string"==typeof t?"data:image/"==t.substring(0,11)?await this._decode_Base64(t,e):await this._decode_Url(t,e):x.isDCEFrame(t)?(e.bCopyData=!0,await this._decode_DCEFrame(t,e)):x.isDSImage(t)?(e.bCopyData=!0,await this._decode_DSImage(t,e)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(t){let e={};return!this.region||this.region instanceof Array||(e.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(t,e)}async decodeUrl(t){let e={};return!this.region||this.region instanceof Array||(e.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(t,e)}async _decodeBuffer_Uint8Array(t,e,i,r,s,n,o){return await new Promise(((a,h)=>{let l=x._nextTaskID++;x._taskCallbackMap.set(l,(t=>{if(t.success){let e,i=x._onLog?Date.now():0;x._onLog&&x._onLog("worker return result: "+i),this._lastInnerDecodeDuration=t.duration;try{e=this._handleRetJsonString(t.decodeReturn)}catch(t){return h(t)}if(x._onLog){let t=Date.now();x._onLog("DBR getting message from worker timestamp: "+i),x._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),x._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),x._onLog("Handling results from DBR worker costs: "+(t-i)),x._onLog("Total decoding image costs: "+(t-this._timeStartDecode))}return a(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,h(e)}})),this._timeEnterInnerDBR=Date.now(),x._onLog&&x._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),x._dbrWorker.postMessage({type:"decodeBuffer",id:l,instanceID:this._instanceID,body:{buffer:t,width:e,height:i,stride:r,format:s,orientation:n,config:o}},[t.buffer]),x._onLog&&o&&o.timeStamp&&x._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(t,e,i,r,s,n,o){x._onLog&&x._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=t.arrayBuffer?await t.arrayBuffer():await new Promise(((e,i)=>{let r=new FileReader;r.readAsArrayBuffer(t),r.onload=()=>{e(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),e,i,r,s,n,o)}async decodeBuffer(t,e,i,r,s,n,o){let a;return x._onLog&&x._onLog("decodeBuffer(buffer,width,height,stride,format)"),x._onLog&&(this._timeStartDecode=Date.now()),t instanceof Uint8Array||t instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(t,e,i,r,s,n,o):t instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(t),e,i,r,s,n,o):t instanceof Blob&&(a=await this._decodeBuffer_Blob(t,e,i,r,s,n,o)),a}async _decodeFileInMemory_Uint8Array(t){return await new Promise(((e,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(t=>{if(t.success){let r;this._lastInnerDecodeDuration=t.duration;try{r=this._handleRetJsonString(t.decodeReturn)}catch(t){return i(t)}return e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),x._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:t}})}))}async getRuntimeSettings(){return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success){let e=JSON.parse(i.results);return null!=this.userDefinedRegion&&(e.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let e;if("string"==typeof t)if("speed"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=3,e.expectedBarcodesCount=0,e.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=5,e.expectedBarcodesCount=512,e.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region}else if("dense"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=9,e.expectedBarcodesCount=0,e.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=3,e.expectedBarcodesCount=0,e.localizationModes=[2,8,0,0,0,0,0,0]}else e=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(e=JSON.parse(JSON.stringify(t)),e.region instanceof Array){let t=e.region;[t.regionLeft,t.regionTop,t.regionLeft,t.regionBottom,t.regionMeasuredByPercentage].some((t=>void 0!==t))&&(e.region={regionLeft:t.regionLeft||0,regionTop:t.regionTop||0,regionRight:t.regionRight||0,regionBottom:t.regionBottom||0,regionMeasuredByPercentage:t.regionMeasuredByPercentage||0})}}if(!x._bUseFullFeature){if(0!=(e.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.BF_DATAMATRIX))||0!=e.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=e.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let t=e.region;if(t instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(t)),(t.regionLeft||t.regionTop||t.regionRight||t.regionBottom||t.regionMeasuredByPercentage)&&(t.regionLeft||t.regionTop||100!=t.regionRight||100!=t.regionBottom||!t.regionMeasuredByPercentage)?this.region=t:this.region=null,e.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(e.intermediateResultTypes|=S.IRT_TYPED_BARCODE_ZONE),await new Promise(((t,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.updateReturn)}catch(t){i(t)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),x._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(e)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=b,await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=b,await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!x._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t(i.results);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(t){if(!x._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof t)t=t;else{if("object"!=typeof t)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");t=JSON.stringify(t)}return await new Promise(((e,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.initReturn)}catch(t){i(t)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),x._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:t}})}))}async _decode_Blob(t,e){x._onLog&&x._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await function(t){return new Promise(((e,i)=>{let r=URL.createObjectURL(t),s=new Image;s.dbrObjUrl=r,s.src=r,s.onload=()=>{e(s)},s.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let s=await this._decode_Image(i||r,e);return i&&i.close(),s}async _decode_ArrayBuffer(t,e){return await this._decode_Blob(new Blob([t]),e)}async _decode_Uint8Array(t,e){return await this._decode_Blob(new Blob([t]),e)}async _decode_Image(t,e){x._onLog&&x._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),e=e||{};let i,r,s=t instanceof HTMLImageElement?t.naturalWidth:t.width,n=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(s,n);if(o>this._maxCvsSideLength){let t=this._maxCvsSideLength/o;i=Math.round(s*t),r=Math.round(n*t)}else i=s,r=n;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,s,n,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._decode_Canvas(a,e)}async _decode_Canvas(t,e){if(x._onLog&&x._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let i=(t.ctx2d||t.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(i,t.width,t.height,4*t.width,p.IPF_ABGR_8888,0,e)}async _decode_Video(t,e){if(x._onLog&&x._onLog("_decode_Video(video)"),!(t instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";e=e||{};let i,r,s=t.videoWidth,n=t.videoHeight,o=Math.max(s,n);if(o>this._maxCvsSideLength){let t=this._maxCvsSideLength/o;i=Math.round(s*t),r=Math.round(n*t)}else i=s,r=n;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,s,n,0,0,i,r),await this._decode_Canvas(a,e)}async _decode_DCEFrame(t,e){if(x._onLog&&x._onLog("_decode_DCEFrame(dceFrame)"),!x.isDCEFrame(t))return[];let i=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:r,height:s,colorMode:n,pixelFormat:o,stride:a,timeStamp:h}=t;let l;l=e&&e.bCopyData?new Uint8Array(t.data):t.data;let c=null;if(e?(c=JSON.parse(JSON.stringify(e)),c.timeStamp=h):c={timeStamp:h},o&&a)if("grey"===o)i=await this._decodeBuffer_Uint8Array(l,r,s,a,p.IPF_GrayScaled,0,c);else if("rgba"===o)i=await this._decodeBuffer_Uint8Array(l,r,s,a,p.IPF_ABGR_8888,0,c);else{if("bgra"!==o)throw new Error(`Pixel format '${o}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(l,r,s,a,p.IPF_ARGB_8888,0,c)}else if("grey"===n)i=await this._decodeBuffer_Uint8Array(l,r,s,r,p.IPF_GrayScaled,0,c);else if("rgba"===n)i=await this._decodeBuffer_Uint8Array(l,r,s,4*r,p.IPF_ABGR_8888,0,c);else{if("bgra"!==n)throw new Error(`Color mode '${n}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(l,r,s,4*r,p.IPF_ARGB_8888,0,c)}return i}async _decode_DSImage(t,e){if(x._onLog&&x._onLog("_decode_DSImage(dsImage)"),!x.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const t=document.createElement("canvas");let e;switch(t.width=this.width,t.height=this.height,this.pixelFormat){case"grey":e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{e(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,e)}}async _decode_FilePath(t,e){throw x._onLog&&x._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(t,e,i,r,s,n,o){if(t.length>0)for(let a of t){let t=a.localizationResult;2==t.resultCoordinateType&&(t.x1*=.01*n,t.x2*=.01*n,t.x3*=.01*n,t.x4*=.01*n,t.y1*=.01*o,t.y2*=.01*o,t.y3*=.01*o,t.y4*=.01*o);let h=n/r,l=o/s;t.x1=t.x1/h+e,t.x2=t.x2/h+e,t.x3=t.x3/h+e,t.x4=t.x4/h+e,t.y1=t.y1/l+i,t.y2=t.y2/l+i,t.y3=t.y3/l+i,t.y4=t.y4/l+i,2==t.resultCoordinateType&&(t.x1*=100/r,t.x2*=100/r,t.x3*=100/r,t.x4*=100/r,t.y1*=100/s,t.y2*=100/s,t.y3*=100/s,t.y4*=100/s)}}static BarcodeReaderException(t,e){let i,r=m.DBR_UNKNOWN;return"number"==typeof t?(r=t,i=new Error(e)):i=new Error(t),i.code=r,i}_handleRetJsonString(t){let e=m;if(t.textResults){for(let e=0;e{let i=e.indexOf(":");t[e.substring(0,i)]=e.substring(i+1)})),i.exception=t}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!x._setWarnnedEx.has(t.description)&&(x._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==e.DBR_SUCCESS)return t.data;throw x.BarcodeReaderException(t.exception,t.description)}async setModeArgument(t,e,i,r){return await new Promise(((s,n)=>{let o=x._nextTaskID++;x._taskCallbackMap.set(o,(t=>{if(t.success){try{this._handleRetJsonString(t.setReturn)}catch(t){return n(t)}return s()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),x._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:t,index:e,argumentName:i,argumentValue:r}})}))}async getModeArgument(t,e,i){return await new Promise(((r,s)=>{let n=x._nextTaskID++;x._taskCallbackMap.set(n,(t=>{if(t.success){let e;try{e=this._handleRetJsonString(t.getReturn)}catch(t){return s(t)}return r(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}})),x._dbrWorker.postMessage({type:"getModeArgument",id:n,instanceID:this._instanceID,body:{modeName:t,index:e,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t(i.results);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),e=[];for(let i of t)if(i.dataType==v.IMRDT_IMAGE)for(let t of i.results){const i=t.bytes;let r;switch(x._onLog&&x._onLog(" "+i.length+" "+i.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case p.IPF_ABGR_8888:r=new Uint8ClampedArray(i);break;case p.IPF_RGB_888:{const t=i.length/3;r=new Uint8ClampedArray(4*t);for(let e=0;e=s)break;r[o]=r[o+1]=r[o+2]=(128&e)/128*255,r[o+3]=255,e<<=1}}break}default:console.warn("unknow intermediate image",t)}if(!r)continue;let s=new ImageData(r,t.width,t.height),n=document.createElement("canvas");n.width=t.width,n.height=t.height,n.getContext("2d").putImageData(s,0,0),e.push(n)}return e}async getScanSettings(){return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success){let e=i.results;return e.intervalTime=this.intervalTime,e.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,e.soundOnSuccessfullRead=this.soundSource,e.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,e.vibrateDuration=this.vibrateDuration,e.captureAndDecodeInParallel=this.captureAndDecodeInParallel,e.autoZoom=this.autoZoom,e.autoFocus=this.autoFocus,e.autoSuggestTip=this.autoSuggestTip,t(e)}{let t=new Error(i.message);return t.stack+="\n"+i.stack,e(t)}})),x._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(t){if(!t)return;const e=JSON.parse(JSON.stringify(t));if(e.autoZoom||e.autoFocus||e.autoSuggestTip){if(!x._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const t=await this.getRuntimeSettings();t.intermediateResultTypes|=S.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(t)}return e.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(e.intervalTime,0),delete e.intervalTime),e.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=e.whenToPlaySoundforSuccessfulRead,delete e.whenToPlaySoundforSuccessfulRead),e.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=e.soundOnSuccessfullRead,delete e.soundOnSuccessfullRead),e.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=e.whenToVibrateforSuccessfulRead,delete e.whenToVibrateforSuccessfulRead),e.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=e.vibrateDuration,delete e.vibrateDuration),e.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=e.captureAndDecodeInParallel,delete e.captureAndDecodeInParallel),e.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=e.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=e.autoZoom,delete e.autoZoom),e.hasOwnProperty("autoFocus")&&(this.autoFocus=e.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete e.autoFocus),e.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=e.autoSuggestTip,delete e.autoFocus),await new Promise(((t,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack+="\n"+e.stack,i(t)}})),x._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:e}})}))}_cloneDecodeResults(t){if(t instanceof Array){let e=[];for(let i of t)e.push(this._cloneDecodeResults(i));return e}{let e=t,i=JSON.parse(JSON.stringify(e,((t,e)=>"oriVideoCanvas"==t||"searchRegionCanvas"==t?void 0:e)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return x._onLog&&x._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));x._onLog&&x._onLog("======= once read ======="),x._onLog&&(this._timeStartDecode=Date.now());let t=null,e=null;if(this.dce)t=this._getVideoFrame();else if(this._imgSource&&(e=await this._imgSource.getImage(),!x.isDSImage(e)))throw new Error("Invalid DSImage.");if(!t&&!e)return x._onLog&&x._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(t){i=await this._decode_DCEFrame(t,{bScanner:!0,bCopyData:!1});let e=null;if(i&&i.length){const{sx:r,sy:s,width:n,height:o,_sWidth:a,_sHeight:h}=t;e=i.map((t=>({resultState:t.resultState,localizationResult:JSON.parse(JSON.stringify(t.localizationResult))}))),x.recalculateResultLocation(e,r,s,a,h,n,o)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(e,i),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else e&&(i=await this._decode_DSImage(e,{bScanner:!0,bCopyData:!1}));return i})().then((t=>{if(x._onLog&&x._onLog(t),this.dce&&this.captureAndDecodeInParallel){let t=this.array_decodeFrameTimeCost,e=this.array_getFrameTimeCost;const i=()=>{let i=0;if(e&&e.length){let r=Math.min(...t),s=Math.max(...e);r&&s&&(i=r-s)}else i=0;return i>0?i:0};(()=>{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&t.length){let e=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?e=t.some((t=>t.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(e=t.some((t=>0==t.resultState))),e&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&t.length){let e=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?e=t.some((t=>t.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(e=t.some((t=>0==t.resultState))),e)try{navigator.vibrate(this.vibrateDuration)}catch(t){console.warn("Vibration not allowed. User interaction required: "+(t.message||t))}}if(this.onImageRead){t=t.filter((t=>t.resultState>=0));const e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead){t=t.filter((t=>0==t.resultState));const e=this._cloneDecodeResults(t);for(let t of e)this.onUniqueRead(t.barcodeText,t)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((t=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),x._onLog&&x._onLog(t.message||t),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==t.message||console.warn(t.message)}))}_getVideoFrame(){if(!this.dce)return null;let t;if(this.captureAndDecodeInParallel){if(x._onLog&&x._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;t=this.dce.getFrameFromBuffer();const e=t=>{if(!t)return;let e=t.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(e)};e(t)}else x._onLog&&x._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),t=this.dce.getFrame();return t}_drawResults(t,e){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const i=this._dbrDrawingLayer;t||(t=[]);let r=this._arrPolygons;for(let s=0;s{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(e),e}stopScanning(t){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[t]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(t){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),t&&t.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(x._onLog&&x._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let t=x._nextTaskID++;x._taskCallbackMap.set(t,(t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}})),x._dbrWorker.postMessage({type:"destroyContext",id:t,instanceID:this._instanceID})}}x._jsVersion="9.6.10",x._jsEditVersion="20230213",x._version=`loading...(JS ${x._jsVersion}.${x._jsEditVersion})`,x._license=f,x._sessionPassword=g,x.browserInfo=o,x._workerName=`dbr-${x._jsVersion}.browser.worker.js`,x._engineResourcePath=u,x._licenseServer=[],x._deviceFriendlyName="",x._isShowRelDecodeTimeInResults=!1,x._bWasmDebug=!1,x._bNeverShowDialog=!1,x.__bUseFullFeature=!0,x._nextTaskID=0,x._taskCallbackMap=new Map,x._pLoad=new w,x._lastErrorCode=0,x._lastErrorString="",x._setWarnnedEx=new Set,x._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var T={653:(t,e,i)=>{var r,s,n,o,a,h,l,c,u,d,f,g,_,p,m,v,y,S,C,w,b,x=x||{version:"5.2.1"};if(e.fabric=x,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?x.document=document:x.document=document.implementation.createHTMLDocument(""),x.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;x.document=T.document,x.jsdomImplForWrapper=i(898).implForWrapper,x.nodeCanvas=i(245).Canvas,x.window=T,DOMParser=x.window.DOMParser}function I(t,e){var i=t.canvas,r=e.targetCanvas,s=r.getContext("2d");s.translate(0,r.height),s.scale(1,-1);var n=i.height-r.height;s.drawImage(i,0,n,r.width,r.height,0,0,r.width,r.height)}function E(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,s=e.destinationHeight,n=r*s*4,o=new Uint8Array(this.imageBuffer,0,n),a=new Uint8ClampedArray(this.imageBuffer,0,n);t.readPixels(0,0,r,s,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,s);i.putImageData(h,0,0)}x.isTouchSupported="ontouchstart"in x.window||"ontouchstart"in x.document||x.window&&x.window.navigator&&x.window.navigator.maxTouchPoints>0,x.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,x.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],x.DPI=96,x.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",x.commaWsp="(?:\\s+,?\\s*|,\\s*)",x.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,x.reNonWord=/[ \n\.,;!\?\-]/,x.fontPaths={},x.iMatrix=[1,0,0,1,0,0],x.svgNS="http://www.w3.org/2000/svg",x.perfLimitSizeTotal=2097152,x.maxCacheSideLimit=4096,x.minCacheSideLimit=256,x.charWidthsCache={},x.textureSize=2048,x.disableStyleCopyPaste=!1,x.enableGLFiltering=!0,x.devicePixelRatio=x.window.devicePixelRatio||x.window.webkitDevicePixelRatio||x.window.mozDevicePixelRatio||1,x.browserShadowBlurConstant=1,x.arcToSegmentsCache={},x.boundsOfCurveCache={},x.cachesBoundsOfCurve=!0,x.forceGLPutImageData=!1,x.initFilterBackend=function(){return x.enableGLFiltering&&x.isWebglSupported&&x.isWebglSupported(x.textureSize)?(console.log("max texture size: "+x.maxTextureSize),new x.WebglFilterBackend({tileSize:x.textureSize})):x.Canvas2dFilterBackend?new x.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=x),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:x.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}x.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,s=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},x.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof x.Gradient||this.set(e,new x.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof x.Pattern?i&&i():this.set(e,new x.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,s=Math.sqrt,n=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,x.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new x.Point(t.x-e.x,t.y-e.y),s=x.util.rotateVector(r,i);return new x.Point(s.x,s.y).addEquals(e)},rotateVector:function(t,e){var i=x.util.sin(e),r=x.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new x.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new x.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=x.util.createVector(t,e),s=x.util.createVector(t,i),n=x.util.calcAngleBetweenVectors(r,s),o=n*(0===x.util.calcAngleBetweenVectors(x.util.rotateVector(r,n),s)?1:-1)/2;return{vector:x.util.getHatVector(x.util.rotateVector(r,o)),angle:n}},projectStrokeOnPoints:function(t,e,i){var r=[],s=e.strokeWidth/2,n=e.strokeUniform?new x.Point(1/e.scaleX,1/e.scaleY):new x.Point(1,1),o=function(t){var e=s/Math.hypot(t.x,t.y);return new x.Point(t.x*e*n.x,t.y*e*n.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new x.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(x.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(x.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=x.util.getBisector(u,l,c),_=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-s/Math.sin(p/2),f=new x.Point(_.x*d*n.x,_.y*d*n.y),Math.hypot(f.x,f.y)/s<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-s*Math.SQRT2,f=new x.Point(_.x*d*n.x,_.y*d*n.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new x.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new x.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var s,n=!0,o=t.getImageData(e,i,2*r||1,2*r||1),a=o.data.length;for(s=3;s=s?n-s:2*Math.PI-(s-n)}function n(t,e,i){for(var n=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,n,o,a,h){var l=Math.PI,c=h*l/180,u=x.util.sin(c),d=x.util.cos(c),f=0,g=0,_=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,m=(i=Math.abs(i))*i,v=(n=Math.abs(n))*n,y=p*p,S=_*_,C=m*v-m*y-v*S,w=0;if(C<0){var b=Math.sqrt(1-C/(m*v));i*=b,n*=b}else w=(o===a?-1:1)*Math.sqrt(C/(m*y+v*S));var T=w*i*p/n,I=-w*n*_/i,E=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=s(1,0,(_-T)/i,(p-I)/n),A=s((_-T)/i,(p-I)/n,(-_-T)/i,(-p-I)/n);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),M=[],F=A/D,L=8/3*Math.sin(F/4)*Math.sin(F/4)/Math.sin(F/2),P=R+F,k=0;kw)for(var T=1,I=_.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:s.x===t[i-2].x?0:-1,h=s.y>t[i-2].y?1:s.y===t[i-2].y?0:-1),r.push(["L",s.x+a*e,s.y+h*e]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(e,i,r,s,n,o,a,h){var l;if(x.cachesBoundsOfCurve&&(l=t.call(arguments),x.boundsOfCurveCache[l]))return x.boundsOfCurveCache[l];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,C=Math.abs,w=[],b=[[],[]];u=6*e-12*r+6*n,c=-3*e+9*r-9*n+3*a,d=3*r-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*s+6*o,c=-3*i+9*s-9*o+3*h,d=3*s-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&w.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&w.push(g),0<(_=(-u-m)/(2*c))&&_<1&&w.push(_));for(var I,E,O,R=w.length,A=R;R--;)I=(O=1-(f=w[R]))*O*O*e+3*O*O*f*r+3*O*f*f*n+f*f*f*a,b[0][R]=I,E=O*O*O*i+3*O*O*f*s+3*O*f*f*o+f*f*f*h,b[1][R]=E;b[0][A]=e,b[1][A]=i,b[0][A+1]=a,b[1][A+1]=h;var D=[{x:y.apply(null,b[0]),y:y.apply(null,b[1])},{x:S.apply(null,b[0]),y:S.apply(null,b[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=D),D},x.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(n),s=n,(r=o(l.x,l.y,i.x,i.y))+a>e?(n-=c,c/=2):(l=i,n+=c,a+=r);return i.angle=u(s),i}(n,e)}},x.util.transformPath=function(t,e,i){return i&&(e=x.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},s=1;s=e}))}}}(),function(){function t(e,i,r){if(r)if(!x.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var s=0,n=i.length;s57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var s=t.charCodeAt(e-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1}x.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,s=[];for(r=0;r-1?t.prototype[s]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var s=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return s}}(s):t.prototype[s]=e[s],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function s(){}function n(e){for(var i=null,r=this;r.constructor.superclass;){var s=r.constructor.superclass.prototype[e];if(r[e]!==s){i=s;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}x.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(s.prototype=i.prototype,a.prototype=new s,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=x.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(t){return t},d?_=function(t,e){return t.style.opacity=e,t}:f&&(_=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),x.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?_(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?_(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,s=Array.prototype.slice,n=function(t){return s.call(t,0)};try{t=n(x.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=x.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=x.document.documentElement,s=x.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===x.document?(e=s.scrollLeft||r.scrollLeft||0,i=s.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(n=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=x.document.defaultView&&x.document.defaultView.getComputedStyle?function(t,e){var i=x.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=x.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",x.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=x.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},x.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},x.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},x.util.getById=function(t){return"string"==typeof t?x.document.getElementById(t):t},x.util.toArray=n,x.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},x.util.makeElement=o,x.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},x.util.getScrollLeftTop=a,x.util.getElementOffset=function(t){var i,r,s=t&&t.ownerDocument,n={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!s)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=s.documentElement,void 0!==t.getBoundingClientRect&&(n=t.getBoundingClientRect()),r=a(t),{left:n.left+r.left-(i.clientLeft||0)+o.left,top:n.top+r.top-(i.clientTop||0)+o.top}},x.util.getNodeCanvas=function(t){var e=x.jsdomImplForWrapper(t);return e._canvas||e._image},x.util.cleanUpJsdomNode=function(t){if(x.isLikelyNode){var e=x.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}x.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",s=i.onComplete||function(){},n=new x.window.XMLHttpRequest,o=i.body||i.parameters;return n.onreadystatechange=function(){4===n.readyState&&(s(n),n.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),n.open(r,e,!0),"POST"!==r&&"PUT"!==r||n.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),n.send(o),n}}(),x.log=console.log,x.warn=console.warn,function(){var t=x.util.object.extend,e=x.util.object.clone,i=[];function r(){return!1}function s(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}x.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var n=x.window.requestAnimationFrame||x.window.webkitRequestAnimationFrame||x.window.mozRequestAnimationFrame||x.window.oRequestAnimationFrame||x.window.msRequestAnimationFrame||function(t){return x.window.setTimeout(t,1e3/60)},o=x.window.cancelAnimationFrame||x.window.clearTimeout;function a(){return n.apply(x.window,arguments)}x.util.animate=function(i){i||(i={});var n,o=!1,h=function(){var t=x.runningAnimations.indexOf(n);return t>-1&&x.runningAnimations.splice(t,1)[0]};return n=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(n),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||s,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(t,e){return v[e]-m[e]})):v-m);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,s=r/c,S=p?m.map((function(t,e){return _(r,m[e],y[e],c)})):_(r,m,y,c),C=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(n.currentValue=p?S.slice():S,n.completionRate=C,n.durationRate=s,!o){if(!f(S,C,s))return e>u?(n.currentValue=p?v.slice():v,n.completionRate=1,n.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(S,C,s),void a(t));h()}}(l)})),n.cancel},x.util.requestAnimFrame=a,x.util.cancelAnimFrame=function(){return o.apply(x.window,arguments)},x.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}x.util.animateColor=function(e,i,r,s){var n=new x.Color(e).getSource(),o=new x.Color(i).getSource(),a=s.onComplete,h=s.onChange;return s=s||{},x.util.animate(x.util.object.extend(s,{duration:r||500,startValue:n,endValue:o,byValue:o,easing:function(e,i,r,n){return t(i,r,s.colorEasing?s.colorEasing(e,n):1-Math.cos(e/n*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(n):n(i,s)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,s,n,o=[];for(s=0,n=e.length;s1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,s,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,_=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",m=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,C={},w="",b=0,x=0;if(C.width=0,C.height=0,C.toBeParsed=S,m&&(g||_)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(w=" translate("+n(g)+" "+n(_)+") ",a=(t.getAttribute("transform")||"")+w,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),S)return C;if(m)return C.width=n(d),C.height=n(f),C;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),s=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=r,C.viewBoxWidth=s,C.viewBoxHeight=o,y?(C.width=s,C.height=o):(C.width=n(d),C.height=n(f),c=C.width/s,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),b=C.width-s*c,x=C.height-o*c,"Mid"===p.alignX&&(b/=2),"Mid"===p.alignY&&(x/=2),"Min"===p.alignX&&(b=0),"Min"===p.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return C;if((g||_)&&"#document"!==t.parentNode.nodeName&&(w=" translate("+n(g)+" "+n(_)+") "),a=w+" matrix("+c+" 0 0 "+u+" "+(i*c+b)+" "+(r*u+x)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function S(t,e){var i="xlink:href",r=m(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var s=r.cloneNode(!0);s.firstChild;)e.appendChild(s.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,s,n){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,s,n){var o,a=(n.x-s.x)*(t.y-s.y)-(n.y-s.y)*(t.x-s.x),h=(r.x-t.x)*(t.y-s.y)-(r.y-t.y)*(t.x-s.x),l=(n.y-s.y)*(r.x-t.x)-(n.x-s.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var s,n,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,s=new i,n=t.length;for(r=0;r0&&(s.status="Intersection"),s},e.Intersection.intersectPolygonRectangle=function(t,r,s){var n=r.min(s),o=r.max(s),a=new e.Point(o.x,n.y),h=new e.Point(n.x,o.y),l=i.intersectLinePolygon(n,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,n,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var s,n,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)s=n=0;else{var l=a-h;switch(n=o>.5?l/(2-a-h):l/(a+h),a){case t:s=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,s=r.canvas,n=e.util.object.clone(i);n.target=r,s&&s.fire("object:"+t,n),r.fire(t,i)}function _(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function m(t,e,i){var r=t.lockScalingX,s=t.lockScalingY;return!((!r||!s)&&(e||!r&&!s||!i)&&(!r||"x"!==e)&&(!s||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,s){var n=i.target,o=n.getCenterPoint(),a=n.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,s);return n.setPositionByOrigin(a,i.originX,i.originY),h}}function S(t,e){return function(i,r,s,n){var o=e(i,r,s,n);return o&&g(t,v(i,r,s,n)),o}}function C(t,i,r,s,n){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(s,n),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function w(t){return t.flipX!==t.flipY}function b(t,e,i,r,s){if(0!==t[e]){var n=s/t._getTransformedDimensions()[r]*t[i];t.set(i,n)}}function x(t,e,i,r){var s,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?s=0:(s=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===n&&e.originY===h&&(s=-s),e.originX===a&&e.originY===o&&(s=-s),w(l)&&(s=-s));var _=g!==s;if(_){var p=l._getTransformedDimensions().y;l.set("skewX",s),b(l,"skewY","scaleY","y",p)}return _}function T(t,e,i,r){var s,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?s=0:(s=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===n&&e.originY===h&&(s=-s),e.originX===a&&e.originY===o&&(s=-s),w(l)&&(s=-s));var _=g!==s;if(_){var p=l._getTransformedDimensions().x;l.set("skewY",s),b(l,"skewX","scaleX","x",p)}return _}function I(t,e,i,r,s){s=s||{};var n,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=s.by,S=_(t,f),w=m(f,y,S),b=e.gestureScale;if(w)return!1;if(b)o=e.scaleX*b,a=e.scaleY*b;else{if(n=C(e,e.originX,e.originY,i,r),l="y"!==y?d(n.x):1,u="x"!==y?d(n.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),S&&!y){var x=Math.abs(n.x)+Math.abs(n.y),T=e.original,I=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(n.x*f.scaleX/h.x),a=Math.abs(n.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var E=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),E!==f.scaleX||O!==f.scaleY}s.scaleCursorStyleHandler=function(t,e,r){var s=_(t,r),n="";if(0!==e.x&&0===e.y?n="x":0===e.x&&0!==e.y&&(n="y"),m(r,n,s))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},s.skewCursorStyleHandler=function(t,e,i){var s="not-allowed";if(0!==e.x&&i.lockSkewingY)return s;if(0!==e.y&&i.lockSkewingX)return s;var n=f(i,e)%4;return r[n]+"-resize"},s.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?s.skewCursorStyleHandler(t,e,i):s.scaleCursorStyleHandler(t,e,i)},s.rotationWithSnapping=S("rotating",y((function(t,e,i,r){var s=e,n=s.target,o=n.translateToOriginPoint(n.getCenterPoint(),s.originX,s.originY);if(n.lockRotation)return!1;var a,h=Math.atan2(s.ey-o.y,s.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+s.theta);if(n.snapAngle>0){var d=n.snapAngle,f=n.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?n:a:(c>0&&(s=u===o?n:a),c<0&&(s=u===o?a:n),w(h)&&(s=s===n?a:n)),e.originX=s,S("skewing",y(x))(t,e,i,r))},s.skewHandlerY=function(t,e,i,r){var s,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?s=C(e,l,l,i,r).y>0?o:h:(c>0&&(s=u===n?o:h),c<0&&(s=u===n?h:o),w(a)&&(s=s===o?h:o)),e.originY=s,S("skewing",y(T))(t,e,i,r))},s.dragHandler=function(t,e,i,r){var s=e.target,n=i-e.offsetX,o=r-e.offsetY,a=!s.get("lockMovementX")&&s.left!==n,h=!s.get("lockMovementY")&&s.top!==o;return a&&s.set("left",n),h&&s.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},s.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},s.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},s.fireEvent=g,s.wrapWithFixedAnchor=y,s.wrapWithFireEvent=S,s.getLocalPoint=C,e.controlsUtils=s}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,s){r=r||{};var n,o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,o>a?(n=o,t.scale(1,a/o),d=i*o/a):a>o?(n=a,t.scale(o/a,1),u=e*a/o):n=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,n/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,s,n){s=s||{};var o=this.sizeX||s.cornerSize||n.cornerSize,a=this.sizeY||s.cornerSize||n.cornerSize,h=void 0!==s.transparentCorners?s.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(s.cornerStrokeColor||n.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=s.cornerColor||n.cornerColor,t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(n.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,s,n){var o,a,h,l,c=n?this.touchSizeX:this.sizeX,u=n?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),_=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(_),l=f*e.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:s-h},tr:{x:r+o,y:s-a},bl:{x:r-o,y:s+a},br:{x:r+l,y:s+h}}},render:function(t,i,r,s,n){"circle"===((s=s||{}).cornerStyle||n.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,s,n):e.controlsUtils.renderSquareControl.call(this,t,i,r,s,n)}}}(e),function(){function t(t,e){var i,r,s,n,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),n=h.length;n--;){var l=h[n].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(s=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),s||(s=t.getAttribute("stop-opacity")),r=(i=new x.Color(i)).getAlpha(),s=isNaN(parseFloat(s))?1:parseFloat(s),s*=r*e,{offset:a,color:i.toRgb(),opacity:s}}var e=x.util.object.clone;x.Gradient=x.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+x.Object.__uid++:this.id=x.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new x.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return x.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,s,n,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():x.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+x.util.matrixToSVG(c)+'" ',"linear"===this.type?n=["\n']:"radial"===this.type&&(n=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,s=h.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,s=h.length;r\n')}return n.push("linear"===this.type?"\n":"\n"),n.join("")},toLive:function(t){var e,i,r,s=x.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(s.x1,s.y1,s.x2,s.y2):"radial"===this.type&&(e=t.createRadialGradient(s.x1,s.y1,s.r1,s.x2,s.y2,s.r2)),i=0,r=this.colorStops.length;i1?1:n,isNaN(n)&&(n=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],n));return l=x.parseTransformAttribute(d),function(t,e,i,r){var s,n;Object.keys(e).forEach((function(t){"Infinity"===(s=e[t])?n=1:"-Infinity"===s?n=0:(n=parseFloat(e[t],10),"string"==typeof s&&/^(\d+\.\d+)%|(\d+)%$/.test(s)&&(n*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(n*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(n*=i.viewBoxHeight||i.height)))),e[t]=n}))}(0,a,s,u),"pixels"===u&&(g=-i.left,_=-i.top),new x.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:_})}})}(),m=x.util.toFixed,x.Pattern=x.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=x.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=x.util.createImage(),x.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=x.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},x.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,s=this.offsetX/t.width,n=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,n&&(r+=Math.abs(n))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,s&&(i+=Math.abs(s))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var r=40,s=40,n=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,n)+20,s=100*i((Math.abs(o.y)+this.blur)/t.height,n)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(x.StaticCanvas)x.warn("fabric.StaticCanvas is already defined.");else{var t=x.util.object.extend,e=x.util.getElementOffset,i=x.util.removeFromArray,r=x.util.toFixed,s=x.util.transformPoint,n=x.util.invertTransform,o=x.util.getNodeCanvas,a=x.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");x.StaticCanvas=x.util.createClass(x.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:x.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return x.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,x.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=x.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?x.util.loadImage(e,(function(e,s){if(e){var n=new x.Image(e,r);this[t]=n,n.canvas=this}i&&i(e,s)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=x.util.getById(t)||this._createCanvasElement(),x.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,s=this._activeObject,n=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,s=e.width||this.width,n=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=x.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",x.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+x.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],s=t.viewportTransform,n={width:t.width/(r?s[0]:1),height:t.height/(r?s[3]:1)};return i.toSVG(n,{additionalTransform:r?x.util.matrixToSVG(s):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,s,n,o,a,h="",l={},c=x.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,s,n=this._objects;for(r=0,s=n.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,s,n=this._activeObject;if(t===n&&"activeSelection"===t.type)for(e=(s=n._objects).length;e--;)r=s[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,s,n=this._activeObject;if(t===n&&"activeSelection"===t.type)for(s=n._objects,e=0;e0+l&&(o=n-1,i(this._objects,s),this._objects.splice(o,0,s)),l++;else 0!==(n=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,n,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,s;if(i){for(r=e,s=e-1;s>=0;--s)if(t.intersectsWithObject(this._objects[s])||t.isContainedWithinObject(this._objects[s])||this._objects[s].isContainedWithinObject(t)){r=s;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,s,n,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)s=a[r],(n=this._objects.indexOf(s))"}}),t(x.StaticCanvas.prototype,x.Observable),t(x.StaticCanvas.prototype,x.Collection),t(x.StaticCanvas.prototype,x.DataURLExporter),t(x.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),x.StaticCanvas.prototype.toJSON=x.StaticCanvas.prototype.toObject,x.isLikelyNode&&(x.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},x.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),x.BaseBrush=x.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=x.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new x.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),x.PencilBrush=x.util.createClass(x.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,s=this.canvas.contextTop;this._saveAndTransform(s),this.oldEnd&&(s.beginPath(),s.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(s,i[r-2],i[r-1],!0),s.stroke(),s.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new x.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new x.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],s=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===s.x&&r.y===s.y){var n=this.width/1e3;r=new x.Point(r.x,r.y),s=new x.Point(s.x,s.y),r.x-=n,s.x+=n}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=s&&(o=t[i],a.push(o));return a.push(t[n]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),x.CircleBrush=x.util.createClass(x.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var s=0,n=this._objects.length;s1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=x.util.invertTransform(i),s=this.restorePointerVpt(e);return x.util.transformPoint(s,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),s=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),n=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return x.util.isTransparent(t._cacheContext,Math.round(s),Math.round(n),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,x.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var s=r.controls[e];return s.getActionName(i,s,r)},_setupCurrentTransform:function(t,i,r){if(i){var s=this.getPointer(t),n=i.__corner,o=i.controls[n],a=r&&n?o.getActionHandler(t,i,o):x.controlsUtils.dragHandler,h=this._getActionFromCorner(r,n,t,i),l=this._getOriginFromCorner(i,n),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:n,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:s.x-i.left,offsetY:s.y-i.top,originX:l.x,originY:l.y,ex:s.x,ey:s.y,lastX:s.x,lastY:s.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:x.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new x.Point(e.ex,e.ey),r=x.util.transformPoint(i,this.viewportTransform),s=new x.Point(e.ex+e.left,e.ey+e.top),n=x.util.transformPoint(s,this.viewportTransform),o=Math.min(r.x,n.x),a=Math.min(r.y,n.y),h=Math.max(r.x,n.x),l=Math.max(r.y,n.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,x.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,s,n=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(n,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],n))return o;if(1===a.length&&o===this._searchPossibleTargets([o],n)){if(!this.preserveObjectStacking)return o;r=o,s=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,n);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=s),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,s=t.length;s--;){var n=t[s],o=n.group?this._normalizePointer(n.group,e):e;if(this._checkTarget(o,n,e)){(i=t[s]).subTargetCheck&&i instanceof x.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return x.util.transformPoint(t,x.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,s=t(e),n=this.upperCanvasEl,o=n.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),s.x=s.x-this._offset.left,s.y=s.y-this._offset.top,i||(s=this.restorePointerVpt(s));var l=this.getRetinaScaling();return 1!==l&&(s.x/=l,s.y/=l),r=0===a||0===h?{width:1,height:1}:{width:n.width/a,height:n.height/h},{x:s.x*r.width,y:s.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),x.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=x.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),x.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),x.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;x.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,x.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),s=[],n=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),n.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e,target:r}),s.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e,selected:s,deselected:n}):r.length>0?this.fire("selection:created",{e,selected:s}):t.length>0&&this.fire("selection:cleared",{e,deselected:n})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){x.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,x.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),s=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),s},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),x.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),x.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),x.StaticCanvas)"prototype"!==r&&(x.Canvas[r]=x.StaticCanvas[r])}(),function(){var t=x.util.addListener,e=x.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}x.util.object.extend(x.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,s=this._getEventPrefix();t(x.window,"resize",this._onResize),t(r,s+"down",this._onMouseDown),t(r,s+"move",this._onMouseMove,i),t(r,s+"out",this._onMouseOut),t(r,s+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(x.document,t+"up",this._onMouseUp),e(x.document,"touchend",this._onTouchEnd,i),e(x.document,t+"move",this._onMouseMove,i),e(x.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var s=this.upperCanvasEl,n=this._getEventPrefix();t(x.document,"touchend",this._onTouchEnd,i),t(x.document,"touchmove",this._onMouseMove,i),e(s,n+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var s=this.upperCanvasEl,n=this._getEventPrefix();e(s,n+"move",this._onMouseMove,i),t(x.document,n+"up",this._onMouseUp),t(x.document,n+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var s=this._getEventPrefix();e(x.document,"touchend",this._onTouchEnd,i),e(x.document,"touchmove",this._onMouseMove,i);var n=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(n.upperCanvasEl,s+"down",n._onMouseDown),n._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var s=this.upperCanvasEl,n=this._getEventPrefix();this._isMainEvent(r)&&(e(x.document,n+"up",this._onMouseUp),e(x.document,n+"move",this._onMouseMove,i),t(s,n+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,s=this._groupSelector,n=!1,o=!s||0===s.left&&0===s.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),n=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),n||(n=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),x.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),n=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),n?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,s={e,target:i,subTargets:r};if(this.fire(t,s),i&&i.fire(t,s),!r)return i;for(var n=0;n1&&(e=new x.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,s=this._groupSelector.ey,n=r+this._groupSelector.left,o=s+this._groupSelector.top,a=new x.Point(v(r,n),v(s,o)),h=new x.Point(y(r,n),y(s,o)),l=!this.selectionFullyContained,c=r===n&&s===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),x.util.object.extend(x.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),s=this.toCanvasElement(r,t);return x.util.toDataURL(s,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,s=this.getZoom(),n=this.width,o=this.height,a=s*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=x.util.createCanvasElement(),_=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=n,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=_,g}}),x.util.object.extend(x.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):x.util.object.clone(t),s=this,n=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){s.clear(),s._setBgOverlay(r,(function(){n?s._enlivenObjects([n],(function(i){s.clipPath=i[0],s.__setupCanvas.call(s,r,t,o,e)})):s.__setupCanvas.call(s,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var s=this;e.forEach((function(t,e){s.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var s=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?x.util.enlivenObjects([e],(function(e){s[t]=e[0],i[t]=!0,r&&r()})):this["set"+x.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?x.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=x.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new x.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,s=e.util.toFixed,n=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,s=t.height,n=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=n&&s<=n&&r*s<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),s>u&&(t.zoomY/=s/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var s,n,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,_=f||g,p=0,m=0,v=!1;if(f){var y=this._cacheCanvas.width,S=this._cacheCanvas.height,C=l>y||c>S;v=C||(l<.9*y||c<.9*S)&&y>h&&S>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,m=.1*c)}return this instanceof e.Text&&this.path&&(_=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!_&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+m)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),s=a.x/2,n=a.y/2,this.cacheTranslationX=Math.round(o.width/2-s)+s,this.cacheTranslationY=Math.round(o.height/2-n)+n,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:s(this.left,i),top:s(this.top,i),width:s(this.width,i),height:s(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:s(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:s(this.strokeMiterLimit,i),scaleX:s(this.scaleX,i),scaleY:s(this.scaleY,i),angle:s(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:s(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:s(this.skewX,i),skewY:s(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),s=this.canvas.getRetinaScaling();e*=r*s,i*=r*s}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,s=this[t]!==i,n=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,s&&(n=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,n&&this.group.set("dirty",!0)):n&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,s,n,a=this.getViewportTransform(),h=this.calcTransformMatrix();s=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,n=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?s&&this.drawBordersInGroup(t,r,i):s&&this.drawBorders(t,i),n&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,s=this.canvas,n=s&&s.viewportTransform[0]||1,o=s&&s.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),s&&s._isRetinaScaling()&&(n*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(n+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*n*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,s=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,s):t.transform(1,0,0,1,r,s),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:s}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,s=this._limitCacheSize(this._getCacheCanvasDimensions()),n=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=s.x/this.scaleX/o,h=s.y/this.scaleY/o;n.width=a,n.height=h,(r=n.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(s.zoomX/this.scaleX/o,s.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/s.zoomX,o*this.scaleY/s.zoomY),t.strokeStyle=r.createPattern(n,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),s=this.group,n=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),_.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+_.x,u=f.height+_.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var m=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=n,this.set("canvas",m),s&&(this.group=s),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),s=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,s,o(-this.angle))),{x:r.x-s.x,y:r.y-s.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,s,n){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=n?new o(i[n],i):new o(i);s&&s(t)}))}))},e.Object.__uid=0)}(e),S=x.util.degreesToRadians,C={left:-.5,center:0,right:.5},w={top:-.5,center:0,bottom:.5},x.util.object.extend(x.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,s){var n,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof r?r=C[r]:r-=.5,"string"==typeof i?i=w[i]:i-=.5,"string"==typeof s?s=w[s]:s-=.5,o=s-i,((n=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+n*a.x,l=t.y+o*a.y),new x.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?x.util.rotatePoint(r,t,S(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?x.util.rotatePoint(r,t,S(this.angle)):r},getCenterPoint:function(){var t=new x.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,s,n=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(n,"center","center",e,i):new x.Point(this.left,this.top),s=new x.Point(t.x,t.y),this.angle&&(s=x.util.rotatePoint(s,n,-S(this.angle))),s.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),s=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",s.x),this.set("top",s.y)},adjustPosition:function(t){var e,i,r=S(this.angle),s=this.getScaledWidth(),n=x.util.cos(r)*s,o=x.util.sin(r)*s;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=n*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=x.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(x.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new x.Point(i.tl.x,i.tl.y),new x.Point(i.tr.x,i.tr.y),new x.Point(i.br.x,i.br.y),new x.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var s=this.getCoords(i,r);return"Intersection"===x.Intersection.intersectPolygonRectangle(s,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===x.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),s=e?t.aCoords:t.lineCoords,n=0,o=t._getImageLines(s);n<4;n++)if(!t.containsPoint(r[n],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var s=this.getBoundingRect(i,r);return s.left>=t.x&&s.left+s.width<=e.x&&s.top>=t.y&&s.top+s.height<=e.y},containsPoint:function(t,e,i,r){var s=this._getCoords(i,r),n=(e=e||this._getImageLines(s),this._findCrossPoints(t,e));return 0!==n&&n%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,s,n=0;for(var o in e)if(!((s=e[o]).o.y=t.y&&s.d.y>=t.y||(s.o.x===s.d.x&&s.o.x>=t.x?r=s.o.x:(i=(s.d.y-s.o.y)/(s.d.x-s.o.x),r=-(t.y-0*t.x-(s.o.y-i*s.o.x))/(0-i)),r>=t.x&&(n+=1),2!==n)))break;return n},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",s=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=s,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,s=(e=e||{}).noStyle,n=e.reviver,o=s?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+x.Object.__uid++,r='\n'+h.toClipPathSVG(n)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,s?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[_]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),n?n(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=x.util.object.extend,e="stateProperties";function i(e,i,r){var s={};r.forEach((function(t){s[t]=e[t]})),t(e[i],s,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var s=0,n=t.length;s=0;h--)if(s=a[h],this.isControlVisible(s)&&(r=this._getImageLines(e?this.oCoords[s].touchCorner:this.oCoords[s].corner),0!==(i=this._findCrossPoints({x:n,y:o},r))&&i%2==1))return this.__corner=s,s;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),s=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/s[0],1/s[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,s=i.x+r,n=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-s/2,-n/2,s,n),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*s,e.y*n),t.lineTo(e.x*s+e.offsetX,e.y*n+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=x.util.sizeAfterTransform(this.width,this.height,e),s=this.strokeWidth,n=this.strokeUniform,o=this.borderScaleFactor,a=r.x+s*(n?this.canvas.getZoom():e.scaleX)+o,h=r.y+s*(n?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,s=this.canvas.getRetinaScaling();return t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(s,n,o){r=o.oCoords[n],s.getVisibility(o,n)&&(i&&(r=x.util.transformPoint(r,i)),s.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),x.util.object.extend(x.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,s=e.onChange||i,n=this;return x.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),n.requestRenderAll(),s()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,s=e.onChange||i,n=this;return x.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),n.requestRenderAll(),s()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,s=e.onChange||i,n=this;return x.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),n.requestRenderAll(),s()},onComplete:function(){n.remove(t),r()}})}}),x.util.object.extend(x.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var s=0,n=i.length;s-1||s&&n.colorProperties.indexOf(s[1])>-1,a=s?this.get(s[0])[s[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(n,t,e,r)},onChange:function(e,o,a){s?n[s[0]][s[1]]=e:n.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,s){r||(n.setCoords(),i.onComplete&&i.onComplete(t,e,s))}};return o?x.util.animateColor(h.startValue,h.endValue,h.duration,h):x.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,s={x1:1,x2:1,y1:1,y2:1};function n(t,e){var i=t.origin,r=t.axis1,s=t.axis2,n=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(s));case a:return Math.min(this.get(r),this.get(s))+.5*this.get(n);case h:return Math.max(this.get(r),this.get(s))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==s[t]&&this._setWidthHeight(),this},_getLeftToOriginX:n({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:n({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,s){s=s||{};var n=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[n.x1||0,n.y1||0,n.x2||0,n.y2||0];r(new e.Line(o,i(n,s)))},e.Line.fromObject=function(t,i){var s=r(t,!0);s.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",s,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var s=i(this.startAngle),n=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(n)*o+" "+e.util.sin(n)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,s=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=s)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");s.left=(s.left||0)-s.radius,s.top=(s.top||0)-s.radius,i(new e.Circle(s))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,s=this.height,n=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(n+e,o),t.lineTo(n+r-e,o),a&&t.bezierCurveTo(n+r-h*e,o,n+r,o+h*i,n+r,o+i),t.lineTo(n+r,o+s-i),a&&t.bezierCurveTo(n+r,o+s-h*i,n+r-h*e,o+s,n+r-e,o+s),t.lineTo(n+e,o+s),a&&t.bezierCurveTo(n+h*e,o+s,n,o+s-h*i,n,o+s-i),t.lineTo(n,o+i),a&&t.bezierCurveTo(n,o+h*i,n+h*e,o,n+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,s){if(!t)return r(null);s=s||{};var n=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);n.left=n.left||0,n.top=n.top||0,n.height=n.height||0,n.width=n.width||0;var o=new e.Rect(i(s?e.util.object.clone(s):{},n));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,s=e.util.array.max,n=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(s(t,"x")||0)-e,height:(s(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,s=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,s=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-s);for(var n=0;n"},toObject:function(t){return s(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,s,n=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var s=e.toObject(t);return e.includeDefaultValues=r,s})),s=e.Object.prototype.toObject.call(this,t);return s.objects=r,s},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var s=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=s;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var n=e.Object.prototype.toDatalessObject.call(this,t);return n.objects=i,n},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,s=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return x.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,s=i.scaleY,n=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&s>e)return this._element=n,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=s);x.filterBackend||(x.filterBackend=x.initFilterBackend());var o=x.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=n.width,l=n.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=s,x.filterBackend.applyFilters([t],n,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var s=x.util.createCanvasElement();s.width=i,s.height=r,this._element=s,this._filteredEl=s}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return x.filterBackend||(x.filterBackend=x.initFilterBackend()),x.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){x.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){x.util.setImageSmoothing(t,this.imageSmoothing),x.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,s=this.width,n=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(s*i,c-d),_=o(n*r,u-f),p=-s/2,m=-n/2,v=o(s,c/i-h),y=o(n,u/r-l);e&&t.drawImage(e,d,f,g,_,p,m,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(x.util.getById(t),e),x.util.addClass(this.getElement(),x.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?x.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=x.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,s=1,n=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(s=c/i,n=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(s=n=x.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*n)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(s=n=x.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/n,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/s,r=u/n)),{width:i,height:r,scaleX:s,scaleY:n,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),x.Image.CSS_CANVAS="canvas-img",x.Image.prototype.getSvgSrc=x.Image.prototype.getSrc,x.Image.fromObject=function(t,e){var i=x.util.object.clone(t);x.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):x.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],x.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],x.util.enlivenObjectEnlivables(i,i,(function(){var r=new x.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},x.Image.fromURL=function(t,e,i){x.util.loadImage(t,(function(t,r){e&&e(new x.Image(t,i),r)}),null,i&&i.crossOrigin)},x.Image.ATTRIBUTE_NAMES=x.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),x.Image.fromElement=function(t,i,r){var s=x.parseAttributes(t,x.Image.ATTRIBUTE_NAMES);x.Image.fromURL(s["xlink:href"],i,e(r?x.util.object.clone(r):{},s))})}(e),x.util.object.extend(x.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,s=this;return x.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){s.rotate(t),r()},onComplete:function(){s.setCoords(),i()}})}}),x.util.object.extend(x.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}x.isWebglSupported=function(e){if(x.isLikelyNode)return!1;e=e||x.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),s=!1;if(r){x.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),s=x.maxTextureSize>=e;for(var n=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,n[o])){x.webGlPrecision=n[o];break}}return this.isSupported=s,s},x.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var s="undefined"!=typeof ArrayBuffer,n="undefined"!=typeof Uint8ClampedArray;if(r&&i&&s&&n){var o=x.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(x.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=E);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),E.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=E):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=x.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},s=i.getContext("webgl",r);s||(s=i.getContext("experimental-webgl",r)),s&&(s.clearColor(0,0,0,0),this.canvas=i,this.gl=s)},applyFilters:function(t,e,i,r,s,n){var o,a=this.gl;n&&(o=this.getCachedTexture(n,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:s},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,s=t.destinationWidth,n=t.destinationHeight;i===s&&r===n||(e.width=s,e.height=n)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),s.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var s=t.createTexture();return t.bindTexture(t.TEXTURE_2D,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),s},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),s=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),s&&(e.vendor=s.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}x.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,s){var n=s.getContext("2d");n.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:n.getImageData(0,0,i,r),originalEl:e,originalImageData:n.getImageData(0,0,i,r),canvasEl:s,ctx:n,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(s.width=o.imageData.width,s.height=o.imageData.height),n.putImageData(o.imageData,0,0),o}}}(),x.Image=x.Image||{},x.Image.filters=x.Image.filters||{},x.Image.filters.BaseFilter=x.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==x.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+x.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(s,e),t.compileShader(s),!t.getShaderParameter(s,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(s));var n=t.createProgram();if(t.attachShader(n,r),t.attachShader(n,s),t.linkProgram(n),!t.getProgramParameter(n,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(n));var o=this.getAttributeLocations(t,n),a=this.getUniformLocations(t,n)||{};return a.uStepW=t.getUniformLocation(n,"uStepW"),a.uStepH=t.getUniformLocation(n,"uStepH"),{program:n,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,s=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,s),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=x.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),x.Image.filters.BaseFilter.fromObject=function(t,e){var i=new x.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,s,n,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(n=0;n=S||o<0||o>=y||(h=4*(a*y+o),l=p[f*m+d],e+=_[h]*l,i+=_[h+1]*l,r+=_[h+2]*l,b||(s+=_[h+3]*l));w[n]=e,w[n+1]=i,w[n+2]=r,w[n+3]=b?_[n+3]:s}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,s=r.length,n=this.mode;for(e=0;el[0]&&s>l[1]&&n>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,s,n,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,s=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var s,n=e.width,a=e.height,h=o(n*i),l=o(a*r);"sliceHack"===this.resizeType?s=this.sliceByTwo(t,n,a,h,l):"hermite"===this.resizeType?s=this.hermiteFastResize(t,n,a,h,l):"bilinear"===this.resizeType?s=this.bilinearFiltering(t,n,a,h,l):"lanczos"===this.resizeType&&(s=this.lanczosResize(t,n,a,h,l)),t.imageData=s},sliceByTwo:function(t,i,s,n,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=s*c,_=e.filterBackend.resources,p=0,m=0,v=i,y=0;for(_.sliceByTwo||(_.sliceByTwo=document.createElement("canvas")),((a=_.sliceByTwo).width<1.5*i||a.height=e)){M=r(1e3*n(x-C.x)),S[M]||(S[M]={});for(var L=w.y-y;L<=w.y+y;L++)L<0||L>=o||(F=r(1e3*n(L-C.y)),S[M][F]||(S[M][F]=f(s(i(M*p,2)+i(F*m,2))/1e3)),(T=S[M][F])>0&&(E+=T,O+=T*c[I=4*(L*e+x)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(b*a+h)]=O/E,d[I+1]=R/E,d[I+2]=A/E,d[I+3]=D/E}return++h1&&F<-1||(y=2*F*F*F-3*F*F+1)>0&&(T+=y*f[3+(M=4*(D+E*e))],C+=y,f[M+3]<255&&(y=y*f[M+3]/250),w+=y*f[M],b+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=w/S,_[v+1]=b/S,_[v+2]=x/S,_[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,s=Math.floor(255*this.contrast),n=259*(s+255)/(255*(259-s));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,s=i.length,n=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,s=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,s,n){this._renderChars(t,e,i,r,s,n)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,s,n,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,_=this._textLines.length;g<_;g++)if(e=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){r=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,s=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,m=r.length;p=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,n,o),u+=n.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var s=t+i.kernedWidth/2,n=this.path,o=e.util.getPointOnPath(n.path,s,n.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,s){var n,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=n=this._getWidthOfCharSpacing(),l+=n);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!s){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,s=e.length;r0){var E=v+n+u;"rtl"===this.direction&&(E=this.width-E-d),l&&m&&(t.fillStyle=m,t.fillRect(E,c+w*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,m=p,r=s,o=a}else d+=f.kernedWidth;E=v+n+u,"rtl"===this.direction&&(E=this.width-E-d),t.fillStyle=p,g&&p&&t.fillRect(E,c+w*r+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,s=this.fontFamily,n=e.Text.genericFonts.indexOf(s.toLowerCase())>-1,o=void 0===s||s.indexOf("'")>-1||s.indexOf(",")>-1||s.indexOf('"')>-1||n?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),s=["\n"],n=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}x.IText=x.util.createClass(x.Text,x.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,s,n=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(s.left*=-1),this.cursorOffsetCache=s,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,s=i.charIndex>0?i.charIndex-1:0,n=this.getValueOfPropertyAt(r,s,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,s,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-n*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,s,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,n)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,s=-1!==this.textAlign.indexOf("justify"),n=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=n.lineIndex,h=o.lineIndex,l=n.charIndex<0?0:n.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+_,y=p-_,S=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",S=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,S),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),x.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var s in e.styles[r])t(e.styles[r][s]);x.Object._fromObject("IText",e,i,"text")}}(),b=x.util.object.clone,x.util.object.extend(x.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],x.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var s;return s={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){s.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return s.isAborted}}),s},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),s=x.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:s,selectionEnd:s};var n=i.slice(t,e);return{selectionStart:s,selectionEnd:s+x.util.string.graphemeSplit(n).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,s=i.charIndex,n=this.getValueOfPropertyAt(r,s,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+n},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-n,g=d-n,_=c.clientWidth/u,p=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=_,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:n+"px",charHeight:n}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,s=this.get2DCursorLocation(t,!0),n=this.get2DCursorLocation(e,!0),o=s.lineIndex,a=s.charIndex,h=n.lineIndex,l=n.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=b(this.styles);for(var r in this.styles){var s=parseInt(r,10);s>t&&(this.styles[s+e]=i[s],i[s-e]||delete this.styles[s])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var s,n={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(s=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,n[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=n,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:b(r[i-1])}:s?this.styles[t+i]={0:b(s)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var s=this.styles[t],n=s?b(s):{};for(var o in i||(i=1),n){var a=parseInt(o,10);a>=e&&(s[a+i]=n[a],n[a-i]||delete s[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=b(r[i]));else if(s)for(var h=s[e?e-1:1];h&&i--;)this.styles[t][e+i]=b(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),s=[0],n=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,s[0],i),i=i&&i.slice(s[0]+1)),n&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+s[0],n),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,s[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(s[o]+1);s[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,s[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),x.util.object.extend(x.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,s=0,n=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));s=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+s);for(var c=0,u=e.length;cn||o<0?0:1);return this.flipX&&(a=s-a),a>this._text.length&&(a=this._text.length),a}}),x.util.object.extend(x.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=x.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):x.document.body.appendChild(this.hiddenTextarea),x.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),x.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),x.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),x.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(x.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,s,n,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),s=r.lineIndex;if(s===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var n=r.charIndex,o=this._getWidthBeforeCursor(s,n),a=this._getIndexOnLine(s+1,o);return this._textLines[s].slice(n).length+a+1+this.missingNewlineOffset(s)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),s=r.lineIndex;if(0===s||t.metaKey||33===t.keyCode)return-i;var n=r.charIndex,o=this._getWidthBeforeCursor(s,n),a=this._getIndexOnLine(s-1,o),h=this._textLines[s].slice(0,n),l=this.missingNewlineOffset(s-1);return-this._textLines[s-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,s=this._textLines[t],n=this._getLineLeftOffset(t),o=0,a=0,h=s.length;ae){r=!0;var l=n-i,c=n,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var s=x.util.string.graphemeSplit(t);this.insertNewStyleBlock(s,i,e),this._text=[].concat(this._text.slice(0,i),s,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=x.util.toFixed,e=/ +/g;x.util.object.extend(x.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],s=[],n=t;this._setSVGBg(s);for(var o=0,a=this._textLines.length;o",x.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var s,n,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)h=g===_||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(s=s||this.getCompleteStyleDeclaration(e,g),n=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(s,n)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",s=n,i+=d,d=0)},_pushTextBgRect:function(e,i,r,s,n,o){var a=x.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var s,n,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,s={},n=0;n0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&n>0&&(i++,r++),s[n]={line:e,offset:i},r+=t.graphemeLines[n].length,i+=t.graphemeLines[n].length;return s},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,s=!1,n=this._styleMap[t],o=this._styleMap[t+1];for(var a in n&&(t=n.line,r=n.offset),o&&(s=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!s||hr&&!p?(a.push(h),h=[],n=f,p=!0):n+=m,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(h),_+s>this.dynamicMinWidth&&(this.dynamicMinWidth=_-m+s),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),s=new Array(r.length),n=0;n{},898:()=>{},245:()=>{}},I={};function E(t){var e=I[t];if(void 0!==e)return e.exports;var i=I[t]={exports:{}};return T[t](i,i.exports,E),i.exports}E.d=(t,e)=>{for(var i in e)E.o(e,i)&&!E.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},E.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var O={};(()=>{let t;E.d(O,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?E(653).fabric:{version:"5.2.1"}})();var R=O.R; +import{Howl as t}from"dm-howler";const e="undefined"==typeof self;let i,r,s,n,o;if("undefined"!=typeof navigator&&(i=navigator,r=i.userAgent,s=i.platform,n=i.mediaDevices),!e){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:i.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:s,search:"Win"},Mac:{str:s},Linux:{str:s}};let n="unknownBrowser",a=0,h="unknownOS";for(let e in t){const i=t[e]||{};let s=i.str||r,o=i.search||e,h=i.verStr||r,l=i.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(o)){n=e;for(let t of l){let e=h.indexOf(t);if(-1!=e){a=parseFloat(h.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let s=i.str||r,n=i.search||t;if(-1!=s.indexOf(n)){h=t;break}}"Linux"==h&&-1!=r.indexOf("Windows NT")&&(h="HarmonyOS"),o={browser:n,version:a,OS:h}}e&&(o={browser:"ssr",version:0,OS:"ssr"});const a="undefined"!=typeof WebAssembly&&r&&!(/Safari/.test(r)&&!/Chrome/.test(r)&&/\(.+\s11_2_([2-6]).*\)/.test(r)),h=!("undefined"==typeof Worker),l=!(!n||!n.getUserMedia),c=async()=>{let t=!1;if(l)try{(await n.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===o.browser&&o.version>66||"Safari"===o.browser&&o.version>13||"OPR"===o.browser&&o.version>43||"Edge"===o.browser&&o.version;const u=(()=>{if(!e&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})(),d=" is not allowed to change after `createInstance` or `loadWasm` is called.",f=!e&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",g=!e&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",_=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let i=0;it&&"object"==typeof t&&"function"==typeof t.then;class w extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(C(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,C(t)?e=t:"function"==typeof t&&(e=new Promise(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}}const b=["iPhone","iPad","Android","HarmonyOS"].includes(o.OS)?2048:4096;class x{constructor(){this._instanceID=void 0,this._ifSaveOriginalImageInACanvas=!1,this.oriCanvas=null,this.oriCanvasData=null,this.canvas=null,this.bFilterRegionInJs=!1,this._region=null,this._timeStartDecode=null,this._timeEnterInnerDBR=null,this._timeGetMessage=null,this.decodeRecords={},this.bDestroyed=!1,this._lastErrorCode=0,this._lastErrorString="",this._lastInnerDecodeDuration=0,this.intervalTime=0,this._intervalGetVideoFrame=0,this.array_getFrameTimeCost=[],this.array_decodeFrameTimeCost=[],this._indexCurrentDecodingFrame=0,this._arrPolygons=[],this._bPauseScan=!1,this._intervalDetectVideoPause=1e3,this._soundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",this.beepSound=new t({src:["data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"],onplayerror:(t,e)=>{console.warn(`Sound '${t}' playback failure: ${e}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=b,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`license`"+d);i._license=e})(x,t)}static get productKeys(){return this._license}static set productKeys(t){x.license=t}static get handshakeCode(){return this._license}static set handshakeCode(t){x.license=t}static get organizationID(){return this._license}static set organizationID(t){x.license=t}static set sessionPassword(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+d);i._sessionPassword=e})(x,t)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:a,worker:h,getUserMedia:l,camera:await c(),browser:o.browser,version:o.version,OS:o.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(t){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");x._engineResourcePath=(t=>{if(null==t&&(t="./"),!e){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get licenseServer(){return this._licenseServer}static set licenseServer(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+d);i._licenseServer=_(e)})(x,t)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+d);i._deviceFriendlyName=e||""})(x,t)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(t){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");x.__bUseFullFeature=t}static isImageSource(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&"getImage"in t}static isDSImage(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&("data"in t&&("width"in t&&("height"in t&&"pixelFormat"in t)))}static isDCEFrame(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&("data"in t&&("region"in t&&("sx"in t&&("sy"in t&&("width"in t&&("height"in t&&(("colorMode"in t||"pixelFormat"in t)&&("timeSpent"in t&&("timeStamp"in t&&("isCropped"in t&&("toCanvas"in t&&("_sWidth"in t&&("_sHeight"in t&&"_bUseWebGL"in t)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(t){this._ifSaveOriginalImageInACanvas=t}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(t){this._region=t,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var t;return null===(t=x._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",x.engineResourcePath)}static set defaultUIElementURL(t){x._defaultUIElementURL=t}static _fireHTTPSWarnning(){x.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{x.onWarning&&x.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new t({src:[this._soundSource],onplayerror:(t,e)=>{console.warn(`Sound '${t}' playback failure: ${e}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(t){this.bPlaySoundOnSuccessfulRead="never"!==t&&t}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(t){this.bVibrateOnSuccessfulRead="never"!==t&&t}set dce(t){this._dce=t}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(t){this._maxCvsSideLength=t,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",t)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;x._onLog&&x._onLog("_registerDCEControler()");const t=this.dce;this._dceControler=t._createControler();const e=this._dceControler;e.register(this),e.setDisiredValue(this,"refreshInterval",200),e.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(t){"ReferenceError"===t.name&&window&&(window.ResizeObserver=void 0)}const i=t.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{i?i===e._innerSetUI&&(await t.setUIElement(`${r.engineResourcePath}dce.ui.html`),e._innerSetUI=t.getUIElement()):(await t.setUIElement(`${r.engineResourcePath}dbr.ui.html`),e._innerSetUI=t.getUIElement())}catch(e){await t.setUIElement(r.defaultUIElementURL)}else i||await t.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async t=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let e=await this._decode_DCEFrame(t,{bCopyData:!1}),i=null;if(e&&e.length){const{sx:r,sy:s,width:n,height:o,_sWidth:a,_sHeight:h}=t;i=e.map((t=>({localizationResult:JSON.parse(JSON.stringify(t.localizationResult))}))),x.recalculateResultLocation(i,r,s,a,h,n,o)}if(this._drawResults(i,e),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let t of e)this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))},t.on("cameraChange",this.callbackCameraChange),t.on("resolutionChange",this.callbackResolutionChange),t.on("cameraClose",this.callbackCameraClose),t.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(x._onLog&&x._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(t,e){if(null==t)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(t&&t.isCameraEnhancer)this.dce=t,await this._registerDCEControler(),this._imgSource=null;else{if(!x.isImageSource(t))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=t}e&&e.resultsHighlightBaseShapes&&(this._drawingItemNamespace=e.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:t,l:e,ls:i,sp:r,rmk:s}=(t=>{const e=t;if(e._pLoad.isEmpty){let t,i,r=e._license||"",s=JSON.parse(JSON.stringify(e._licenseServer)),n=e._sessionPassword,o=0;if(r.startsWith("t")||r.startsWith("f"))o=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))o=1;else{o=2;const e=r.indexOf(":");if(-1!=e&&(r=r.substring(e+1)),r.startsWith("DLS2")){let e;try{let t=r.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===s.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),s=_(t)}!n&&e.sessionPassword&&(n=e.sessionPassword),t=e.remark}("200001"===r||r.startsWith("200001-"))&&(s&&s.length||(r="")),r||(o=1)}if(o&&(globalThis.crypto||(i="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(i="Require https to use online key in this browser.")),i){if(1!==o)throw new Error(i);o=0,console.warn(i),e._lastErrorCode=-1,e._lastErrorString=i}return 1===o&&(r="",console.warn("Applying for a public trial license ...")),{lt:o,l:r,ls:s,sp:n,rmk:t}}throw new Error("Can't preprocess license again"+d)})(x);this._pLoad.task=async(n,a)=>{let h=x.engineResourcePath+x._workerName;x.engineResourcePath.startsWith(location.origin)||(h=await fetch(h).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),x._dbrWorker=new Worker(h),x._dbrWorker.onerror=t=>{let e=new Error(t.message);a(e)},x._dbrWorker.onmessage=async e=>{let i=e.data?e.data:e;switch(i.type){case"log":x._onLog&&x._onLog(i.message);break;case"load":{i.message&&(i.message=i.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let e,r=!1;1===t&&(r=!0,i.message||(i.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),i.success?(x._dbrWorker.onerror=null,x._version=i.version+"(JS "+x._jsVersion+"."+x._jsEditVersion+")",x._onLog&&x._onLog("load dbr worker success"),i.message&&console.warn(i.message)):(e=new Error(i.message),e.stack=i.stack+"\n"+e.stack,e.ltsErrorCode=i.ltsErrorCode,r||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&x.showDialog(i.success?"warn":"error",i.message),i.success?n():a(e);break}case"task":{let t=i.id,e=i.body;try{x._taskCallbackMap.get(t)(e),x._taskCallbackMap.delete(t)}catch(e){throw x._taskCallbackMap.delete(t),e}break}default:x._onLog&&x._onLog(e)}},x._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:x.engineResourcePath,bUseFullFeature:x._bUseFullFeature,bd:x._bWasmDebug,v:x._jsVersion,brtk:!!t,bptk:1===t,l:e,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:o,cv:x.authCacheVersion,fn:x.deviceFriendlyName,ls:i,sp:r,rmk:s})}}await this._pLoad}static async showDialog(t,e){await(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let r=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let s=await r.text();if(!s.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let n=document.createElement("div");n.innerHTML=s;let o=[];for(let t=0;t{if(t==e.target){a.remove();for(let t of o)t.remove()}}));else if(!l&&t.classList.contains("dls-license-icon-close"))l=t,t.addEventListener("click",(()=>{a.remove();for(let t of o)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),r=e.indexOf("]",i),s=e.indexOf("(",r),n=e.indexOf(")",s);if(-1==i||-1==r||-1==s||-1==n){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let o=document.createElement("a"),a=e.substring(i+1,r);o.innerText=a;let h=e.substring(s+1,n);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(n+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})(this,t,e)}static async createInstanceInWorker(t=!1){return await x.loadWasm(),await new Promise(((e,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(t=>{if(t.success)return e(t.instanceID);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),x._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:t})}))}static async createInstance(){let t=new x;return t._instanceID=await x.createInstanceInWorker(),x._fireHTTPSWarnning(),t}async clearMapDecodeRecord(){return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(t){x._onLog&&x._onLog("decode(source: any)"),x._onLog&&(this._timeStartDecode=Date.now());{let e={};return!this.region||this.region instanceof Array||(e.region=JSON.parse(JSON.stringify(this.region))),t instanceof Blob?await this._decode_Blob(t,e):t instanceof ArrayBuffer?await this._decode_ArrayBuffer(t,e):t instanceof Uint8Array||t instanceof Uint8ClampedArray?await this._decode_Uint8Array(t,e):t instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap?await this._decode_Image(t,e):t instanceof HTMLCanvasElement?await this._decode_Canvas(t,e):t instanceof HTMLVideoElement?await this._decode_Video(t,e):"string"==typeof t?"data:image/"==t.substring(0,11)?await this._decode_Base64(t,e):await this._decode_Url(t,e):x.isDCEFrame(t)?(e.bCopyData=!0,await this._decode_DCEFrame(t,e)):x.isDSImage(t)?(e.bCopyData=!0,await this._decode_DSImage(t,e)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(t){let e={};return!this.region||this.region instanceof Array||(e.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(t,e)}async decodeUrl(t){let e={};return!this.region||this.region instanceof Array||(e.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(t,e)}async _decodeBuffer_Uint8Array(t,e,i,r,s,n,o){return await new Promise(((a,h)=>{let l=x._nextTaskID++;x._taskCallbackMap.set(l,(t=>{if(t.success){let e,i=x._onLog?Date.now():0;x._onLog&&x._onLog("worker return result: "+i),this._lastInnerDecodeDuration=t.duration;try{e=this._handleRetJsonString(t.decodeReturn)}catch(t){return h(t)}if(x._onLog){let t=Date.now();x._onLog("DBR getting message from worker timestamp: "+i),x._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),x._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),x._onLog("Handling results from DBR worker costs: "+(t-i)),x._onLog("Total decoding image costs: "+(t-this._timeStartDecode))}return a(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,h(e)}})),this._timeEnterInnerDBR=Date.now(),x._onLog&&x._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),x._dbrWorker.postMessage({type:"decodeBuffer",id:l,instanceID:this._instanceID,body:{buffer:t,width:e,height:i,stride:r,format:s,orientation:n,config:o}},[t.buffer]),x._onLog&&o&&o.timeStamp&&x._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(t,e,i,r,s,n,o){x._onLog&&x._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const a=t.arrayBuffer?await t.arrayBuffer():await new Promise(((e,i)=>{let r=new FileReader;r.readAsArrayBuffer(t),r.onload=()=>{e(r.result)},r.onerror=()=>{i(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(a),e,i,r,s,n,o)}async decodeBuffer(t,e,i,r,s,n,o){let a;return x._onLog&&x._onLog("decodeBuffer(buffer,width,height,stride,format)"),x._onLog&&(this._timeStartDecode=Date.now()),t instanceof Uint8Array||t instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(t,e,i,r,s,n,o):t instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(t),e,i,r,s,n,o):t instanceof Blob&&(a=await this._decodeBuffer_Blob(t,e,i,r,s,n,o)),a}async _decodeFileInMemory_Uint8Array(t){return await new Promise(((e,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(t=>{if(t.success){let r;this._lastInnerDecodeDuration=t.duration;try{r=this._handleRetJsonString(t.decodeReturn)}catch(t){return i(t)}return e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),x._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:t}})}))}async getRuntimeSettings(){return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success){let e=JSON.parse(i.results);return null!=this.userDefinedRegion&&(e.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"getRuntimeSettings",id:i,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let e;if("string"==typeof t)if("speed"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=3,e.expectedBarcodesCount=0,e.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=5,e.expectedBarcodesCount=512,e.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region}else if("dense"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=9,e.expectedBarcodesCount=0,e.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,e.region=t.region,e.deblurLevel=3,e.expectedBarcodesCount=0,e.localizationModes=[2,8,0,0,0,0,0,0]}else e=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(e=JSON.parse(JSON.stringify(t)),e.region instanceof Array){let t=e.region;[t.regionLeft,t.regionTop,t.regionLeft,t.regionBottom,t.regionMeasuredByPercentage].some((t=>void 0!==t))&&(e.region={regionLeft:t.regionLeft||0,regionTop:t.regionTop||0,regionRight:t.regionRight||0,regionBottom:t.regionBottom||0,regionMeasuredByPercentage:t.regionMeasuredByPercentage||0})}}if(!x._bUseFullFeature){if(0!=(e.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.BF_DATAMATRIX))||0!=e.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=e.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let t=e.region;if(t instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(t)),(t.regionLeft||t.regionTop||t.regionRight||t.regionBottom||t.regionMeasuredByPercentage)&&(t.regionLeft||t.regionTop||100!=t.regionRight||100!=t.regionBottom||!t.regionMeasuredByPercentage)?this.region=t:this.region=null,e.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(e.intermediateResultTypes|=S.IRT_TYPED_BARCODE_ZONE),await new Promise(((t,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.updateReturn)}catch(t){i(t)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),x._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(e)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=b,await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=b,await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!x._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t(i.results);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(t){if(!x._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof t)t=t;else{if("object"!=typeof t)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");t=JSON.stringify(t)}return await new Promise(((e,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.initReturn)}catch(t){i(t)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}})),x._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:t}})}))}async _decode_Blob(t,e){x._onLog&&x._onLog("_decode_Blob(blob: Blob)");let i=null,r=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(r=await function(t){return new Promise(((e,i)=>{let r=URL.createObjectURL(t),s=new Image;s.dbrObjUrl=r,s.src=r,s.onload=()=>{e(s)},s.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let s=await this._decode_Image(i||r,e);return i&&i.close(),s}async _decode_ArrayBuffer(t,e){return await this._decode_Blob(new Blob([t]),e)}async _decode_Uint8Array(t,e){return await this._decode_Blob(new Blob([t]),e)}async _decode_Image(t,e){x._onLog&&x._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),e=e||{};let i,r,s=t instanceof HTMLImageElement?t.naturalWidth:t.width,n=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(s,n);if(o>this._maxCvsSideLength){let t=this._maxCvsSideLength/o;i=Math.round(s*t),r=Math.round(n*t)}else i=s,r=n;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,s,n,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._decode_Canvas(a,e)}async _decode_Canvas(t,e){if(x._onLog&&x._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let i=(t.ctx2d||t.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(i,t.width,t.height,4*t.width,p.IPF_ABGR_8888,0,e)}async _decode_Video(t,e){if(x._onLog&&x._onLog("_decode_Video(video)"),!(t instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";e=e||{};let i,r,s=t.videoWidth,n=t.videoHeight,o=Math.max(s,n);if(o>this._maxCvsSideLength){let t=this._maxCvsSideLength/o;i=Math.round(s*t),r=Math.round(n*t)}else i=s,r=n;this.canvas||(this.canvas=document.createElement("canvas"));const a=this.canvas;a.width===i&&a.height===r||(a.width=i,a.height=r),a.ctx2d||(a.ctx2d=a.getContext("2d",{willReadFrequently:!0}));return a.ctx2d.drawImage(t,0,0,s,n,0,0,i,r),await this._decode_Canvas(a,e)}async _decode_DCEFrame(t,e){if(x._onLog&&x._onLog("_decode_DCEFrame(dceFrame)"),!x.isDCEFrame(t))return[];let i=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:r,height:s,colorMode:n,pixelFormat:o,stride:a,timeStamp:h}=t;let l;l=e&&e.bCopyData?new Uint8Array(t.data):t.data;let c=null;if(e?(c=JSON.parse(JSON.stringify(e)),c.timeStamp=h):c={timeStamp:h},o&&a)if("grey"===o)i=await this._decodeBuffer_Uint8Array(l,r,s,a,p.IPF_GrayScaled,0,c);else if("rgba"===o)i=await this._decodeBuffer_Uint8Array(l,r,s,a,p.IPF_ABGR_8888,0,c);else{if("bgra"!==o)throw new Error(`Pixel format '${o}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(l,r,s,a,p.IPF_ARGB_8888,0,c)}else if("grey"===n)i=await this._decodeBuffer_Uint8Array(l,r,s,r,p.IPF_GrayScaled,0,c);else if("rgba"===n)i=await this._decodeBuffer_Uint8Array(l,r,s,4*r,p.IPF_ABGR_8888,0,c);else{if("bgra"!==n)throw new Error(`Color mode '${n}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(l,r,s,4*r,p.IPF_ARGB_8888,0,c)}return i}async _decode_DSImage(t,e){if(x._onLog&&x._onLog("_decode_DSImage(dsImage)"),!x.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const t=document.createElement("canvas");let e;switch(t.width=this.width,t.height=this.height,this.pixelFormat){case"grey":e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{e(r.response)},r.onerror=()=>{i(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(i,e)}}async _decode_FilePath(t,e){throw x._onLog&&x._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(t,e,i,r,s,n,o){if(t.length>0)for(let a of t){let t=a.localizationResult;2==t.resultCoordinateType&&(t.x1*=.01*n,t.x2*=.01*n,t.x3*=.01*n,t.x4*=.01*n,t.y1*=.01*o,t.y2*=.01*o,t.y3*=.01*o,t.y4*=.01*o);let h=n/r,l=o/s;t.x1=t.x1/h+e,t.x2=t.x2/h+e,t.x3=t.x3/h+e,t.x4=t.x4/h+e,t.y1=t.y1/l+i,t.y2=t.y2/l+i,t.y3=t.y3/l+i,t.y4=t.y4/l+i,2==t.resultCoordinateType&&(t.x1*=100/r,t.x2*=100/r,t.x3*=100/r,t.x4*=100/r,t.y1*=100/s,t.y2*=100/s,t.y3*=100/s,t.y4*=100/s)}}static BarcodeReaderException(t,e){let i,r=m.DBR_UNKNOWN;return"number"==typeof t?(r=t,i=new Error(e)):i=new Error(t),i.code=r,i}_handleRetJsonString(t){let e=m;if(t.textResults){for(let e=0;e{let i=e.indexOf(":");t[e.substring(0,i)]=e.substring(i+1)})),i.exception=t}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!x._setWarnnedEx.has(t.description)&&(x._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==e.DBR_SUCCESS)return t.data;throw x.BarcodeReaderException(t.exception,t.description)}async setModeArgument(t,e,i,r){return await new Promise(((s,n)=>{let o=x._nextTaskID++;x._taskCallbackMap.set(o,(t=>{if(t.success){try{this._handleRetJsonString(t.setReturn)}catch(t){return n(t)}return s()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),x._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:t,index:e,argumentName:i,argumentValue:r}})}))}async getModeArgument(t,e,i){return await new Promise(((r,s)=>{let n=x._nextTaskID++;x._taskCallbackMap.set(n,(t=>{if(t.success){let e;try{e=this._handleRetJsonString(t.getReturn)}catch(t){return s(t)}return r(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}})),x._dbrWorker.postMessage({type:"getModeArgument",id:n,instanceID:this._instanceID,body:{modeName:t,index:e,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success)return t(i.results);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}})),x._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),e=[];for(let i of t)if(i.dataType==v.IMRDT_IMAGE)for(let t of i.results){const i=t.bytes;let r;switch(x._onLog&&x._onLog(" "+i.length+" "+i.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case p.IPF_ABGR_8888:r=new Uint8ClampedArray(i);break;case p.IPF_RGB_888:{const t=i.length/3;r=new Uint8ClampedArray(4*t);for(let e=0;e=s)break;r[o]=r[o+1]=r[o+2]=(128&e)/128*255,r[o+3]=255,e<<=1}}break}default:console.warn("unknow intermediate image",t)}if(!r)continue;let s=new ImageData(r,t.width,t.height),n=document.createElement("canvas");n.width=t.width,n.height=t.height,n.getContext("2d").putImageData(s,0,0),e.push(n)}return e}async getScanSettings(){return await new Promise(((t,e)=>{let i=x._nextTaskID++;x._taskCallbackMap.set(i,(i=>{if(i.success){let e=i.results;return e.intervalTime=this.intervalTime,e.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,e.soundOnSuccessfullRead=this.soundSource,e.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,e.vibrateDuration=this.vibrateDuration,e.captureAndDecodeInParallel=this.captureAndDecodeInParallel,e.autoZoom=this.autoZoom,e.autoFocus=this.autoFocus,e.autoSuggestTip=this.autoSuggestTip,t(e)}{let t=new Error(i.message);return t.stack+="\n"+i.stack,e(t)}})),x._dbrWorker.postMessage({type:"getScanSettings",id:i,instanceID:this._instanceID})}))}async updateScanSettings(t){if(!t)return;const e=JSON.parse(JSON.stringify(t));if(e.autoZoom||e.autoFocus||e.autoSuggestTip){if(!x._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const t=await this.getRuntimeSettings();t.intermediateResultTypes|=S.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(t)}return e.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(e.intervalTime,0),delete e.intervalTime),e.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=e.whenToPlaySoundforSuccessfulRead,delete e.whenToPlaySoundforSuccessfulRead),e.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=e.soundOnSuccessfullRead,delete e.soundOnSuccessfullRead),e.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=e.whenToVibrateforSuccessfulRead,delete e.whenToVibrateforSuccessfulRead),e.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=e.vibrateDuration,delete e.vibrateDuration),e.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=e.captureAndDecodeInParallel,delete e.captureAndDecodeInParallel),e.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=e.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=e.autoZoom,delete e.autoZoom),e.hasOwnProperty("autoFocus")&&(this.autoFocus=e.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete e.autoFocus),e.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=e.autoSuggestTip,delete e.autoFocus),await new Promise(((t,i)=>{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack+="\n"+e.stack,i(t)}})),x._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:e}})}))}_cloneDecodeResults(t){if(t instanceof Array){let e=[];for(let i of t)e.push(this._cloneDecodeResults(i));return e}{let e=t,i=JSON.parse(JSON.stringify(e,((t,e)=>"oriVideoCanvas"==t||"searchRegionCanvas"==t?void 0:e)));return i}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return x._onLog&&x._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));x._onLog&&x._onLog("======= once read ======="),x._onLog&&(this._timeStartDecode=Date.now());let t=null,e=null;if(this.dce)t=this._getVideoFrame();else if(this._imgSource&&(e=await this._imgSource.getImage(),!x.isDSImage(e)))throw new Error("Invalid DSImage.");if(!t&&!e)return x._onLog&&x._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let i=[];if(t){i=await this._decode_DCEFrame(t,{bScanner:!0,bCopyData:!1});let e=null;if(i&&i.length){const{sx:r,sy:s,width:n,height:o,_sWidth:a,_sHeight:h}=t;e=i.map((t=>({resultState:t.resultState,localizationResult:JSON.parse(JSON.stringify(t.localizationResult))}))),x.recalculateResultLocation(e,r,s,a,h,n,o)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(e,i),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else e&&(i=await this._decode_DSImage(e,{bScanner:!0,bCopyData:!1}));return i})().then((t=>{if(x._onLog&&x._onLog(t),this.dce&&this.captureAndDecodeInParallel){let t=this.array_decodeFrameTimeCost,e=this.array_getFrameTimeCost;const i=()=>{let i=0;if(e&&e.length){let r=Math.min(...t),s=Math.max(...e);r&&s&&(i=r-s)}else i=0;return i>0?i:0};(()=>{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=i()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&t.length){let e=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?e=t.some((t=>t.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(e=t.some((t=>0==t.resultState))),e&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&t.length){let e=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?e=t.some((t=>t.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(e=t.some((t=>0==t.resultState))),e)try{navigator.vibrate(this.vibrateDuration)}catch(t){console.warn("Vibration not allowed. User interaction required: "+(t.message||t))}}if(this.onImageRead){t=t.filter((t=>t.resultState>=0));const e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead){t=t.filter((t=>0==t.resultState));const e=this._cloneDecodeResults(t);for(let t of e)this.onUniqueRead(t.barcodeText,t)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((t=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),x._onLog&&x._onLog(t.message||t),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==t.message||console.warn(t.message)}))}_getVideoFrame(){if(!this.dce)return null;let t;if(this.captureAndDecodeInParallel){if(x._onLog&&x._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;t=this.dce.getFrameFromBuffer();const e=t=>{if(!t)return;let e=t.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(e)};e(t)}else x._onLog&&x._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),t=this.dce.getFrame();return t}_drawResults(t,e){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const i=this._dbrDrawingLayer;t||(t=[]);let r=this._arrPolygons;for(let s=0;s{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(e),e}stopScanning(t){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[t]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(t){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),t&&t.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(x._onLog&&x._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let t=x._nextTaskID++;x._taskCallbackMap.set(t,(t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}})),x._dbrWorker.postMessage({type:"destroyContext",id:t,instanceID:this._instanceID})}}x._jsVersion="9.6.11",x._jsEditVersion="20230310",x._version=`loading...(JS ${x._jsVersion}.${x._jsEditVersion})`,x._license=f,x._sessionPassword=g,x.browserInfo=o,x._workerName=`dbr-${x._jsVersion}.browser.worker.js`,x._engineResourcePath=u,x._licenseServer=[],x._deviceFriendlyName="",x._isShowRelDecodeTimeInResults=!1,x._bWasmDebug=!1,x._bNeverShowDialog=!1,x.__bUseFullFeature=!0,x._nextTaskID=0,x._taskCallbackMap=new Map,x._pLoad=new w,x._lastErrorCode=0,x._lastErrorString="",x._setWarnnedEx=new Set,x._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var T={653:(t,e,i)=>{var r,s,n,o,a,h,l,c,u,d,f,g,_,p,m,v,y,S,C,w,b,x=x||{version:"5.2.1"};if(e.fabric=x,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?x.document=document:x.document=document.implementation.createHTMLDocument(""),x.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;x.document=T.document,x.jsdomImplForWrapper=i(898).implForWrapper,x.nodeCanvas=i(245).Canvas,x.window=T,DOMParser=x.window.DOMParser}function I(t,e){var i=t.canvas,r=e.targetCanvas,s=r.getContext("2d");s.translate(0,r.height),s.scale(1,-1);var n=i.height-r.height;s.drawImage(i,0,n,r.width,r.height,0,0,r.width,r.height)}function E(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,s=e.destinationHeight,n=r*s*4,o=new Uint8Array(this.imageBuffer,0,n),a=new Uint8ClampedArray(this.imageBuffer,0,n);t.readPixels(0,0,r,s,t.RGBA,t.UNSIGNED_BYTE,o);var h=new ImageData(a,r,s);i.putImageData(h,0,0)}x.isTouchSupported="ontouchstart"in x.window||"ontouchstart"in x.document||x.window&&x.window.navigator&&x.window.navigator.maxTouchPoints>0,x.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,x.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],x.DPI=96,x.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",x.commaWsp="(?:\\s+,?\\s*|,\\s*)",x.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,x.reNonWord=/[ \n\.,;!\?\-]/,x.fontPaths={},x.iMatrix=[1,0,0,1,0,0],x.svgNS="http://www.w3.org/2000/svg",x.perfLimitSizeTotal=2097152,x.maxCacheSideLimit=4096,x.minCacheSideLimit=256,x.charWidthsCache={},x.textureSize=2048,x.disableStyleCopyPaste=!1,x.enableGLFiltering=!0,x.devicePixelRatio=x.window.devicePixelRatio||x.window.webkitDevicePixelRatio||x.window.mozDevicePixelRatio||1,x.browserShadowBlurConstant=1,x.arcToSegmentsCache={},x.boundsOfCurveCache={},x.cachesBoundsOfCurve=!0,x.forceGLPutImageData=!1,x.initFilterBackend=function(){return x.enableGLFiltering&&x.isWebglSupported&&x.isWebglSupported(x.textureSize)?(console.log("max texture size: "+x.maxTextureSize),new x.WebglFilterBackend({tileSize:x.textureSize})):x.Canvas2dFilterBackend?new x.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=x),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:x.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}x.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var r=0,s=i.length;r-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},x.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof x.Gradient||this.set(e,new x.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof x.Pattern?i&&i():this.set(e,new x.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},r=e,s=Math.sqrt,n=Math.atan2,o=Math.pow,a=Math.PI/180,h=Math.PI/2,x.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/h){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/h){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*a},radiansToDegrees:function(t){return t/a},rotatePoint:function(t,e,i){var r=new x.Point(t.x-e.x,t.y-e.y),s=x.util.rotateVector(r,i);return new x.Point(s.x,s.y).addEquals(e)},rotateVector:function(t,e){var i=x.util.sin(e),r=x.util.cos(e);return{x:t.x*r-t.y*i,y:t.x*i+t.y*r}},createVector:function(t,e){return new x.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new x.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var r=x.util.createVector(t,e),s=x.util.createVector(t,i),n=x.util.calcAngleBetweenVectors(r,s),o=n*(0===x.util.calcAngleBetweenVectors(x.util.rotateVector(r,n),s)?1:-1)/2;return{vector:x.util.getHatVector(x.util.rotateVector(r,o)),angle:n}},projectStrokeOnPoints:function(t,e,i){var r=[],s=e.strokeWidth/2,n=e.strokeUniform?new x.Point(1/e.scaleX,1/e.scaleY):new x.Point(1,1),o=function(t){var e=s/Math.hypot(t.x,t.y);return new x.Point(t.x*e*n.x,t.y*e*n.y)};return t.length<=1||t.forEach((function(a,h){var l,c,u=new x.Point(a.x,a.y);0===h?(c=t[h+1],l=i?o(x.util.createVector(c,u)).addEquals(u):t[t.length-1]):h===t.length-1?(l=t[h-1],c=i?o(x.util.createVector(l,u)).addEquals(u):t[0]):(l=t[h-1],c=t[h+1]);var d,f,g=x.util.getBisector(u,l,c),_=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-s/Math.sin(p/2),f=new x.Point(_.x*d*n.x,_.y*d*n.y),Math.hypot(f.x,f.y)/s<=e.strokeMiterLimit))return r.push(u.add(f)),void r.push(u.subtract(f));d=-s*Math.SQRT2,f=new x.Point(_.x*d*n.x,_.y*d*n.y),r.push(u.add(f)),r.push(u.subtract(f))})),r},transformPoint:function(t,e,i){return i?new x.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new x.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>r?e-=r:e=0,i>r?i-=r:i=0);var s,n=!0,o=t.getImageData(e,i,2*r||1,2*r||1),a=o.data.length;for(s=3;s=s?n-s:2*Math.PI-(s-n)}function n(t,e,i){for(var n=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,i,n,o,a,h){var l=Math.PI,c=h*l/180,u=x.util.sin(c),d=x.util.cos(c),f=0,g=0,_=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,m=(i=Math.abs(i))*i,v=(n=Math.abs(n))*n,y=p*p,S=_*_,C=m*v-m*y-v*S,w=0;if(C<0){var b=Math.sqrt(1-C/(m*v));i*=b,n*=b}else w=(o===a?-1:1)*Math.sqrt(C/(m*y+v*S));var T=w*i*p/n,I=-w*n*_/i,E=d*T-u*I+.5*t,O=u*T+d*I+.5*e,R=s(1,0,(_-T)/i,(p-I)/n),A=s((_-T)/i,(p-I)/n,(-_-T)/i,(-p-I)/n);0===a&&A>0?A-=2*l:1===a&&A<0&&(A+=2*l);for(var D=Math.ceil(Math.abs(A/l*2)),M=[],F=A/D,L=8/3*Math.sin(F/4)*Math.sin(F/4)/Math.sin(F/2),P=R+F,k=0;kw)for(var T=1,I=_.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:s.x===t[i-2].x?0:-1,h=s.y>t[i-2].y?1:s.y===t[i-2].y?0:-1),r.push(["L",s.x+a*e,s.y+h*e]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(e,i,r,s,n,o,a,h){var l;if(x.cachesBoundsOfCurve&&(l=t.call(arguments),x.boundsOfCurveCache[l]))return x.boundsOfCurveCache[l];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,C=Math.abs,w=[],b=[[],[]];u=6*e-12*r+6*n,c=-3*e+9*r-9*n+3*a,d=3*r-3*e;for(var T=0;T<2;++T)if(T>0&&(u=6*i-12*s+6*o,c=-3*i+9*s-9*o+3*h,d=3*s-3*i),C(c)<1e-12){if(C(u)<1e-12)continue;0<(f=-d/u)&&f<1&&w.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(m=v(p)))/(2*c))&&g<1&&w.push(g),0<(_=(-u-m)/(2*c))&&_<1&&w.push(_));for(var I,E,O,R=w.length,A=R;R--;)I=(O=1-(f=w[R]))*O*O*e+3*O*O*f*r+3*O*f*f*n+f*f*f*a,b[0][R]=I,E=O*O*O*i+3*O*O*f*s+3*O*f*f*o+f*f*f*h,b[1][R]=E;b[0][A]=e,b[1][A]=i,b[0][A+1]=a,b[1][A+1]=h;var D=[{x:y.apply(null,b[0]),y:y.apply(null,b[1])},{x:S.apply(null,b[0]),y:S.apply(null,b[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=D),D},x.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(n),s=n,(r=o(l.x,l.y,i.x,i.y))+a>e?(n-=c,c/=2):(l=i,n+=c,a+=r);return i.angle=u(s),i}(n,e)}},x.util.transformPath=function(t,e,i){return i&&(e=x.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),r={},s=1;s=e}))}}}(),function(){function t(e,i,r){if(r)if(!x.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var s=0,n=i.length;s57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var r=t.charCodeAt(e+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var s=t.charCodeAt(e-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1}x.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,r=0,s=[];for(r=0;r-1?t.prototype[s]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var s=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return s}}(s):t.prototype[s]=e[s],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function s(){}function n(e){for(var i=null,r=this;r.constructor.superclass;){var s=r.constructor.superclass.prototype[e];if(r[e]!==s){i=s;break}r=r.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}x.util.createClass=function(){var i=null,o=t.call(arguments,0);function a(){this.initialize.apply(this,arguments)}"function"==typeof o[0]&&(i=o.shift()),a.superclass=i,a.subclasses=[],i&&(s.prototype=i.prototype,a.prototype=new s,i.subclasses.push(a));for(var h=0,l=o.length;h-1||"touch"===t.pointerType},d="string"==typeof(u=x.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,_=function(t){return t},d?_=function(t,e){return t.style.opacity=e,t}:f&&(_=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),x.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?_(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?_(t,e[r]):i["float"===r||"cssFloat"===r?void 0===i.styleFloat?"cssFloat":"styleFloat":r]=e[r];return t},function(){var t,e,i,r,s=Array.prototype.slice,n=function(t){return s.call(t,0)};try{t=n(x.document.childNodes)instanceof Array}catch(t){}function o(t,e){var i=x.document.createElement(t);for(var r in e)"class"===r?i.className=e[r]:"for"===r?i.htmlFor=e[r]:i.setAttribute(r,e[r]);return i}function a(t){for(var e=0,i=0,r=x.document.documentElement,s=x.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===x.document?(e=s.scrollLeft||r.scrollLeft||0,i=s.scrollTop||r.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(n=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=x.document.defaultView&&x.document.defaultView.getComputedStyle?function(t,e){var i=x.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=x.document.documentElement.style,r="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",x.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=x.util.falseFunction),r?t.style[r]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},x.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),r?t.style[r]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},x.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},x.util.getById=function(t){return"string"==typeof t?x.document.getElementById(t):t},x.util.toArray=n,x.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},x.util.makeElement=o,x.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=o(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},x.util.getScrollLeftTop=a,x.util.getElementOffset=function(t){var i,r,s=t&&t.ownerDocument,n={left:0,top:0},o={left:0,top:0},h={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!s)return o;for(var l in h)o[h[l]]+=parseInt(e(t,l),10)||0;return i=s.documentElement,void 0!==t.getBoundingClientRect&&(n=t.getBoundingClientRect()),r=a(t),{left:n.left+r.left-(i.clientLeft||0)+o.left,top:n.top+r.top-(i.clientTop||0)+o.top}},x.util.getNodeCanvas=function(t){var e=x.jsdomImplForWrapper(t);return e._canvas||e._image},x.util.cleanUpJsdomNode=function(t){if(x.isLikelyNode){var e=x.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}x.util.request=function(e,i){i||(i={});var r=i.method?i.method.toUpperCase():"GET",s=i.onComplete||function(){},n=new x.window.XMLHttpRequest,o=i.body||i.parameters;return n.onreadystatechange=function(){4===n.readyState&&(s(n),n.onreadystatechange=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),n.open(r,e,!0),"POST"!==r&&"PUT"!==r||n.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),n.send(o),n}}(),x.log=console.log,x.warn=console.warn,function(){var t=x.util.object.extend,e=x.util.object.clone,i=[];function r(){return!1}function s(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e}x.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var n=x.window.requestAnimationFrame||x.window.webkitRequestAnimationFrame||x.window.mozRequestAnimationFrame||x.window.oRequestAnimationFrame||x.window.msRequestAnimationFrame||function(t){return x.window.setTimeout(t,1e3/60)},o=x.window.cancelAnimationFrame||x.window.clearTimeout;function a(){return n.apply(x.window,arguments)}x.util.animate=function(i){i||(i={});var n,o=!1,h=function(){var t=x.runningAnimations.indexOf(n);return t>-1&&x.runningAnimations.splice(t,1)[0]};return n=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(n),a((function(t){var e,l=t||+new Date,c=i.duration||500,u=l+c,d=i.onChange||r,f=i.abort||r,g=i.onComplete||r,_=i.easing||s,p="startValue"in i&&i.startValue.length>0,m="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?m.map((function(t,e){return v[e]-m[e]})):v-m);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,s=r/c,S=p?m.map((function(t,e){return _(r,m[e],y[e],c)})):_(r,m,y,c),C=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(n.currentValue=p?S.slice():S,n.completionRate=C,n.durationRate=s,!o){if(!f(S,C,s))return e>u?(n.currentValue=p?v.slice():v,n.completionRate=1,n.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void h()):(d(S,C,s),void a(t));h()}}(l)})),n.cancel},x.util.requestAnimFrame=a,x.util.cancelAnimFrame=function(){return o.apply(x.window,arguments)},x.runningAnimations=i}(),function(){function t(t,e,i){var r="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(r+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}x.util.animateColor=function(e,i,r,s){var n=new x.Color(e).getSource(),o=new x.Color(i).getSource(),a=s.onComplete,h=s.onChange;return s=s||{},x.util.animate(x.util.object.extend(s,{duration:r||500,startValue:n,endValue:o,byValue:o,easing:function(e,i,r,n){return t(i,r,s.colorEasing?s.colorEasing(e,n):1-Math.cos(e/n*(Math.PI/2)))},onComplete:function(e,i,r){if(a)return a(t(o,o,0),i,r)},onChange:function(e,i,r){if(h){if(Array.isArray(e))return h(t(e,e,0),i,r);h(e,i,r)}}}))}}(),function(){function t(t,e,i,r){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;a=h?i.map(n):n(i,s)}}else i="";return!h&&isNaN(a)?i:a}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,r,s,n,o=[];for(s=0,n=e.length;s1;)h.shift(),l=e.util.multiplyTransformMatrices(l,h[0]);return l}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,r,s,o,a,h,l=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,_=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",m=!l||!(l=l.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,C={},w="",b=0,x=0;if(C.width=0,C.height=0,C.toBeParsed=S,m&&(g||_)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(w=" translate("+n(g)+" "+n(_)+") ",a=(t.getAttribute("transform")||"")+w,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),S)return C;if(m)return C.width=n(d),C.height=n(f),C;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),s=parseFloat(l[3]),o=parseFloat(l[4]),C.minX=i,C.minY=r,C.viewBoxWidth=s,C.viewBoxHeight=o,y?(C.width=s,C.height=o):(C.width=n(d),C.height=n(f),c=C.width/s,u=C.height/o),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),b=C.width-s*c,x=C.height-o*c,"Mid"===p.alignX&&(b/=2),"Mid"===p.alignY&&(x/=2),"Min"===p.alignX&&(b=0),"Min"===p.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===_)return C;if((g||_)&&"#document"!==t.parentNode.nodeName&&(w=" translate("+n(g)+" "+n(_)+") "),a=w+" matrix("+c+" 0 0 "+u+" "+(i*c+b)+" "+(r*u+x)+") ","svg"===t.nodeName){for(h=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)h.appendChild(t.firstChild);t.appendChild(h)}else(h=t).removeAttribute("x"),h.removeAttribute("y"),a=h.getAttribute("transform")+a;return h.setAttribute("transform",a),C}function S(t,e){var i="xlink:href",r=m(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&S(t,r),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){r&&!e.hasAttribute(t)&&r.hasAttribute(t)&&e.setAttribute(t,r.getAttribute(t))})),!e.children.length)for(var s=r.cloneNode(!0);s.firstChild;)e.appendChild(s.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,s,n){if(t){!function(t){for(var i=g(t,["use","svg:use"]),r=0;i.length&&rt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,r,s,n){var o,a=(n.x-s.x)*(t.y-s.y)-(n.y-s.y)*(t.x-s.x),h=(r.x-t.x)*(t.y-s.y)-(r.y-t.y)*(t.x-s.x),l=(n.y-s.y)*(r.x-t.x)-(n.x-s.x)*(r.y-t.y);if(0!==l){var c=a/l,u=h/l;0<=c&&c<=1&&0<=u&&u<=1?(o=new i("Intersection")).appendPoint(new e.Point(t.x+c*(r.x-t.x),t.y+c*(r.y-t.y))):o=new i}else o=new i(0===a||0===h?"Coincident":"Parallel");return o},e.Intersection.intersectLinePolygon=function(t,e,r){var s,n,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,s=new i,n=t.length;for(r=0;r0&&(s.status="Intersection"),s},e.Intersection.intersectPolygonRectangle=function(t,r,s){var n=r.min(s),o=r.max(s),a=new e.Point(o.x,n.y),h=new e.Point(n.x,o.y),l=i.intersectLinePolygon(n,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,n,t),f=new i;return f.appendPoints(l.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function r(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,r){t/=255,i/=255,r/=255;var s,n,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,i,r]);if(o=(a+h)/2,a===h)s=n=0;else{var l=a-h;switch(n=o>.5?l/(2-a-h):l/(a+h),a){case t:s=(i-r)/l+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var r=i.transform.target,s=r.canvas,n=e.util.object.clone(i);n.target=r,s&&s.fire("object:"+t,n),r.fire(t,i)}function _(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function p(t){return t.originX===l&&t.originY===l}function m(t,e,i){var r=t.lockScalingX,s=t.lockScalingY;return!((!r||!s)&&(e||!r&&!s||!i)&&(!r||"x"!==e)&&(!s||"y"!==e))}function v(t,e,i,r){return{e:t,transform:e,pointer:{x:i,y:r}}}function y(t){return function(e,i,r,s){var n=i.target,o=n.getCenterPoint(),a=n.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,s);return n.setPositionByOrigin(a,i.originX,i.originY),h}}function S(t,e){return function(i,r,s,n){var o=e(i,r,s,n);return o&&g(t,v(i,r,s,n)),o}}function C(t,i,r,s,n){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.Point(s,n),i,r);return c.x>=l&&(c.x-=l),c.x<=-l&&(c.x+=l),c.y>=l&&(c.y-=l),c.y<=l&&(c.y+=l),c.x-=a.offsetX,c.y-=a.offsetY,c}function w(t){return t.flipX!==t.flipY}function b(t,e,i,r,s){if(0!==t[e]){var n=s/t._getTransformedDimensions()[r]*t[i];t.set(i,n)}}function x(t,e,i,r){var s,l=e.target,c=l._getTransformedDimensions(0,l.skewY),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.x)-c.x,g=l.skewX;f<2?s=0:(s=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===n&&e.originY===h&&(s=-s),e.originX===a&&e.originY===o&&(s=-s),w(l)&&(s=-s));var _=g!==s;if(_){var p=l._getTransformedDimensions().y;l.set("skewX",s),b(l,"skewY","scaleY","y",p)}return _}function T(t,e,i,r){var s,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=C(e,e.originX,e.originY,i,r),f=Math.abs(2*d.y)-c.y,g=l.skewY;f<2?s=0:(s=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===n&&e.originY===h&&(s=-s),e.originX===a&&e.originY===o&&(s=-s),w(l)&&(s=-s));var _=g!==s;if(_){var p=l._getTransformedDimensions().x;l.set("skewY",s),b(l,"skewX","scaleX","x",p)}return _}function I(t,e,i,r,s){s=s||{};var n,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=s.by,S=_(t,f),w=m(f,y,S),b=e.gestureScale;if(w)return!1;if(b)o=e.scaleX*b,a=e.scaleY*b;else{if(n=C(e,e.originX,e.originY,i,r),l="y"!==y?d(n.x):1,u="x"!==y?d(n.y):1,e.signX||(e.signX=l),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==l||e.signY!==u))return!1;if(h=f._getTransformedDimensions(),S&&!y){var x=Math.abs(n.x)+Math.abs(n.y),T=e.original,I=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(n.x*f.scaleX/h.x),a=Math.abs(n.y*f.scaleY/h.y);p(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var E=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!v&&f.set("scaleY",a)),E!==f.scaleX||O!==f.scaleY}s.scaleCursorStyleHandler=function(t,e,r){var s=_(t,r),n="";if(0!==e.x&&0===e.y?n="x":0===e.x&&0!==e.y&&(n="y"),m(r,n,s))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},s.skewCursorStyleHandler=function(t,e,i){var s="not-allowed";if(0!==e.x&&i.lockSkewingY)return s;if(0!==e.y&&i.lockSkewingX)return s;var n=f(i,e)%4;return r[n]+"-resize"},s.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?s.skewCursorStyleHandler(t,e,i):s.scaleCursorStyleHandler(t,e,i)},s.rotationWithSnapping=S("rotating",y((function(t,e,i,r){var s=e,n=s.target,o=n.translateToOriginPoint(n.getCenterPoint(),s.originX,s.originY);if(n.lockRotation)return!1;var a,h=Math.atan2(s.ey-o.y,s.ex-o.x),l=Math.atan2(r-o.y,i-o.x),c=u(l-h+s.theta);if(n.snapAngle>0){var d=n.snapAngle,f=n.snapThreshold||d,g=Math.ceil(c/d)*d,_=Math.floor(c/d)*d;Math.abs(c-_)0?n:a:(c>0&&(s=u===o?n:a),c<0&&(s=u===o?a:n),w(h)&&(s=s===n?a:n)),e.originX=s,S("skewing",y(x))(t,e,i,r))},s.skewHandlerY=function(t,e,i,r){var s,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?s=C(e,l,l,i,r).y>0?o:h:(c>0&&(s=u===n?o:h),c<0&&(s=u===n?h:o),w(a)&&(s=s===o?h:o)),e.originY=s,S("skewing",y(T))(t,e,i,r))},s.dragHandler=function(t,e,i,r){var s=e.target,n=i-e.offsetX,o=r-e.offsetY,a=!s.get("lockMovementX")&&s.left!==n,h=!s.get("lockMovementY")&&s.top!==o;return a&&s.set("left",n),h&&s.set("top",o),(a||h)&&g("moving",v(t,e,i,r)),a||h},s.scaleOrSkewActionName=function(t,e,i){var r=t[i.canvas.altActionKey];return 0===e.x?r?"skewX":"scaleY":0===e.y?r?"skewY":"scaleX":void 0},s.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},s.fireEvent=g,s.wrapWithFixedAnchor=y,s.wrapWithFireEvent=S,s.getLocalPoint=C,e.controlsUtils=s}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,i,r,s){r=r||{};var n,o=this.sizeX||r.cornerSize||s.cornerSize,a=this.sizeY||r.cornerSize||s.cornerSize,h=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,l=h?"stroke":"fill",c=!h&&(r.cornerStrokeColor||s.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,o>a?(n=o,t.scale(1,a/o),d=i*o/a):a>o?(n=a,t.scale(o/a,1),u=e*a/o):n=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,n/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,r,s,n){s=s||{};var o=this.sizeX||s.cornerSize||n.cornerSize,a=this.sizeY||s.cornerSize||n.cornerSize,h=void 0!==s.transparentCorners?s.transparentCorners:n.transparentCorners,l=h?"stroke":"fill",c=!h&&(s.cornerStrokeColor||n.cornerStrokeColor),u=o/2,d=a/2;t.save(),t.fillStyle=s.cornerColor||n.cornerColor,t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(n.angle)),t[l+"Rect"](-u,-d,o,a),c&&t.strokeRect(-u,-d,o,a),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,r,s,n){var o,a,h,l,c=n?this.touchSizeX:this.sizeX,u=n?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),_=Math.PI/2-d-e.util.degreesToRadians(t);o=f*e.util.cos(g),a=f*e.util.sin(g),h=f*e.util.cos(_),l=f*e.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),o=h=f*e.util.cos(g),a=l=f*e.util.sin(g);return{tl:{x:r-l,y:s-h},tr:{x:r+o,y:s-a},bl:{x:r-o,y:s+a},br:{x:r+l,y:s+h}}},render:function(t,i,r,s,n){"circle"===((s=s||{}).cornerStyle||n.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,s,n):e.controlsUtils.renderSquareControl.call(this,t,i,r,s,n)}}}(e),function(){function t(t,e){var i,r,s,n,o=t.getAttribute("style"),a=t.getAttribute("offset")||0;if(a=(a=parseFloat(a)/(/%$/.test(a)?100:1))<0?0:a>1?1:a,o){var h=o.split(/\s*;\s*/);for(""===h[h.length-1]&&h.pop(),n=h.length;n--;){var l=h[n].split(/\s*:\s*/),c=l[0].trim(),u=l[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(s=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),s||(s=t.getAttribute("stop-opacity")),r=(i=new x.Color(i)).getAlpha(),s=isNaN(parseFloat(s))?1:parseFloat(s),s*=r*e,{offset:a,color:i.toRgb(),opacity:s}}var e=x.util.object.clone;x.Gradient=x.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+x.Object.__uid++:this.id=x.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new x.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return x.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var r,s,n,o,a=e(this.coords,!0),h=(i=i||{},e(this.colorStops,!0)),l=a.r1>a.r2,c=this.gradientTransform?this.gradientTransform.concat():x.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(h.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,o='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',o+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+x.util.matrixToSVG(c)+'" ',"linear"===this.type?n=["\n']:"radial"===this.type&&(n=["\n']),"radial"===this.type){if(l)for((h=h.concat()).reverse(),r=0,s=h.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,s=h.length;r\n')}return n.push("linear"===this.type?"\n":"\n"),n.join("")},toLive:function(t){var e,i,r,s=x.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(s.x1,s.y1,s.x2,s.y2):"radial"===this.type&&(e=t.createRadialGradient(s.x1,s.y1,s.r1,s.x2,s.y2,s.r2)),i=0,r=this.colorStops.length;i1?1:n,isNaN(n)&&(n=1);var o,a,h,l,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,_=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(o="linear",a=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(o="radial",a=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),h=c.length;h--;)f.push(t(c[h],n));return l=x.parseTransformAttribute(d),function(t,e,i,r){var s,n;Object.keys(e).forEach((function(t){"Infinity"===(s=e[t])?n=1:"-Infinity"===s?n=0:(n=parseFloat(e[t],10),"string"==typeof s&&/^(\d+\.\d+)%|(\d+)%$/.test(s)&&(n*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(n*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(n*=i.viewBoxHeight||i.height)))),e[t]=n}))}(0,a,s,u),"pixels"===u&&(g=-i.left,_=-i.top),new x.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:_})}})}(),m=x.util.toFixed,x.Pattern=x.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=x.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=x.util.createImage(),x.util.loadImage(t.source,(function(t,r){i.source=t,e&&e(i,r)}),null,this.crossOrigin)}},toObject:function(t){var e,i,r=x.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:m(this.offsetX,r),offsetY:m(this.offsetY,r),patternTransform:this.patternTransform?this.patternTransform.concat():null},x.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,r=e.height/t.height,s=this.offsetX/t.width,n=this.offsetY/t.height,o="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(r=1,n&&(r+=Math.abs(n))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,s&&(i+=Math.abs(s))),e.src?o=e.src:e.toDataURL&&(o=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),r=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(r[1],10)||0,offsetY:parseFloat(r[2],10)||0,blur:parseFloat(r[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var r=40,s=40,n=e.Object.NUM_FRACTION_DIGITS,o=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),a=new e.Color(this.color);return t.width&&t.height&&(r=100*i((Math.abs(o.x)+this.blur)/t.width,n)+20,s=100*i((Math.abs(o.y)+this.blur)/t.height,n)+20),t.flipX&&(o.x*=-1),t.flipY&&(o.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(x.StaticCanvas)x.warn("fabric.StaticCanvas is already defined.");else{var t=x.util.object.extend,e=x.util.getElementOffset,i=x.util.removeFromArray,r=x.util.toFixed,s=x.util.transformPoint,n=x.util.invertTransform,o=x.util.getNodeCanvas,a=x.util.createCanvasElement,h=new Error("Could not initialize `canvas` element");x.StaticCanvas=x.util.createClass(x.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:x.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return x.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,x.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=x.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,r){return"string"==typeof e?x.util.loadImage(e,(function(e,s){if(e){var n=new x.Image(e,r);this[t]=n,n.canvas=this}i&&i(e,s)}),this,r&&r.crossOrigin):(r&&e.setOptions(r),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=a();if(!t)throw h;if(t.style||(t.style={}),void 0===t.getContext)throw h;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=x.util.getById(t)||this._createCanvasElement(),x.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var r in e=e||{},t)i=t[r],e.cssOnly||(this._setBackstoreDimension(r,t[r]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(r,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,r,s=this._activeObject,n=this.backgroundImage,o=this.overlayImage;for(this.viewportTransform=t,i=0,r=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,s=e.width||this.width,n=e.height||this.height,o='viewBox="0 0 '+this.width+" "+this.height+'" ',a=x.Object.NUM_FRACTION_DIGITS;e.viewBox?o='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,o='viewBox="'+r(-i[4]/i[0],a)+" "+r(-i[5]/i[3],a)+" "+r(this.width/i[0],a)+" "+r(this.height/i[3],a)+'" '),t.push("\n',"Created with Fabric.js ",x.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+x.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var r=t[e+"Vpt"],s=t.viewportTransform,n={width:t.width/(r?s[0]:1),height:t.height/(r?s[3]:1)};return i.toSVG(n,{additionalTransform:r?x.util.matrixToSVG(s):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,s,n,o,a,h="",l={},c=x.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),o=0,a=u.length;o',"\n",h,"","\n"].join("")),h},_setSVGObjects:function(t,e){var i,r,s,n=this._objects;for(r=0,s=n.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,s,n=this._activeObject;if(t===n&&"activeSelection"===t.type)for(e=(s=n._objects).length;e--;)r=s[e],i(this._objects,r),this._objects.unshift(r);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,r,s,n=this._activeObject;if(t===n&&"activeSelection"===t.type)for(s=n._objects,e=0;e0+l&&(o=n-1,i(this._objects,s),this._objects.splice(o,0,s)),l++;else 0!==(n=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,n,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,s;if(i){for(r=e,s=e-1;s>=0;--s)if(t.intersectsWithObject(this._objects[s])||t.isContainedWithinObject(this._objects[s])||this._objects[s].isContainedWithinObject(t)){r=s;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,s,n,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)s=a[r],(n=this._objects.indexOf(s))"}}),t(x.StaticCanvas.prototype,x.Observable),t(x.StaticCanvas.prototype,x.Collection),t(x.StaticCanvas.prototype,x.DataURLExporter),t(x.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=a();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),x.StaticCanvas.prototype.toJSON=x.StaticCanvas.prototype.toObject,x.isLikelyNode&&(x.StaticCanvas.prototype.createPNGStream=function(){var t=o(this.lowerCanvasEl);return t&&t.createPNGStream()},x.StaticCanvas.prototype.createJPEGStream=function(t){var e=o(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),x.BaseBrush=x.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,r=t.getZoom();t&&t._isRetinaScaling()&&(r*=x.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*r,i.shadowOffsetX=e.offsetX*r,i.shadowOffsetY=e.offsetY*r}},needsFullRender:function(){return new x.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),x.PencilBrush=x.util.createClass(x.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var r=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,r=i.length,s=this.canvas.contextTop;this._saveAndTransform(s),this.oldEnd&&(s.beginPath(),s.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(s,i[r-2],i[r-1],!0),s.stroke(),s.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new x.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new x.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,r=this._points[0],s=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&r.x===s.x&&r.y===s.y){var n=this.width/1e3;r=new x.Point(r.x,r.y),s=new x.Point(s.x,s.y),r.x-=n,s.x+=n}for(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=s&&(o=t[i],a.push(o));return a.push(t[n]),a},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),x.CircleBrush=x.util.createClass(x.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,r=this.points;for(this._saveAndTransform(i),t=0,e=r.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var s=0,n=this._objects.length;s1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),r=x.util.invertTransform(i),s=this.restorePointerVpt(e);return x.util.transformPoint(s,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),s=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),n=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return x.util.isTransparent(t._cacheContext,Math.round(s),Math.round(n),this.targetFindTolerance)}var o=this.contextCache,a=t.selectionBackgroundColor,h=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(h[0],h[1],h[2],h[3],h[4],h[5]),t.render(o),o.restore(),t.selectionBackgroundColor=a,x.util.isTransparent(o,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),r=this._activeObject;return!e||e&&r&&i.length>1&&-1===i.indexOf(e)&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e},_shouldCenterTransform:function(t,e,i){var r;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?r=this.centeredScaling||t.centeredScaling:"rotate"===e&&(r=this.centeredRotation||t.centeredRotation),r?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,r){if(!e||!t)return"drag";var s=r.controls[e];return s.getActionName(i,s,r)},_setupCurrentTransform:function(t,i,r){if(i){var s=this.getPointer(t),n=i.__corner,o=i.controls[n],a=r&&n?o.getActionHandler(t,i,o):x.controlsUtils.dragHandler,h=this._getActionFromCorner(r,n,t,i),l=this._getOriginFromCorner(i,n),c=t[this.centeredKey],u={target:i,action:h,actionHandler:a,corner:n,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:s.x-i.left,offsetY:s.y-i.top,originX:l.x,originY:l.y,ex:s.x,ey:s.y,lastX:s.x,lastY:s.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:x.util.saveObjectTransform(i)};this._shouldCenterTransform(i,h,c)&&(u.originX="center",u.originY="center"),u.original.originX=l.x,u.original.originY=l.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new x.Point(e.ex,e.ey),r=x.util.transformPoint(i,this.viewportTransform),s=new x.Point(e.ex+e.left,e.ey+e.top),n=x.util.transformPoint(s,this.viewportTransform),o=Math.min(r.x,n.x),a=Math.min(r.y,n.y),h=Math.max(r.x,n.x),l=Math.max(r.y,n.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(o,a,h-o,l-a)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,o+=c,a+=c,h-=c,l-=c,x.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(o,a,h-o,l-a))},findTarget:function(t,e){if(!this.skipTargetFind){var r,s,n=this.getPointer(t,!0),o=this._activeObject,a=this.getActiveObjects(),h=i(t),l=a.length>1&&!e||1===a.length;if(this.targets=[],l&&o._findTargetCorner(n,h))return o;if(a.length>1&&!e&&o===this._searchPossibleTargets([o],n))return o;if(1===a.length&&o===this._searchPossibleTargets([o],n)){if(!this.preserveObjectStacking)return o;r=o,s=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,n);return t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=s),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,r,s=t.length;s--;){var n=t[s],o=n.group?this._normalizePointer(n.group,e):e;if(this._checkTarget(o,n,e)){(i=t[s]).subTargetCheck&&i instanceof x.Group&&(r=this._searchPossibleTargets(i._objects,e))&&this.targets.push(r);break}}return i},restorePointerVpt:function(t){return x.util.transformPoint(t,x.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var r,s=t(e),n=this.upperCanvasEl,o=n.getBoundingClientRect(),a=o.width||0,h=o.height||0;a&&h||("top"in o&&"bottom"in o&&(h=Math.abs(o.top-o.bottom)),"right"in o&&"left"in o&&(a=Math.abs(o.right-o.left))),this.calcOffset(),s.x=s.x-this._offset.left,s.y=s.y-this._offset.top,i||(s=this.restorePointerVpt(s));var l=this.getRetinaScaling();return 1!==l&&(s.x/=l,s.y/=l),r=0===a||0===h?{width:1,height:1}:{width:n.width/a,height:n.height/h},{x:s.x*r.width,y:s.y*r.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),x.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=x.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),x.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),x.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;x.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,x.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,r=this.getActiveObjects(),s=[],n=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),n.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e,target:r}),s.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e,selected:s,deselected:n}):r.length>0?this.fire("selection:created",{e,selected:s}):t.length>0&&this.fire("selection:cleared",{e,deselected:n})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){x.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,x.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(t),s=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),s},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),x.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var r=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,r)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),x.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),x.StaticCanvas)"prototype"!==r&&(x.Canvas[r]=x.StaticCanvas[r])}(),function(){var t=x.util.addListener,e=x.util.removeListener,i={passive:!1};function r(t,e){return t.button&&t.button===e-1}x.util.object.extend(x.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var r=this.upperCanvasEl,s=this._getEventPrefix();t(x.window,"resize",this._onResize),t(r,s+"down",this._onMouseDown),t(r,s+"move",this._onMouseMove,i),t(r,s+"out",this._onMouseOut),t(r,s+"enter",this._onMouseEnter),t(r,"wheel",this._onMouseWheel),t(r,"contextmenu",this._onContextMenu),t(r,"dblclick",this._onDoubleClick),t(r,"dragover",this._onDragOver),t(r,"dragenter",this._onDragEnter),t(r,"dragleave",this._onDragLeave),t(r,"drop",this._onDrop),this.enablePointerEvents||t(r,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](r,"gesture",this._onGesture),eventjs[e](r,"drag",this._onDrag),eventjs[e](r,"orientation",this._onOrientationChange),eventjs[e](r,"shake",this._onShake),eventjs[e](r,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(x.document,t+"up",this._onMouseUp),e(x.document,"touchend",this._onTouchEnd,i),e(x.document,t+"move",this._onMouseMove,i),e(x.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(r){i.fire("mouse:out",{target:e,e:t}),r&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(r){r.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(r)),this.__onMouseDown(r),this._resetTransformEventData();var s=this.upperCanvasEl,n=this._getEventPrefix();t(x.document,"touchend",this._onTouchEnd,i),t(x.document,"touchmove",this._onMouseMove,i),e(s,n+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var s=this.upperCanvasEl,n=this._getEventPrefix();e(s,n+"move",this._onMouseMove,i),t(x.document,n+"up",this._onMouseUp),t(x.document,n+"move",this._onMouseMove,i)},_onTouchEnd:function(r){if(!(r.touches.length>0)){this.__onMouseUp(r),this._resetTransformEventData(),this.mainTouchId=null;var s=this._getEventPrefix();e(x.document,"touchend",this._onTouchEnd,i),e(x.document,"touchmove",this._onMouseMove,i);var n=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(n.upperCanvasEl,s+"down",n._onMouseDown),n._willAddMouseDown=0}),400)}},_onMouseUp:function(r){this.__onMouseUp(r),this._resetTransformEventData();var s=this.upperCanvasEl,n=this._getEventPrefix();this._isMainEvent(r)&&(e(x.document,n+"up",this._onMouseUp),e(x.document,n+"move",this._onMouseMove,i),t(s,n+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,s=this._groupSelector,n=!1,o=!s||0===s.left&&0===s.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),r(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,o);else{if(r(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,o),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),n=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),n||(n=this._shouldRender(e)||!a&&e===this._activeObject)}var h,l;if(e){if(h=e._findTargetCorner(this.getPointer(t,!0),x.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),n=!0;else{var c=e.controls[h],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(l=this.getPointer(t)).x,l.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==h)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);l=l||this.getPointer(t),f&&f(t,i,l.x,l.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,o),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),n?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,s={e,target:i,subTargets:r};if(this.fire(t,s),i&&i.fire(t,s),!r)return i;for(var n=0;n1&&(e=new x.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],r=this._groupSelector.ex,s=this._groupSelector.ey,n=r+this._groupSelector.left,o=s+this._groupSelector.top,a=new x.Point(v(r,n),v(s,o)),h=new x.Point(y(r,n),y(s,o)),l=!this.selectionFullyContained,c=r===n&&s===o,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(l&&e.intersectsWithRect(a,h,!0)||e.isContainedWithinRect(a,h,!0)||l&&e.containsPoint(a,null,!0)||l&&e.containsPoint(h,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),x.util.object.extend(x.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,r=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),s=this.toCanvasElement(r,t);return x.util.toDataURL(s,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,s=this.getZoom(),n=this.width,o=this.height,a=s*t,h=this.viewportTransform,l=(h[4]-(e.left||0))*t,c=(h[5]-(e.top||0))*t,u=this.interactive,d=[a,0,0,a,l,c],f=this.enableRetinaScaling,g=x.util.createCanvasElement(),_=this.contextTop;return g.width=i,g.height=r,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=r,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=h,this.width=n,this.height=o,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=_,g}}),x.util.object.extend(x.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var r="string"==typeof t?JSON.parse(t):x.util.object.clone(t),s=this,n=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){s.clear(),s._setBgOverlay(r,(function(){n?s._enlivenObjects([n],(function(i){s.clipPath=i[0],s.__setupCanvas.call(s,r,t,o,e)})):s.__setupCanvas.call(s,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var s=this;e.forEach((function(t,e){s.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),r&&r()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var r=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,r),this.__setBgOverlay("overlayImage",t.overlayImage,i,r),this.__setBgOverlay("backgroundColor",t.background,i,r),this.__setBgOverlay("overlayColor",t.overlay,i,r)}else e&&e()},__setBgOverlay:function(t,e,i,r){var s=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?x.util.enlivenObjects([e],(function(e){s[t]=e[0],i[t]=!0,r&&r()})):this["set"+x.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,r&&r()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?x.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(r){i(r.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=x.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new x.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,s=e.util.toFixed,n=e.util.string.capitalize,o=e.util.degreesToRadians,a=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:a,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,r=t.width,s=t.height,n=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=n&&s<=n&&r*s<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),s>u&&(t.zoomY/=s/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,r=e.y*t.scaleY/this.scaleY;return{width:i+2,height:r+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:r}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,r=t._currentTransform.action;if(this===i&&r.slice&&"scale"===r.slice(0,5))return!1}var s,n,o=this._cacheCanvas,a=this._limitCacheSize(this._getCacheCanvasDimensions()),h=e.minCacheSideLimit,l=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=l!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,_=f||g,p=0,m=0,v=!1;if(f){var y=this._cacheCanvas.width,S=this._cacheCanvas.height,C=l>y||c>S;v=C||(l<.9*y||c<.9*S)&&y>h&&S>h,C&&!a.capped&&(l>h||c>h)&&(p=.1*l,m=.1*c)}return this instanceof e.Text&&this.path&&(_=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,m+=this.getHeightOfLine(0)*this.zoomY),!!_&&(v?(o.width=Math.ceil(l+p),o.height=Math.ceil(c+m)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,o.width,o.height)),s=a.x/2,n=a.y/2,this.cacheTranslationX=Math.round(o.width/2-s)+s,this.cacheTranslationY=Math.round(o.height/2-n)+n,this.cacheWidth=l,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,r={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:s(this.left,i),top:s(this.top,i),width:s(this.width,i),height:s(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:s(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:s(this.strokeMiterLimit,i),scaleX:s(this.scaleX,i),scaleY:s(this.scaleY,i),angle:s(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:s(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:s(this.skewX,i),skewY:s(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(r.clipPath=this.clipPath.toObject(t),r.clipPath.inverted=this.clipPath.inverted,r.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,r,t),this.includeDefaultValues||(r=this._removeDefaultValues(r)),r},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var r=this.canvas.getZoom(),s=this.canvas.getRetinaScaling();e*=r*s,i*=r*s}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var r="scaleX"===t||"scaleY"===t,s=this[t]!==i,n=!1;return r&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,s&&(n=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,n&&this.group.set("dirty",!0)):n&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var r=e.util.invertTransform(this.calcTransformMatrix());t.transform(r[0],r[1],r[2],r[3],r[4],r[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=r},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var r,s,n,a=this.getViewportTransform(),h=this.calcTransformMatrix();s=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,n=void 0!==i.hasControls?i.hasControls:this.hasControls,h=e.util.multiplyTransformMatrices(a,h),r=e.util.qrDecompose(h),t.save(),t.translate(r.translateX,r.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(r.angle-=180),t.rotate(o(this.group?r.angle:this.angle)),i.forActiveSelection||this.group?s&&this.drawBordersInGroup(t,r,i):s&&this.drawBorders(t,i),n&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,r=this.shadow,s=this.canvas,n=s&&s.viewportTransform[0]||1,o=s&&s.viewportTransform[3]||1;i=r.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),s&&s._isRetinaScaling()&&(n*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(n+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*n*i.scaleX,t.shadowOffsetY=r.offsetY*o*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,s=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,s):t.transform(1,0,0,1,r,s),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:s}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var r,s=this._limitCacheSize(this._getCacheCanvasDimensions()),n=e.util.createCanvasElement(),o=this.canvas.getRetinaScaling(),a=s.x/this.scaleX/o,h=s.y/this.scaleY/o;n.width=a,n.height=h,(r=n.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,h),r.lineTo(0,h),r.closePath(),r.translate(a/2,h/2),r.scale(s.zoomX/this.scaleX/o,s.zoomY/this.scaleY/o),this._applyPatternGradientTransform(r,i),r.fillStyle=i.toLive(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/s.zoomX,o*this.scaleY/s.zoomY),t.strokeStyle=r.createPattern(n,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var r=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(r,t):e.Object._fromObject("Object",r,t)},cloneAsImage:function(t,i){var r=this.toCanvasElement(i);return t&&t(new e.Image(r)),this},toCanvasElement:function(t){t||(t={});var i=e.util,r=i.saveObjectTransform(this),s=this.group,n=this.shadow,o=Math.abs,a=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var h,l,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),_.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+_.x,u=f.height+_.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var m=this.canvas;p.add(this);var v=p.toCanvasElement(a||1,t);return this.shadow=n,this.set("canvas",m),s&&(this.group=s),this.set(r).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var r=new e.Point(i.x,i.y),s=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,s,o(-this.angle))),{x:r.x-s.x,y:r.y-s.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,s,n){var o=e[t];i=r(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=n?new o(i[n],i):new o(i);s&&s(t)}))}))},e.Object.__uid=0)}(e),S=x.util.degreesToRadians,C={left:-.5,center:0,right:.5},w={top:-.5,center:0,bottom:.5},x.util.object.extend(x.Object.prototype,{translateToGivenOrigin:function(t,e,i,r,s){var n,o,a,h=t.x,l=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof r?r=C[r]:r-=.5,"string"==typeof i?i=w[i]:i-=.5,"string"==typeof s?s=w[s]:s-=.5,o=s-i,((n=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+n*a.x,l=t.y+o*a.y),new x.Point(h,l)},translateToCenterPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?x.util.rotatePoint(r,t,S(this.angle)):r},translateToOriginPoint:function(t,e,i){var r=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?x.util.rotatePoint(r,t,S(this.angle)):r},getCenterPoint:function(){var t=new x.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var r,s,n=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(n,"center","center",e,i):new x.Point(this.left,this.top),s=new x.Point(t.x,t.y),this.angle&&(s=x.util.rotatePoint(s,n,-S(this.angle))),s.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),s=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",s.x),this.set("top",s.y)},adjustPosition:function(t){var e,i,r=S(this.angle),s=this.getScaledWidth(),n=x.util.cos(r)*s,o=x.util.sin(r)*s;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=n*(i-e),this.top+=o*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=x.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,r=t.transformPoint;t.object.extend(x.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new x.Point(i.tl.x,i.tl.y),new x.Point(i.tr.x,i.tr.y),new x.Point(i.br.x,i.br.y),new x.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,r){var s=this.getCoords(i,r);return"Intersection"===x.Intersection.intersectPolygonRectangle(s,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===x.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var r=this.getCoords(e,i),s=e?t.aCoords:t.lineCoords,n=0,o=t._getImageLines(s);n<4;n++)if(!t.containsPoint(r[n],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var s=this.getBoundingRect(i,r);return s.left>=t.x&&s.left+s.width<=e.x&&s.top>=t.y&&s.top+s.height<=e.y},containsPoint:function(t,e,i,r){var s=this._getCoords(i,r),n=(e=e||this._getImageLines(s),this._findCrossPoints(t,e));return 0!==n&&n%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var r={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(r,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,r,s,n=0;for(var o in e)if(!((s=e[o]).o.y=t.y&&s.d.y>=t.y||(s.o.x===s.d.x&&s.o.x>=t.x?r=s.o.x:(i=(s.d.y-s.o.y)/(s.d.x-s.o.x),r=-(t.y-0*t.x-(s.o.y-i*s.o.x))/(0-i)),r>=t.x&&(n+=1),2!==n)))break;return n},getBoundingRect:function(e,i){var r=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(r)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,r=e.additionalTransform||"",s=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=s,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,s=(e=e||{}).noStyle,n=e.reviver,o=s?"":'style="'+this.getSvgStyles()+'" ',a=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return h&&(h.clipPathId="CLIPPATH_"+x.Object.__uid++,r='\n'+h.toClipPathSVG(n)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,s?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[_]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),h&&g.push(r),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),n?n(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=x.util.object.extend,e="stateProperties";function i(e,i,r){var s={};r.forEach((function(t){s[t]=e[t]})),t(e[i],s,!0)}function r(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var s=0,n=t.length;s=0;h--)if(s=a[h],this.isControlVisible(s)&&(r=this._getImageLines(e?this.oCoords[s].touchCorner:this.oCoords[s].corner),0!==(i=this._findCrossPoints({x:n,y:o},r))&&i%2==1))return this.__corner=s,s;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),r=this._calculateCurrentDimensions(),s=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/s[0],1/s[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-r.x/2,-r.y/2,r.x,r.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),r=this.borderScaleFactor,s=i.x+r,n=i.y+r,o=void 0!==e.hasControls?e.hasControls:this.hasControls,a=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-s/2,-n/2,s,n),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*s,e.y*n),t.lineTo(e.x*s+e.offsetX,e.y*n+e.offsetY))})),a&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var r=x.util.sizeAfterTransform(this.width,this.height,e),s=this.strokeWidth,n=this.strokeUniform,o=this.borderScaleFactor,a=r.x+s*(n?this.canvas.getZoom():e.scaleX)+o,h=r.y+s*(n?this.canvas.getZoom():e.scaleY)+o;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-a/2,-h/2,a,h),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,r,s=this.canvas.getRetinaScaling();return t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(s,n,o){r=o.oCoords[n],s.getVisibility(o,n)&&(i&&(r=x.util.transformPoint(r,i)),s.render(t,r.x,r.y,e,o))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),x.util.object.extend(x.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,s=e.onChange||i,n=this;return x.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),n.requestRenderAll(),s()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,s=e.onChange||i,n=this;return x.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),n.requestRenderAll(),s()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,s=e.onChange||i,n=this;return x.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),n.requestRenderAll(),s()},onComplete:function(){n.remove(t),r()}})}}),x.util.object.extend(x.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],r=[];for(t in arguments[0])i.push(t);for(var s=0,n=i.length;s-1||s&&n.colorProperties.indexOf(s[1])>-1,a=s?this.get(s[0])[s[1]]:this.get(t);"from"in i||(i.from=a),o||(e=~e.indexOf("=")?a+parseFloat(e.replace("=","")):parseFloat(e));var h={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,r){return i.abort.call(n,t,e,r)},onChange:function(e,o,a){s?n[s[0]][s[1]]=e:n.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,s){r||(n.setCoords(),i.onComplete&&i.onComplete(t,e,s))}};return o?x.util.animateColor(h.startValue,h.endValue,h.duration,h):x.util.animate(h)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.object.clone,s={x1:1,x2:1,y1:1,y2:1};function n(t,e){var i=t.origin,r=t.axis1,s=t.axis2,n=t.dimension,o=e.nearest,a=e.center,h=e.farthest;return function(){switch(this.get(i)){case o:return Math.min(this.get(r),this.get(s));case a:return Math.min(this.get(r),this.get(s))+.5*this.get(n);case h:return Math.max(this.get(r),this.get(s))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==s[t]&&this._setWidthHeight(),this},_getLeftToOriginX:n({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:n({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,r=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:r,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,r,s){s=s||{};var n=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[n.x1||0,n.y1||0,n.x2||0,n.y2||0];r(new e.Line(o,i(n,s)))},e.Line.fromObject=function(t,i){var s=r(t,!0);s.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",s,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,r=(this.endAngle-this.startAngle)%360;if(0===r)t=["\n'];else{var s=i(this.startAngle),n=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(n)*o+" "+e.util.sin(n)*o,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var r,s=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(r=s)&&r.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");s.left=(s.left||0)-s.radius,s.top=(s.top||0)-s.radius,i(new e.Circle(s))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var r=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,i(new e.Ellipse(r))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,r=this.width,s=this.height,n=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(n+e,o),t.lineTo(n+r-e,o),a&&t.bezierCurveTo(n+r-h*e,o,n+r,o+h*i,n+r,o+i),t.lineTo(n+r,o+s-i),a&&t.bezierCurveTo(n+r,o+s-h*i,n+r-h*e,o+s,n+r-e,o+s),t.lineTo(n+e,o+s),a&&t.bezierCurveTo(n+h*e,o+s,n,o+s-h*i,n,o+s-i),t.lineTo(n,o+i),a&&t.bezierCurveTo(n,o+h*i,n+h*e,o,n+e,o),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,r,s){if(!t)return r(null);s=s||{};var n=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);n.left=n.left||0,n.top=n.top||0,n.height=n.height||0,n.width=n.width||0;var o=new e.Rect(i(s?e.util.object.clone(s):{},n));o.visible=o.visible&&o.width>0&&o.height>0,r(o)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,r=e.util.array.min,s=e.util.array.max,n=e.util.toFixed,o=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return o(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),r=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-r,this.height=i.height-r,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+r/2,y:i.top-this.strokeWidth/2+r/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+r/2,y:i.top+this.height/2+r/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=r(t,"x")||0,i=r(t,"y")||0;return{left:e,top:i,width:(s(t,"x")||0)-e,height:(s(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,r=this.pathOffset.y,s=e.Object.NUM_FRACTION_DIGITS,o=0,a=this.points.length;o\n']},commonRender:function(t){var e,i=this.points.length,r=this.pathOffset.x,s=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-r,this.points[0].y-s);for(var n=0;n"},toObject:function(t){return s(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+o(-this.pathOffset.x,t)+", "+o(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,s,n=[],o=[],a=0,h=0,l=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var r=this._objects.length;if(this.useSetOnGroup)for(;r--;)this._objects[r].setOnGroup(t,i);if("canvas"===t)for(;r--;)this._objects[r]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,r=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var r=e.includeDefaultValues;e.includeDefaultValues=i;var s=e.toObject(t);return e.includeDefaultValues=r,s})),s=e.Object.prototype.toObject.call(this,t);return s.objects=r,s},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var s=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=s;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var n=e.Object.prototype.toDatalessObject.call(this,t);return n.objects=i,n},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,r=this._objects.length;i\n"],i=0,r=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,r=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var r=0,s=this._objects.length;r\n','\t\n',"\n"),o=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var l=this.fill;this.fill=null,t=["\t\n'],this.fill=l}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return x.util.loadImage(t,(function(t,r){this.setElement(t,i),this._setWidthHeight(),e&&e(this,r)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),r=i.scaleX,s=i.scaleY,n=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&s>e)return this._element=n,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=s);x.filterBackend||(x.filterBackend=x.initFilterBackend());var o=x.util.createCanvasElement(),a=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,h=n.width,l=n.height;o.width=h,o.height=l,this._element=o,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=s,x.filterBackend.applyFilters([t],n,h,l,this._element,a),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){var s=x.util.createCanvasElement();s.width=i,s.height=r,this._element=s,this._filteredEl=s}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,r),this._lastScaleX=1,this._lastScaleY=1;return x.filterBackend||(x.filterBackend=x.initFilterBackend()),x.filterBackend.applyFilters(t,this._originalElement,i,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){x.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){x.util.setImageSmoothing(t,this.imageSmoothing),x.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,r=this._filterScalingY,s=this.width,n=this.height,o=Math.min,a=Math.max,h=a(this.cropX,0),l=a(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=h*i,f=l*r,g=o(s*i,c-d),_=o(n*r,u-f),p=-s/2,m=-n/2,v=o(s,c/i-h),y=o(n,u/r-l);e&&t.drawImage(e,d,f,g,_,p,m,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(x.util.getById(t),e),x.util.addClass(this.getElement(),x.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?x.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=x.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,r=this._element.height,s=1,n=1,o=0,a=0,h=0,l=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(s=c/i,n=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(s=n=x.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*n)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(s=n=x.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/n,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),i=c/s,r=u/n)),{width:i,height:r,scaleX:s,scaleY:n,offsetLeft:o,offsetTop:a,cropX:h,cropY:l}}}),x.Image.CSS_CANVAS="canvas-img",x.Image.prototype.getSvgSrc=x.Image.prototype.getSrc,x.Image.fromObject=function(t,e){var i=x.util.object.clone(t);x.util.loadImage(i.src,(function(t,r){r?e&&e(null,!0):x.Image.prototype._initFilters.call(i,i.filters,(function(r){i.filters=r||[],x.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(r){i.resizeFilter=r[0],x.util.enlivenObjectEnlivables(i,i,(function(){var r=new x.Image(t,i);e(r,!1)}))}))}))}),null,i.crossOrigin)},x.Image.fromURL=function(t,e,i){x.util.loadImage(t,(function(t,r){e&&e(new x.Image(t,i),r)}),null,i&&i.crossOrigin)},x.Image.ATTRIBUTE_NAMES=x.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),x.Image.fromElement=function(t,i,r){var s=x.parseAttributes(t,x.Image.ATTRIBUTE_NAMES);x.Image.fromURL(s["xlink:href"],i,e(r?x.util.object.clone(r):{},s))})}(e),x.util.object.extend(x.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,r=t.onChange||e,s=this;return x.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){s.rotate(t),r()},onComplete:function(){s.setCoords(),i()}})}}),x.util.object.extend(x.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",r=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(r,i),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}x.isWebglSupported=function(e){if(x.isLikelyNode)return!1;e=e||x.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),r=i.getContext("webgl")||i.getContext("experimental-webgl"),s=!1;if(r){x.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),s=x.maxTextureSize>=e;for(var n=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,n[o])){x.webGlPrecision=n[o];break}}return this.isSupported=s,s},x.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,r=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var s="undefined"!=typeof ArrayBuffer,n="undefined"!=typeof Uint8ClampedArray;if(r&&i&&s&&n){var o=x.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(x.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=E);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),I.call(c,this.gl,c),l=window.performance.now()-h,h=window.performance.now(),E.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=E):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=x.util.createCanvasElement();i.width=t,i.height=e;var r={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},s=i.getContext("webgl",r);s||(s=i.getContext("experimental-webgl",r)),s&&(s.clearColor(0,0,0,0),this.canvas=i,this.gl=s)},applyFilters:function(t,e,i,r,s,n){var o,a=this.gl;n&&(o=this.getCachedTexture(n,e));var h={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:r,destinationWidth:i,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,i,r,!o&&e),targetTexture:this.createTexture(a,i,r),originalTexture:o||this.createTexture(a,i,r,!o&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:s},l=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,l),t.forEach((function(t){t&&t.applyTo(h)})),function(t){var e=t.targetCanvas,i=e.width,r=e.height,s=t.destinationWidth,n=t.destinationHeight;i===s&&r===n||(e.width=s,e.height=n)}(h),this.copyGLTo2D(a,h),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(h.sourceTexture),a.deleteTexture(h.targetTexture),a.deleteFramebuffer(l),s.getContext("2d").setTransform(1,0,0,1,0,0),h},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,r){var s=t.createTexture();return t.bindTexture(t.TEXTURE_2D,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),r?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),s},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var r=t.getParameter(i.UNMASKED_RENDERER_WEBGL),s=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),s&&(e.vendor=s.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}x.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,r,s){var n=s.getContext("2d");n.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:n.getImageData(0,0,i,r),originalEl:e,originalImageData:n.getImageData(0,0,i,r),canvasEl:s,ctx:n,filterBackend:this};return t.forEach((function(t){t.applyTo(o)})),o.imageData.width===i&&o.imageData.height===r||(s.width=o.imageData.width,s.height=o.imageData.height),n.putImageData(o.imageData,0,0),o}}}(),x.Image=x.Image||{},x.Image.filters=x.Image.filters||{},x.Image.filters.BaseFilter=x.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==x.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+x.webGlPrecision+" float"));var r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(s,e),t.compileShader(s),!t.getShaderParameter(s,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(s));var n=t.createProgram();if(t.attachShader(n,r),t.attachShader(n,s),t.linkProgram(n),!t.getProgramParameter(n,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(n));var o=this.getAttributeLocations(t,n),a=this.getUniformLocations(t,n)||{};return a.uStepW=t.getUniformLocation(n,"uStepW"),a.uStepH=t.getUniformLocation(n,"uStepH"),{program:n,attributeLocations:o,uniformLocations:a}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var r=e.aPosition,s=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,s),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,r=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(r.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(r,e,i)),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t.targetTexture,0)):(r.bindFramebuffer(r.FRAMEBUFFER,null),r.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=x.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),x.Image.filters.BaseFilter.fromObject=function(t,e){var i=new x.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.ColorMatrix=r(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,r,s,n,o=t.imageData.data,a=o.length,h=this.matrix,l=this.colorsOnly;for(n=0;n=S||o<0||o>=y||(h=4*(a*y+o),l=p[f*m+d],e+=_[h]*l,i+=_[h+1]*l,r+=_[h+2]*l,b||(s+=_[h+3]*l));w[n]=e,w[n+1]=i,w[n+2]=r,w[n+3]=b?_[n+3]:s}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Grayscale=r(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,r=t.imageData.data,s=r.length,n=this.mode;for(e=0;el[0]&&s>l[1]&&n>l[2]&&r 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,r,s,n,o,a,h,l=t.imageData.data,c=l.length,u=1-this.alpha;i=(h=new e.Color(this.color).getSource())[0]*this.alpha,r=h[1]*this.alpha,s=h[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return a(e)/e*a(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,r=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/r;var s,n=e.width,a=e.height,h=o(n*i),l=o(a*r);"sliceHack"===this.resizeType?s=this.sliceByTwo(t,n,a,h,l):"hermite"===this.resizeType?s=this.hermiteFastResize(t,n,a,h,l):"bilinear"===this.resizeType?s=this.bilinearFiltering(t,n,a,h,l):"lanczos"===this.resizeType&&(s=this.lanczosResize(t,n,a,h,l)),t.imageData=s},sliceByTwo:function(t,i,s,n,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=s*c,_=e.filterBackend.resources,p=0,m=0,v=i,y=0;for(_.sliceByTwo||(_.sliceByTwo=document.createElement("canvas")),((a=_.sliceByTwo).width<1.5*i||a.height=e)){M=r(1e3*n(x-C.x)),S[M]||(S[M]={});for(var L=w.y-y;L<=w.y+y;L++)L<0||L>=o||(F=r(1e3*n(L-C.y)),S[M][F]||(S[M][F]=f(s(i(M*p,2)+i(F*m,2))/1e3)),(T=S[M][F])>0&&(E+=T,O+=T*c[I=4*(L*e+x)],R+=T*c[I+1],A+=T*c[I+2],D+=T*c[I+3]))}d[I=4*(b*a+h)]=O/E,d[I+1]=R/E,d[I+2]=A/E,d[I+3]=D/E}return++h1&&F<-1||(y=2*F*F*F-3*F*F+1)>0&&(T+=y*f[3+(M=4*(D+E*e))],C+=y,f[M+3]<255&&(y=y*f[M+3]/250),w+=y*f[M],b+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=w/S,_[v+1]=b/S,_[v+2]=x/S,_[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Contrast=r(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,r=i.length,s=Math.floor(255*this.contrast),n=259*(s+255)/(255*(259-s));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,r=e.util.createClass;i.Gamma=r(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,r=this.gamma,s=i.length,n=1/r[0],o=1/r[1],a=1/r[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,s=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=r)}return t},_renderTextLine:function(t,e,i,r,s,n){this._renderChars(t,e,i,r,s,n)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,s,n,o,a,h=t.fillStyle,l=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,_=this._textLines.length;g<_;g++)if(e=this.getHeightOfLine(g),this.textBackgroundColor||this.styleHas("textBackgroundColor",g)){r=this._textLines[g],i=this._getLineLeftOffset(g),d=0,u=0,s=this.getValueOfPropertyAt(g,0,"textBackgroundColor");for(var p=0,m=r.length;p=0:ia?u%=a:u<0&&(u+=a),this._setGraphemeOnPath(u,n,o),u+=n.kernedWidth}return{width:h,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,r){var s=t+i.kernedWidth/2,n=this.path,o=e.util.getPointOnPath(n.path,s,n.segmentsInfo);i.renderLeft=o.x-r.x,i.renderTop=o.y-r.y,i.angle=o.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,r,s){var n,o=this.getCompleteStyleDeclaration(e,i),a=r?this.getCompleteStyleDeclaration(e,i-1):{},h=this._measureChar(t,o,r,a),l=h.kernedWidth,c=h.width;0!==this.charSpacing&&(c+=n=this._getWidthOfCharSpacing(),l+=n);var u={width:c,left:0,height:o.fontSize,kernedWidth:l,deltaY:o.deltaY};if(i>0&&!s){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+h.kernedWidth-h.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),r=1,s=e.length;r0){var E=v+n+u;"rtl"===this.direction&&(E=this.width-E-d),l&&m&&(t.fillStyle=m,t.fillRect(E,c+w*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,m=p,r=s,o=a}else d+=f.kernedWidth;E=v+n+u,"rtl"===this.direction&&(E=this.width-E-d),t.fillStyle=p,g&&p&&t.fillRect(E,c+w*r+o,d-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var r=t||this,s=this.fontFamily,n=e.Text.genericFonts.indexOf(s.toLowerCase())>-1,o=void 0===s||s.indexOf("'")>-1||s.indexOf(",")>-1||s.indexOf('"')>-1||n?r.fontFamily:'"'+r.fontFamily+'"';return[e.isLikelyNode?r.fontWeight:r.fontStyle,e.isLikelyNode?r.fontStyle:r.fontWeight,i?this.CACHE_FONT_SIZE+"px":r.fontSize+"px",o].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),r=new Array(i.length),s=["\n"],n=[],o=0;o-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}x.IText=x.util.createClass(x.Text,x.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:r.left,topOffset:r.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,r,s,n=0,o=0,a=this.get2DCursorLocation(t);r=a.charIndex,i=a.lineIndex;for(var h=0;h0?o:0)},"rtl"===this.direction&&(s.left*=-1),this.cursorOffsetCache=s,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),r=i.lineIndex,s=i.charIndex>0?i.charIndex-1:0,n=this.getValueOfPropertyAt(r,s,"fontSize"),o=this.scaleX*this.canvas.getZoom(),a=this.cursorWidth/o,h=t.topOffset,l=this.getValueOfPropertyAt(r,s,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-n*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,s,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,n)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,r=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,s=-1!==this.textAlign.indexOf("justify"),n=this.get2DCursorLocation(i),o=this.get2DCursorLocation(r),a=n.lineIndex,h=o.lineIndex,l=n.charIndex<0?0:n.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=h;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var v=t.left+f+_,y=p-_,S=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",S=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,S),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),x.IText.fromObject=function(e,i){if(t(e),e.styles)for(var r in e.styles)for(var s in e.styles[r])t(e.styles[r][s]);x.Object._fromObject("IText",e,i,"text")}}(),b=x.util.object.clone,x.util.object.extend(x.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],x.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,r){var s;return s={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){s.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return s.isAborted}}),s},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&rthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===r||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var r=i.slice(0,t),s=x.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:s,selectionEnd:s};var n=i.slice(t,e);return{selectionStart:s,selectionEnd:s+x.util.string.graphemeSplit(n).length}},fromGraphemeToStringSelection:function(t,e,i){var r=i.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),r=i.lineIndex,s=i.charIndex,n=this.getValueOfPropertyAt(r,s,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.topOffset+n},l=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/l,d=c.height/l,f=u-n,g=d-n,_=c.clientWidth/u,p=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=_,h.y*=p,h.x<0&&(h.x=0),h.x>f&&(h.x=f),h.y<0&&(h.y=0),h.y>g&&(h.y=g),h.x+=this.canvas._offset.left,h.y+=this.canvas._offset.top,{left:h.x+"px",top:h.y+"px",fontSize:n+"px",charHeight:n}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,r,s=this.get2DCursorLocation(t,!0),n=this.get2DCursorLocation(e,!0),o=s.lineIndex,a=s.charIndex,h=n.lineIndex,l=n.charIndex;if(o!==h){if(this.styles[o])for(i=a;i=l&&(r[c-d]=r[u],delete r[u])}},shiftLineStyles:function(t,e){var i=b(this.styles);for(var r in this.styles){var s=parseInt(r,10);s>t&&(this.styles[s+e]=i[s],i[s-e]||delete this.styles[s])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var s,n={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(s=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,n[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=n,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:b(r[i-1])}:s?this.styles[t+i]={0:b(s)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var s=this.styles[t],n=s?b(s):{};for(var o in i||(i=1),n){var a=parseInt(o,10);a>=e&&(s[a+i]=n[a],n[a-i]||delete s[a])}if(this._forceClearCache=!0,r)for(;i--;)Object.keys(r[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=b(r[i]));else if(s)for(var h=s[e?e-1:1];h&&i--;)this.styles[t][e+i]=b(h)},insertNewStyleBlock:function(t,e,i){for(var r=this.get2DCursorLocation(e,!0),s=[0],n=0,o=0;o0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,s[0],i),i=i&&i.slice(s[0]+1)),n&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+s[0],n),o=1;o0?this.insertCharStyleObject(r.lineIndex+o,0,s[o],i):i&&this.styles[r.lineIndex+o]&&i[0]&&(this.styles[r.lineIndex+o][0]=i[0]),i=i&&i.slice(s[o]+1);s[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,s[o],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),x.util.object.extend(x.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),r=0,s=0,n=0,o=0,a=0,h=0,l=this._textLines.length;h0&&(o+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));s=this._getLineLeftOffset(a)*this.scaleX,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+s);for(var c=0,u=e.length;cn||o<0?0:1);return this.flipX&&(a=s-a),a>this._text.length&&(a=this._text.length),a}}),x.util.object.extend(x.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=x.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):x.document.body.appendChild(this.hiddenTextarea),x.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),x.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),x.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),x.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),x.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),x.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(x.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,r,s,n,o,a=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,h=this._text.length,l=a.length,c=l-h,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),_=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):l0&&(r+=(i=this.__charBounds[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),s=r.lineIndex;if(s===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var n=r.charIndex,o=this._getWidthBeforeCursor(s,n),a=this._getIndexOnLine(s+1,o);return this._textLines[s].slice(n).length+a+1+this.missingNewlineOffset(s)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),s=r.lineIndex;if(0===s||t.metaKey||33===t.keyCode)return-i;var n=r.charIndex,o=this._getWidthBeforeCursor(s,n),a=this._getIndexOnLine(s-1,o),h=this._textLines[s].slice(0,n),l=this.missingNewlineOffset(s-1);return-this._textLines[s-1].length+a-h.length+(1-l)},_getIndexOnLine:function(t,e){for(var i,r,s=this._textLines[t],n=this._getLineLeftOffset(t),o=0,a=0,h=s.length;ae){r=!0;var l=n-i,c=n,u=Math.abs(l-e);o=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var r;if(t.altKey)r=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;r=this["findLineBoundary"+i](this[e])}if(void 0!==typeof r&&this[e]!==r)return this[e]=r,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,r){void 0===r&&(r=i),r>i&&this.removeStyleFromTo(i,r);var s=x.util.string.graphemeSplit(t);this.insertNewStyleBlock(s,i,e),this._text=[].concat(this._text.slice(0,i),s,this._text.slice(r)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=x.util.toFixed,e=/ +/g;x.util.object.extend(x.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,r=[],s=[],n=t;this._setSVGBg(s);for(var o=0,a=this._textLines.length;o",x.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var s,n,o,a,h,l=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];r+=l*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)h=g===_||this.charSpacing,u+=f[g],o=this.__charBounds[e][g],0===d?(i+=o.kernedWidth-o.width,d+=o.width):d+=o.kernedWidth,c&&!h&&this._reSpaceAndTab.test(f[g])&&(h=!0),h||(s=s||this.getCompleteStyleDeclaration(e,g),n=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(s,n)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",s=n,i+=d,d=0)},_pushTextBgRect:function(e,i,r,s,n,o){var a=x.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var s,n,o=this._textLines[e],a=this.getHeightOfLine(e)/this.lineHeight,h=0,l=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=o.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,r=0,s={},n=0;n0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&n>0&&(i++,r++),s[n]={line:e,offset:i},r+=t.graphemeLines[n].length,i+=t.graphemeLines[n].length;return s},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var r=this._styleMap[i];r&&(i=r.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,r=0,s=!1,n=this._styleMap[t],o=this._styleMap[t+1];for(var a in n&&(t=n.line,r=n.offset),o&&(s=o.line===t,e=o.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var h in i[a])if(h>=r&&(!s||hr&&!p?(a.push(h),h=[],n=f,p=!0):n+=m,p||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(h),_+s>this.dynamicMinWidth&&(this.dynamicMinWidth=_-m+s),a},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),r=this._wrapText(i.lines,this.width),s=new Array(r.length),n=0;n{},898:()=>{},245:()=>{}},I={};function E(t){var e=I[t];if(void 0!==e)return e.exports;var i=I[t]={exports:{}};return T[t](i,i.exports,E),i.exports}E.d=(t,e)=>{for(var i in e)E.o(e,i)&&!E.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},E.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var O={};(()=>{let t;E.d(O,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?E(653).fabric:{version:"5.2.1"}})();var R=O.R; /*! * Dynamsoft JavaScript Library * @product Dynamsoft Camera Enhancer JS Edition @@ -18,4 +18,4 @@ import{Howl as t}from"dm-howler";const e="undefined"==typeof self;let i,r,s,n,o; * @version 3.3.1 (js 20230217) * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest - */const A="undefined"==typeof self;let D,M,F,L,P;if("undefined"!=typeof navigator&&(D=navigator,M=D.userAgent,F=D.platform,L=D.mediaDevices),!A){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:D.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:F,search:"Win"},Mac:{str:F},Linux:{str:F}};let i="unknownBrowser",r=0,s="unknownOS";for(let e in t){const s=t[e]||{};let n=s.str||M,o=s.search||e,a=s.verStr||M,h=s.verSearch||e;if(h instanceof Array||(h=[h]),-1!=n.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||M,n=i.search||t;if(-1!=r.indexOf(n)){s=t;break}}"Linux"==s&&-1!=M.indexOf("Windows NT")&&(s="HarmonyOS"),P={browser:i,version:r,OS:s}}A&&(P={browser:"ssr",version:0,OS:"ssr"});const k="undefined"!=typeof WebAssembly&&M&&!(/Safari/.test(M)&&!/Chrome/.test(M)&&/\(.+\s11_2_([2-6]).*\)/.test(M)),B=!("undefined"==typeof Worker),N=!(!L||!L.getUserMedia),j=async()=>{let t=!1;if(N)try{(await L.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===P.browser&&P.version>66||"Safari"===P.browser&&P.version>13||"OPR"===P.browser&&P.version>43||"Edge"===P.browser&&P.version;const V=(()=>{if(!A&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();class U{constructor(t,e){this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,this._setFabricObject(t),this._mediaType=t.type,this.styleSelector="default",this.styleId=e}get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.styleSelector="selected"})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.styleSelector="selected":this.styleSelector="default","textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let s=r.get(e);s||(s=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,s,n;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,s=t+window.scrollX,n=e+window.scrollY;const a=this._drawingLayer.fabricCanvas.lowerCanvasEl.width,h=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,l=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),c=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),u=l/c,d=a/h,f=this._drawingLayer._getObjectFit();let g,_,p,m,v=1;if("contain"===f)u0?i-1:r,H),actionName:"modifyPolygon",pointIndex:i}),t}),{})}_extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new R.Control({positionHandler:G,actionHandler:Y(r>0?r-1:i,H),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}_extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,s=i.y-e.pathOffset.y;const n=R.util.transformPoint({x:r,y:s},e.calcTransformMatrix());t.push({x:n.x,y:n.y})}return t}}}const z=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=s.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let s=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(s)}}})(e),(t=>{let e="";for(let i=0;im?(g=d,_=d/p,{x:s.x*i.width,y:(s.y-(f-_)/2)*i.width}):(g=f*p,_=f,{x:(s.x-(d-g)/2)*i.height,y:s.y*i.height}):"cover"===l?p>m?{x:(c-i.height*d)/2+s.x*i.height,y:s.y*i.height}:{x:s.x*i.width,y:(u-i.width*f)/2+s.y*i.width}:{x:s.x*i.width,y:s.y*i.height}}return i={width:1,height:1},{x:s.x*i.width,y:s.y*i.height}},R.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();R.util.addListener(R.document,"touchend",this._onTouchEnd,{passive:!1}),R.util.addListener(R.document,"touchmove",this._onMouseMove,{passive:!1}),R.util.removeListener(i,r+"down",this._onMouseDown)},R.Textbox.prototype._wrapLine=function(t,e,i,r){const s=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),n=!(!s||!s.length);var o=0,a=this.splitByGrapheme||n,h=[],l=[],c=a?R.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,_=0,p=0,m=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!m?(h.push(l),l=[],o=g,m=!0):o+=v,m||a||l.push(f),l=l.concat(u),_=a?0:this._measureWord([f],e,d),d++,m=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class K{constructor(t,e,i,r){let s,n;switch(this.mapMediaType_Style=new Map,this.mode="viewer",this.onSelectionChange=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=t.getFabricCanvas():(this.fabricCanvas=new R.Canvas(t,Object.assign(r,{allowTouchScrolling:!0})),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChange&&t.onSelectionChange(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChange&&t.onSelectionChange([],e)}),0)}})),this.fabricCanvas.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],s=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&s.push(i)}setTimeout((()=>{t.onSelectionChange&&t.onSelectionChange(r,s)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas),this.id=e,this._mapDrawingStyles=i,e){case 1:s=i.get(1),n=i.get(5);break;case 2:s=i.get(2),n=i.get(6);break;case 3:s=i.get(3),n=i.get(7);break;default:s=i.get(4),n=i.get(8)}for(let t of U.arrMediaTypes)this.mapMediaType_Style.set(t,{default:s,selected:n})}getId(){return this.id}_getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=this._mapDrawingStyles.get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(t){return t.styleId?t.styleId:this.mapMediaType_Style.get(t._mediaType)[t.styleSelector].styleId}_getItemCurrentStyle(t){if(t.styleId)return this._getDrawingStyle(t.styleId);return t._mapStyle.get(t.styleSelector)||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){let s;switch(t){case"rect":s=this.fabricCanvas.getObjects("rect");break;case"arc":s=this.fabricCanvas.getObjects("circle");break;case"polygon":s=this.fabricCanvas.getObjects("polygon");break;case"image":s=this.fabricCanvas.getObjects("image");break;case"text":s=this.fabricCanvas.getObjects("textbox");break;case"line":s=this.fabricCanvas.getObjects("line");break;case"path":s=this.fabricCanvas.getObjects("path")}for(let t of s){if(!this._arrFabricObject.includes(t))continue;const r=t.getDrawingItem();r.styleSelector===e&&this._changeItemStyle(r,i,!0)}r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=this._getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=this._getDrawingStyle(e.styleId);else{i=this.mapMediaType_Style.get(e._mediaType)[t.styleSelector];const r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},s=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let s,n;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){s=t.getChildItems();for(let t of s)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(s){for(let t of s){const e=this.mapMediaType_Style.get(t._mediaType);for(let i of U.arrStyleSelectors)t._mapStyle.set(i,e[i]);if(t.styleId)n=this._getDrawingStyle(t.styleId);else{n=e.default;const i=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected,!0)},r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default,!0)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,n,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapMediaType_Style.get(t._mediaType);for(let i of U.arrStyleSelectors)t._mapStyle.set(i,e[i]);if(t.styleId)n=this._getDrawingStyle(t.styleId);else{n=e.default;const i=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected)},r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,n)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;e{for(let e of this._arrDrawingLayer)if(e.getId()===t)return!0;return!1};if(void 0===e){for(let t=100;;t++)if(!i(t)){e=t;break}}else if(i(e))throw new Error("Existed drawing layer id.");const r=new K(t,e,this._mapDrawingStyles,{enableRetinaScaling:!1});return r._manager=this,this._arrDrawingLayer.push(r),this._switchPointerEvent(),r}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._arrDrawingLayer[0].fabricCanvas.getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){this._arrDrawingLayer.length&&(this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.display=t?"block":"none")}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class q{constructor(t){this._controlTarget=null,this._arrUsers=[],this._mapAction_UserArgs=new Map,this._mapProperty_UserValue=new Map,this._mapAction_Callbacks=new Map,this._controlTarget=t}setControlTarget(t){this._controlTarget=t}getControlTarget(){return this._controlTarget}register(t){this._arrUsers.includes(t)||this._arrUsers.push(t)}logout(t){const e=this._arrUsers.indexOf(t);-1!==e&&(this.clearUserDisiredAction({user:t}),this.clearUserDisiredValue({user:t}),this._arrUsers.splice(e,1))}getRegisteredUsers(){return this._arrUsers}ifUserExisted(t){return this._arrUsers.includes(t)}setDisiredValue(t,e,i,r){if(!this._arrUsers.includes(t))throw new Error("Unregistered user.");r&&(this._controlTarget[e]=i),this._mapProperty_UserValue.get(e)?this._mapProperty_UserValue.get(e).set(t,i):this._mapProperty_UserValue.set(e,new Map([[t,i]]))}clearUserDisiredValue(t){if(t&&(t.user||t.property)){if(t.property&&t.user){const e=this._mapProperty_UserValue.get(t.property);if(!e)return;e.delete(t.user)}else if(t.property)this._mapProperty_UserValue.delete(t.property);else if(t.user)for(let e of this._mapProperty_UserValue.values())e.delete(t.user)}else this._mapProperty_UserValue=new Map}getValue(t){if(!this._controlTarget)throw new Error("Control target is not set.");return this._controlTarget[t]}getPropertyDisiredValue(t){if(this._mapProperty_UserValue.get(t)){const e=[],i=this._mapProperty_UserValue.get(t);for(let t of i.values())e.push(t);return e}return null}setDisiredAction(t,e,i,r){if(!this._arrUsers.includes(t))throw new Error("Unregistered user.");return i||(i=[]),r?this._controlTarget[e](...i):(this._mapAction_UserArgs.get(e)?this._mapAction_UserArgs.get(e).set(t,i):this._mapAction_UserArgs.set(e,new Map([[t,i]])),this._render(e))}clearUserDisiredAction(t){if(t&&(t.user||t.actionName)){if(t.actionName&&t.user){const e=this._mapAction_UserArgs.get(t.actionName);if(!e)return;e.delete(t.user)}else if(t.actionName)this._mapAction_UserArgs.delete(t.actionName);else if(t.user)for(let e of this._mapAction_UserArgs.values())e.delete(t.user);this.render()}else this._mapAction_UserArgs=new Map}addCallback(t,e){const i=this._mapAction_Callbacks.get(t);i?i.push(e):this._mapAction_Callbacks.set(t,[e])}removeCallback(t,e){const i=this._mapAction_Callbacks.get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}clearCallback(t){t?this._mapAction_Callbacks.delete(t):this._mapAction_Callbacks.clear()}_fireCallback(t){const e=this._mapAction_Callbacks.get(t);if(e)for(let t of e){if(!t)return;setTimeout(t.bind(this._controlTarget),0)}}_render(t){const e=this._mapAction_UserArgs.get(t);if(!e)throw new Error("Unrecorded action.");if(e.size===this._arrUsers.length){let i=[];for(let t of e.values())t.length>0&&(i=t);if(this._controlTarget[t]){const e=this._controlTarget[t](...i);return this._mapAction_UserArgs.delete(t),this._fireCallback(t),e}}}render(t){if(t)return this._render(t);for(let t of this._mapAction_UserArgs.keys())this._render(t)}}class Q{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const s=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*s[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Q.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return Q.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return Q.multiply(t,[e,0,0,0,i,0,0,0,1])}}var $;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}($||($={}));const tt=(t,e,i,r)=>{let s=e+Math.round((t-e)/i)*i;return r&&(s=Math.min(s,r)),s};class et{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this._predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this._mapCameraResolutions=new Map,this._bWebGLSupported=!0,this.extraBindings=[],this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode&&!this.getDrawingLayers().some((t=>"editor"==t.getMode()))){if(!this._singleFrameModeIpt){const t=document.createElement("input");this._singleFrameModeIpt=t,t.setAttribute("type","file"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),t.setAttribute("capture",""),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";const i=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),s=new Image;s.dbrObjUrl=i,s.src=i,s.onload=()=>{t(s)},s.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(e),r=i instanceof HTMLImageElement?i.naturalWidth:i.width,s=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=s;const n=t=>{const e=Date.now();if(0===r||0===s)return null;if(t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");const i=this._scanRegion,n=this.getFrameSize(r,s,i,this.maxCvsSideLength);if(!n)return null;let o=!0;r===n.sWidth&&s===n.sHeight&&(o=!1);const a=this.mapPixelFormatString_Enum.get(this.framePixelFormat.toLowerCase()),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:n.sx,sy:n.sy,width:n.dWidth,height:n.dHeight,colorMode:null,pixelFormat:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:n.sWidth,_sHeight:n.sHeight,_bUseWebGL:null},l=this._getImageData(t,r,s,n,null,{pixelFormat:a});if(!l)return null;const c=Date.now();return h.data=l.data,h.pixelFormat=h.colorMode=l.pixelFormat,h._bUseWebGL=l._bUseWebGL,h.timeSpent=c-e,h.timeStamp=c,l.pixelFormat===$.GREY?h.stride=h.width:h.stride=4*h.width,h};(t=>{let e=this._cvsSingleFrameMode;if(!e){if(e=document.createElement("canvas"),!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e),e.style.position="absolute",e.style.width="100%",e.style.height="100%",e.style.left="0",e.style.top="0",e.style.objectFit="contain",e.style.pointerEvents="none",this._cvsSingleFrameMode=e}e.width==r&&e.height==s||(e.width=r,e.height=s);const i=e.getContext("2d");i.clearRect(0,0,e.width,e.height),i.drawImage(t,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t);let o;this._updateDrawingLayersSize();try{o=n(i)}catch(t){throw t}const a=this.mapCameraEvents.get("singleframeacquired");for(let t of a)if(t)try{const e={data:new Uint8Array(o.data),region:JSON.parse(JSON.stringify(o.region)),sx:o.sx,sy:o.sy,width:o.width,height:o.height,stride:o.stride,colorMode:o.colorMode,pixelFormat:o.pixelFormat,timeSpent:o.timeSpent,timeStamp:o.timeStamp,isCropped:o.isCropped,toCanvas:o.toCanvas,_sWidth:o._sWidth,_sHeight:o._sHeight,_bUseWebGL:o._bUseWebGL};await t.apply(this,[e])}catch(t){console.error(t)}})),t.style.position="fixed",t.style.left="-1px",t.style.top="-1px",t.style.width="1px",t.style.height="1px",t.style.backgroundColor="transparent",t.style.color="transparent",document.body.appendChild(t)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._framePixelFormat=void 0,this._defaultFramePixelFormat="rgba",this.mapPixelFormatString_Enum=new Map([["grey",$.GREY],["grey32",$.GREY32],["rgba",$.RGBA],["rbga",$.RBGA],["grba",$.GRBA],["gbra",$.GBRA],["brga",$.BRGA],["bgra",$.BGRA]]),this.shaderPixelFormat=$.RGBA,this.maxVideoCvsLength=3,this._reusedCvs=null,this._reusedWebGLCvs=null,this._tempDataContainer=null,this._webGLTexture=null,this._webGLProgramInfo=null,this._webGLBuffers=null,this._softwareScale=1,this._scaleCenter={x:0,y:0},this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,_focusArea:null},this._tapFocusEnabled=!0,this._focusSupported=!0,this._tapDoFocus=async t=>{if(this._touchMoved)return void(this._touchMoved=!1);if(!this._tapFocusEnabled)return;if(!this._bOpen)return;if(this.singleFrameMode)return;if(!this._video||this._video.paused)return;if(!this._videoTrack)return;if(!this._focusSupported)return;if(this.getDrawingLayers().some((t=>"editor"==t.getMode())))return;if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let e,i,r,s;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)e=t.clientX,i=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;e=t.changedTouches[0].clientX,i=t.changedTouches[0].clientY}const n=this.getVideoFit(),o=this._video.videoWidth,a=this._video.videoHeight,h=this._elContainer.getBoundingClientRect(),l=h.left,c=h.top,u=window.getComputedStyle(this._elContainer),d=parseFloat(u.width),f=parseFloat(u.height),g=d/f,_=o/a;let p=1;if("contain"===n)_>g?(p=d/o,r=(e-l)/p,s=(i-c-(f-d/_)/2)/p):(p=f/a,s=(i-c)/p,r=(e-l-(d-f*_)/2)/p);else{if("cover"!==n)throw new Error("Unsupported object-fit.");_>g?(p=f/a,s=(i-c)/p,r=(e-l+(f*_-d)/2)/p):(p=d/o,r=(e-l)/p,s=(i-c+(d/_-f)/2)/p)}const m={x:r+"px",y:s+"px"},v=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=v;await this._setLocalFocus(m,v,y,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance),this._focusParameters.taskBackToContinous=setTimeout((()=>{this._videoTrack&&this._videoTrack.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime)},this._touchMoved=!1,this._touchMoveEvent=()=>{this._touchMoved=!0},this._recordedStates={},this.playCallbackInfo=null,this._toCanvas=function(){const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,"grey"===(this.pixelFormat||this.colorMode)){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let t,e;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];t=i.getAttribute("data-width"),e=i.getAttribute("data-height")}await this.setResolution(t,e),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this.singleFrameMode)if("visible"===document.visibilityState){if(this._bOpen&&this._vc_bPlayingVideoBeforeHide)if(this.videoSrc)this._video.play();else if(this._video.srcObject){const t=this._video.srcObject.getTracks()[0];this._video.srcObject.active&&t&&!t.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(["iPhone","iPad"].includes(P.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let t of this._arrScanRegionOverlays)t&&(t.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&(t.style.display="",this._updateScanRegionOverlay(t));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null}static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:k,worker:B,getUserMedia:N,camera:await j(),browser:P.browser,version:P.version,OS:P.OS}))()}static set engineResourcePath(t){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");et._engineResourcePath=(t=>{if(null==t&&(t="./"),!A){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static isDCEFrame(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&"data"in t&&"region"in t&&"sx"in t&&"sy"in t&&"width"in t&&"height"in t&&("colorMode"in t||"pixelFormat"in t)&&"timeSpent"in t&&"timeStamp"in t&&"isCropped"in t&&"toCanvas"in t&&"_sWidth"in t&&"_sHeight"in t&&"_bUseWebGL"in t}static async testCameraAccess(){try{if(!navigator||!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return{ok:!1,message:"Insecure context."};(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()}))}catch(t){if("OverconstrainedError"===t.name||"NotFoundError"===t.name)return{ok:!1,message:"No camera detected."};if("NotAllowedError"===t.name)return{ok:!1,message:"No permission to access camera."};if("AbortError"===t.name)return{ok:!1,message:"Some problem occurred which prevented the device from being used."};if("NotReadableError"===t.name)return{ok:!1,message:"A hardware error occurred."};if("SecurityError"===t.name)return{ok:!1,message:"User media support is disabled."};throw t}return{ok:!0,message:"Successfully accessed the camera."}}set maxCvsSideLength(t){if(t<=0)throw new Error("Invalid value.");this._maxCvsSideLength=t}get maxCvsSideLength(){if(void 0!==this._maxCvsSideLength)return this._maxCvsSideLength;if(this._controler){const t=this._controler.getPropertyDisiredValue("maxCvsSideLength");if(t&&1===t.length)return t[0]}return this._defaultMaxCvsSideLength}static set defaultUIElementURL(t){et._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=et._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",et.engineResourcePath)}getUIElement(){return this.UIElement}async setUIElement(t){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof t||t instanceof String){if(!t.trim().startsWith("<")){let e=await fetch(t);if(!e.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+e.statusText);t=await e.text()}if(!t.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let e=document.createElement("div");e.innerHTML=t;for(let t=0;t100||t.regionTop>100||t.regionRight>100||t.regionBottom>100)))}set scanRegion(t){if(!this._checkValidRegion(t))throw new Error("Invalid region.");this._scanRegion=JSON.parse(JSON.stringify(t)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t)}setScanRegion(t){this.scanRegion=t}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}_calculateCvsSize(){if(!this._bOpen)return null;let t,e,i;if(this.singleFrameMode)t=this._imgWidth,e=this._imgHeight,i="contain";else{if(!this._video)return null;t=this._video.videoWidth,e=this._video.videoHeight,i=this.getVideoFit()}return{width:t,height:e,objectFit:i}}addScanRegionOverlayCanvas(){this._assertOpen();const t=document.createElement("canvas");if(this._updateScanRegionOverlay(t),!this._scanRegionOverlayContainer){const t=document.createElement("div");if(this._scanRegionOverlayContainer=t,t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.overflow="hidden",t.style.pointerEvents="none",this._layerBaseCvs)this._layerBaseCvs.parentElement.after(t);else if(this._cvsScanRegion)this._cvsScanRegion.after(t);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(t);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(t);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(t)}this._recordedStates.overlayShow=!0}return this._scanRegionOverlayContainer.append(t),this._arrScanRegionOverlays.push(t),t}removeScanRegionOverlayCanvas(t){const e=this._arrScanRegionOverlays.indexOf(t);-1!==e&&(t.remove(),this._arrScanRegionOverlays.splice(e,1))}_updateScanRegionOverlay(t){if(!t)return;const e=this._calculateCvsSize();if(!e)return;const{width:i,height:r,objectFit:s}=e;if(i<=0||r<=0)return t.width=0,void(t.height=0);const n=this._getRegionInPixels(i,r,this._scanRegion),o=this.getFrameSize(i,r,this._scanRegion,this.maxCvsSideLength),a=o.dWidth,h=o.dHeight;t.width==a&&t.height==h||(t.width=a,t.height=h);const l=window.getComputedStyle(this._elContainer),c=parseFloat(l.width),u=parseFloat(l.height),d=c/u,f=i/r;let g,_,p,m,v=1;"contain"===s?(f>d?(v=c/i,g=0,_=(u-r*v)/2):(v=u/r,g=(c-i*v)/2,_=0),g+=n.regionLeft*v,_+=n.regionTop*v,p=(n.regionRight-n.regionLeft)*v,m=(n.regionBottom-n.regionTop)*v):"cover"===s?(f>d?(v=u/r,g=n.regionLeft*v-(i*v-c)/2,_=n.regionTop*v):(v=c/i,g=n.regionLeft*v,_=n.regionTop*v-(r*v-u)/2),p=(n.regionRight-n.regionLeft)*v,m=(n.regionBottom-n.regionTop)*v):(g=0,_=0,p=0,m=0),t.style.position="absolute",t.style.left=g+"px",t.style.top=_+"px",t.style.width=p+"px",t.style.height=m+"px"}showScanRegionOverlays(){this._scanRegionOverlayContainer&&("none"==this._scanRegionOverlayContainer.style.display&&(this._scanRegionOverlayContainer.style.display=""),this._recordedStates.overlayShow=!0)}hideScanRegionOverlays(){this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none",this._recordedStates.overlayShow=!1)}setViewDecorator(t,e){if(!t)return void(this._cvsViewDecorator&&(this._cvsViewDecorator.remove(),this._cvsViewDecorator=null));if(!e)throw new Error("Invalid area.");this._assertOpen();let i=[];if("string"==typeof t?i.push(t):Array.isArray(t)&&(i=JSON.parse(JSON.stringify(t))),!this._cvsViewDecorator){if(this._cvsViewDecorator=document.createElement("canvas"),this._scanRegionOverlayContainer)this._scanRegionOverlayContainer.after(this._cvsViewDecorator);else if(this._layerBaseCvs)this._layerBaseCvs.parentElement.after(this._cvsViewDecorator);else if(this._cvsScanRegion)this._cvsScanRegion.after(this._cvsViewDecorator);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(this._cvsViewDecorator);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(this._cvsViewDecorator);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(this._cvsViewDecorator)}this._recordedStates.decoratorShow=!0}this._decoratorArea=JSON.parse(JSON.stringify(e)),this._decoratorType.length=0;const r=["rectangle","focus"],s=["crossline","crosshair"];let n=!1,o=!1;for(let t of i)t=t.toLowerCase(),r.includes(t)&&!n&&(n=!0,this._decoratorType.push(t)),s.includes(t)&&!o&&(o=!0,!this._decoratorType.includes(t)&&this._decoratorType.push(t));this._updateViewDecorator()}getViewDecorator(){return{type:JSON.parse(JSON.stringify(this._decoratorType)),area:JSON.parse(JSON.stringify(this._decoratorArea)),canvas:this._cvsViewDecorator}}showViewDecorator(){this._cvsViewDecorator&&("none"==this._cvsViewDecorator.style.display&&(this._cvsViewDecorator.style.display=""),this._recordedStates.decoratorShow=!0)}hideViewDecorator(){this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none",this._recordedStates.decoratorShow=!1)}setViewDecoratorLineWidth(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("lineWidth"))throw new Error(`It is not allowed to change the property 'lineWidth' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].lineWidth=e,this._updateViewDecorator()}setViewDecoratorStrokeStyle(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("strokeStyle"))throw new Error(`It is not allowed to change the property 'strokeStyle' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].strokeStyle=e,this._updateViewDecorator()}setViewDecoratorFillStyle(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("fillStyle"))throw new Error(`It is not allowed to change the property 'fillStyle' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].fillStyle=e,this._updateViewDecorator()}setViewDecoratorMaskFillStyle(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("maskFillStyle"))throw new Error(`It is not allowed to change the property 'maskFillStyle' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].maskFillStyle=e,this._updateViewDecorator()}_updateViewDecorator(){if(!this._bOpen)return;if(!this._cvsViewDecorator||!this._decoratorArea)return;let t;if(this.singleFrameMode)t="contain";else{if(!this._video)return;t=this.getVideoFit()}const e=this._cvsViewDecorator;e.style.position="absolute",e.style.width="100%",e.style.height="100%",e.style.left="0",e.style.top="0",e.style.objectFit=t,e.style.pointerEvents="none";const i=this.getVisibleRegion(!0),r=i.regionRight-i.regionLeft,s=i.regionBottom-i.regionTop;if(e.width==r&&e.height==s||(e.width=r,e.height=s),r<=0||s<=0)return;const n=e.getContext("2d");n.clearRect(0,0,e.width,e.height);const o=this._decoratorArea.x/100*r,a=this._decoratorArea.y/100*s,h=this._decoratorArea.width/100*r,l=this._decoratorArea.height/100*s;for(let t of this._decoratorType){if("rectangle"===t){n.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,n.fillRect(0,0,e.width,e.height),n.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),n.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,n.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),n.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,n.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const t=n.lineWidth/2;n.strokeRect(Math.round(o-t),Math.round(a-t),Math.round(h+n.lineWidth),Math.round(l+n.lineWidth))}if("focus"===t){n.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,n.fillRect(0,0,e.width,e.height),n.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),n.fillStyle=this._viewDecoratorInfo.focus.fillStyle,n.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),n.lineWidth=this._viewDecoratorInfo.focus.lineWidth,n.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const t=n.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];n.beginPath();for(let t=0;t{const t=parseFloat(window.getComputedStyle(this._elContainer).width),e=parseFloat(window.getComputedStyle(this._elContainer).height);let n,o={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===s?t/ethis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){if(void 0!==this._maxNumberOfFramesInBuffer)return this._maxNumberOfFramesInBuffer;if(this._controler){const t=this._controler.getPropertyDisiredValue("maxNumberOfFramesInBuffer");if(t&&1===t.length)return t[0]}return this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(t){this._refreshInterval=t}get refreshInterval(){if(void 0!==this._refreshInterval)return this._refreshInterval;if(this._controler){const t=this._controler.getPropertyDisiredValue("refreshInterval");if(t&&1===t.length)return t[0]}return this._defaultRefreshInterval}static async createInstance(t){let e=new et;("string"==typeof t||t instanceof String)&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return this._hasEngineResourceLoaded=!0,e._drawingLayersManager=new J,e}static async playVideo(t,e,i){return new Promise(((r,s)=>{t||s(new Error("Invalid video element.")),e||s(new Error("Invalid source.")),t.onloadedmetadata=async()=>{t.onloadedmetadata=null,await t.play(),r(t)},"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,void 0!==i&&setTimeout((()=>s(new Error("Failed to play video. Timeout."))),i)}))}static findBestRearCamera(t){if(!t||!t.length)return null;const e=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"];for(let i of t){const t=i.label.toLowerCase();if(t&&e.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return i.deviceId}return["Android","HarmonyOS"].includes(P.OS)?t[t.length-1].deviceId:null}async play(t,e,i,r){if(this._video&&this.videoSrc){const t=await et.playVideo(this._video,this.videoSrc,4e3);if(!this._video)return t.pause(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};const e={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};this.playCallbackInfo=JSON.parse(JSON.stringify(e));const i=this.mapCameraEvents.get("played");for(let t of i){if(!t)continue;const i=JSON.parse(JSON.stringify(e));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[i])}),0)}return this._recordedStates.videoPlaying=!0,e}if(this.singleFrameMode)return r&&r.notTriggerSingleFrameClick||this._clickIptSingleFrameMode(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};if(!this._video)throw new Error("'video' is null or undefined.");const s=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,s{var r;try{this._video&&this._video.srcObject&&this.stop(),et._onLog&&et._onLog("DCE: ======before video========");const s=()=>{if(!this._video)throw a&&a.getTracks().forEach((t=>{t.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},n=this.getVideoSettings();let o,a;if("boolean"==typeof n.video&&(n.video={}),t)delete n.video.facingMode,n.video.deviceId={exact:t};else if(n.video.deviceId);else if(this._lastDeviceId)delete n.video.facingMode,n.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&et.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete n.video.facingMode,n.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const t=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),e=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));t&&e&&(n.video.width=t,n.video.height=e)}else if(this.ifSkipCameraInspection);else if(n.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let t=n.video.facingMode;if(t instanceof Array&&t.length&&(t=t[0]),t=t.exact||t.ideal||t,"environment"===t){o=!0;const t=et.findBestRearCamera(this._allCameras);t&&(delete n.video.facingMode,n.video.deviceId={ideal:t})}}e&&(n.video.width={ideal:e}),i&&(n.video.height={ideal:i}),et._onLog&&et._onLog("DCE: ======try getUserMedia========");let h=[0,500],l=null;const c=async t=>{for(let e of h){e&&await new Promise((t=>setTimeout(t,e))),s();try{et._onLog&&et._onLog("DCE: ask "+JSON.stringify(t)),a=await navigator.mediaDevices.getUserMedia(t);break}catch(t){l=t,et._onLog&&et._onLog("DCE: "+t.message||t)}}};let u;if(await c(n),a||(et._onLog&&et._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(n)),"object"==typeof u.video&&(["iPhone","iPad"].includes(P.OS)?(e>=1280||i>=1280?u.video.width=1280:e>=640||i>=640?u.video.width=640:(e<640||i<640)&&(u.video.width=320),delete u.video.height):o&&!n.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0),et._onLog&&et._onLog("DCE: "+u),await c(u)),a||(h=[1e3,2e3],await c(n)),a||await c(u),!a)throw l;const d=()=>{const t=a.getVideoTracks();let e,i;if(t.length&&(e=this._videoTrack=t[0]),this._video&&e){const t=e.getSettings();if(t)for(let r of this._allCameras)if(t.deviceId===r.deviceId){r._checked=!0,r.label=e.label,i=r;break}}this._currentCamera=i};if(await this.getAllCameras(!1),s(),o){d();const t=et.findBestRearCamera(this._allCameras),e=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;t&&t!=e&&(a.getTracks().forEach((t=>{t.stop()})),h=[0,500,1e3,2e3],await c(n))}et._onLog&&et._onLog("DCE: ======play video========"),s(),await et.playVideo(this._video,a,4e3),s(),et._onLog&&et._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=f,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),et._onLog&&et._onLog("DCE: got "+f),d(),this._renderSelCameraInfo();const g={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};g.deviceId&&(this._lastDeviceId=g.deviceId,this.ifSaveLastUsedCamera&&et.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),n.video.width&&n.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(n.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(n.video.height)))));const _=this.mapCameraEvents.get("played");for(let t of _){if(!t)continue;const e=JSON.parse(JSON.stringify(g));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}return this.promisePlay=null,g}catch(t){throw this.promisePlay=null,this._bgLoading&&(this._bgLoading.style.display="none"),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}})();const n=await this.promisePlay;return this.playCallbackInfo=JSON.parse(JSON.stringify(n)),this._recordedStates.videoPlaying=!0,n}async resume(){this._assertOpen(),this._video&&(await this._video.play(),this._recordedStates.videoPlaying=!0),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const t=[this.UIElement];for(let e=0;e','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&e.classList.contains("dce-opt-gotResolution")?this._optGotRsl=e:!this._btnClose&&e.classList.contains("dce-btn-close")?this._btnClose=e:!this._selMinLtr&&e.classList.contains("dlr-sel-minletter")?(this._selMinLtr=e,this._selMinLtr.options.length||(this._selMinLtr.innerHTML=[this._optGotMinLtr?"":'','','','','','','','','','',''].join(""),this._optGotMinLtr=this._optGotMinLtr||this._selMinLtr.options[0])):!this._optGotMinLtr&&e.classList.contains("dlr-opt-gotMinLtr")&&(this._optGotMinLtr=e);if(this.extraBindings&&this.extraBindings.length)for(let i of this.extraBindings)try{i(e)}catch(t){}}if(!this._video)throw this._unbindUI(),Error(`Can not find the video container element with class '${this.containerClassName}'`);this.singleFrameMode||this.videoSrc?(this.singleFrameMode&&(this._elContainer&&(this._elContainer.addEventListener("click",this._clickIptSingleFrameMode),this._elContainer.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._elContainer&&(["Android","HarmonyOS"].includes(P.OS)?(this._elContainer.addEventListener("touchend",this._tapDoFocus),this._elContainer.addEventListener("touchmove",this._touchMoveEvent)):this._elContainer.addEventListener("click",this._tapDoFocus)),this._selCam&&(this._selCam.style.display="block",this._selCam.addEventListener("change",this._onCameraSelChange)),this._selRsl&&(this._selRsl.style.display="block",this._selRsl.addEventListener("change",this._onResolutionSelChange)),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._bgLoading&&(this._bgLoading.style.display="block")),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&(this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{for(let e of t)e.target===this._elContainer&&this._updateLayers()}))),this._elContainer&&this._resizeObserver.observe(this._elContainer)),window.addEventListener("resize",this._updateLayers)}_unbindUI(){this.singleFrameMode?(this._elContainer&&(this._elContainer.removeEventListener("click",this._clickIptSingleFrameMode),this._elContainer.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._elContainer&&(this._elContainer.removeEventListener("click",this._tapDoFocus),this._elContainer.removeEventListener("touchend",this._tapDoFocus),this._elContainer.removeEventListener("touchmove",this._touchMoveEvent)),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._drawingLayersManager.setVisible(!1),this._hideOriginalImageCvs(),this._videoContainer&&this._videoContainer.remove(),this._video=null,this._videoContainer=null,this._elContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._updateLayers)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}async open(t){this.UIElement||await this.setUIElement(et.defaultUIElementURL),this._bindUI(),t&&this.appendAndShowUI();let e=await this.play();this.bOpen=!0,this._focusParameters.fds=null,this._focusParameters.kTimeout=void 0,this._focusSupported=!0,this._tapFocusEnabled&&!this.singleFrameMode&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,this._focusParameters.fds||(this._focusSupported=!1,this._tapFocusEnabled=!1));const i=this.mapCameraEvents.get("cameraopen");for(let t of i){if(!t)continue;const i=JSON.parse(JSON.stringify(e));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[i])}),0)}return e}close(t){if(!this._video)return;this.stop(),this._hideOriginalImage(!1),this.hideTip(),this._unbindUI(),t&&this.hideUI(),this.stopFetchingLoop(),this.bOpen=!1;const e=this.mapCameraEvents.get("cameraclose");for(let t of e){if(!t)continue;const e={width:0,height:0,deviceId:null};setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}stop(){this._video&&this._video.srcObject&&(this._video.srcObject.getTracks().forEach((t=>{t.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0,this._reusedCvs&&this._reusedCvs.ctx2d&&this._reusedCvs.ctx2d.clearRect(0,0,this._reusedCvs.width,this._reusedCvs.height),this.forceLoseContext()}async getAllCameras(t=!0){let e=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));if(t&&e&&e.length&&!e[0].deviceId){let t=await navigator.mediaDevices.getUserMedia({video:!0});e=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}const i=[],r=[];if(this._allCameras)for(let t of this._allCameras)t._checked&&r.push(t);for(let t=0;t{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}if(r!==n.width||s!==n.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const t=this.mapCameraEvents.get("resolutionchange");for(let e of t){if(!e)continue;const t=JSON.parse(JSON.stringify(n));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return n}getResolution(){if(this._bOpen)return[this._video.videoWidth,this._video.videoHeight];{let t=0,e=0;const i=this.videoSettings.video.width,r=this.videoSettings.video.height;return i&&(t=i.exact||i.ideal||i),r&&(e=r.exact||r.ideal||r),[t,e]}}async setResolution(t,e){let i,r;if(t instanceof Array?(i=t[0],r=t[1]):(i=t,r=e),this.videoSettings.video.width={ideal:i},this.videoSettings.video.height={ideal:r},!this._bOpen||this._video.paused)return null;const s=this._video.videoWidth,n=this._video.videoHeight,o=await this.play(null,i,r);if(s!==o.width||n!==o.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const t=this.mapCameraEvents.get("resolutionchange");for(let e of t){if(!e)continue;const t=JSON.parse(JSON.stringify(o));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return o}async getResolutions(t){let e="";const i=(t,e)=>{const i=this._mapCameraResolutions.get(t);if(!i||!i.length)return!1;for(let t of i)if(t[0]===e.width&&t[1]===e.height)return!0;return!1},r=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let s=null;try{s=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!s)return null;const n=s.getVideoTracks();let o=null;try{const t=n[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=s,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return n.forEach((t=>{t.stop()})),o};if(!this._bOpen){const s=this.videoSettings.video.deviceId;if(!s)return null;if(e=s.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:s.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!e)return null;let n=this._mapCameraResolutions.get(e);if(n&&!t)return this._mapCameraResolutions.get(e);this._mapCameraResolutions.set(e,[]),n=this._mapCameraResolutions.get(e);for(let t of this._predefinedResolutions){const s=await r(e,t.width,t.height);s&&!i(e,s)&&n.push([s.width,s.height])}return n}if(this._currentCamera){e=this._currentCamera.deviceId;let r=this._mapCameraResolutions.get(e);if(r&&!t)return this._mapCameraResolutions.get(e);this._mapCameraResolutions.set(e,[]),r=this._mapCameraResolutions.get(e);const s=this.getConstraints();for(let t of this._predefinedResolutions){await this._videoTrack.applyConstraints({width:{ideal:t.width},height:{ideal:t.height}});const s=this._videoTrack.getSettings(),n={width:s.width,height:s.height};i(e,n)||r.push([n.width,n.height])}return await this._videoTrack.applyConstraints(s),r}return null}on(t,e){if(!e)return;const i=this.mapCameraEvents.get(t.toLowerCase());if(!i)throw new Error(`Event '${t}' does not exist.`);i.includes(e)||i.push(e)}off(t,e){const i=this.mapCameraEvents.get(t.toLowerCase());if(!i)throw new Error(`Event '${t}' does not exist.`);const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){if(t){if("string"==typeof t){const e=this.mapCameraEvents.get(t);e&&(e.length=0)}}else for(let t of this.mapCameraEvents.values())t&&(t.length=0)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(t){if(this.videoSettings=JSON.parse(JSON.stringify(t)),this._lastDeviceId=null,this._bOpen)return this.play()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return await this._videoTrack.applyConstraints(t)}async turnOnTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}async turnOffTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}async setColorTemperature(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let e=this.getCapabilities().colorTemperature;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),await this._videoTrack.applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]})}getColorTemperature(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let e=this.getCapabilities().exposureCompensation;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),await this._videoTrack.applyConstraints({advanced:[{exposureCompensation:t}]})}getExposureCompensation(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setHardwareScale()' is unavailable in singleFrameMode.");if(t<1)throw new RangeError("Invalid value.");if(!this._videoTrack)return;const e=this.getCapabilities().zoom;if(!e)throw new Error("Not supported.");return te.max&&(t=e.max),t=tt(t,e.min,e.step,e.max),await this._videoTrack.applyConstraints({advanced:[{zoom:t}]}),t}_getHardwareScale(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(t,e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setSoftwareScale()' is unavailable in singleFrameMode.");if(t<1)throw new RangeError("Invalid value.");e&&this._setScaleCenter(e),this._softwareScale=t,this._scaleVideo(t,e)}_getSoftwareScale(){return this._softwareScale}_setScaleCenter(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setScaleCenter()' is unavailable in singleFrameMode.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid center.");const e=this._video.videoWidth,i=this._video.videoHeight;let r=0,s=0;if(t.x.endsWith("px"))r=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.x)/100*e}if(t.y.endsWith("px"))s=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");s=parseFloat(t.y)/100*i}if(NaN==r||NaN==s)throw new Error("Invalid scale center.");this._scaleCenter={x:r,y:s}}_resetScaleCenter(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_resetScaleCenter()' is unavailable in singleFrameMode.");const t=this._video.videoWidth,e=this._video.videoHeight;this._scaleCenter={x:t/2,y:e/2}}_isVideoCenter(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_isVideoCenter()' is unavailable in singleFrameMode.");return t&&t.x==this._video.videoWidth/2&&t.y==this._video.videoHeight/2}async _setZoom(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(t<1)throw new RangeError("Invalid value.");this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const e=await this._setHardwareScale(t);let i=this._getHardwareScale();1==i&&1!=e&&(i=e),t>i?this._setSoftwareScale(t/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(t)}catch(e){if("Not supported."!==(e.message||e))throw e;this._setSoftwareScale(t)}}async setZoom(t){if("number"!=typeof t&&"object"!=typeof t)throw new TypeError("Illegal type of argument.");if("number"==typeof t)return this._setZoom(t);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(t){if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid value.");t.centerPoint?this._setScaleCenter(t.centerPoint):this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const e=await this._setHardwareScale(t.factor);let i=this._getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this._setSoftwareScale(t.factor/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(t.factor)}catch(e){if("Not supported."!==(e.message||e))throw e;this._setSoftwareScale(t.factor)}}}getZoom(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?{factor:this._getHardwareScale()*this._softwareScale}:null}async resetZoom(){await this.setZoom({factor:1})}async setFrameRate(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let e=this.getCapabilities().frameRate;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),await this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:t})}getFrameRate(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(t,e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if("string"!=typeof t)throw Error("Invalid focus mode.");t=t.toLowerCase();const i=this.getCapabilities().focusMode,r=this.getCapabilities().focusDistance;if(!i)throw Error("Not supported.");if(!i.includes(t))throw Error("Unsupported mode.");if(e>=0){if(!r)throw Error("Manual focus unsupported.");return er.max&&(e=r.max),e=tt(e,r.min,r.step,r.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:t,focusDistance:e}]})}return await this._videoTrack.applyConstraints({advanced:[{focusMode:t}]})}async setFocus(t,e){if("string"==typeof t)return this._setFocus(t,e);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if(!t)return;const i=this.getCapabilities(),r=i.focusMode,s=i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw Error("Invalid focus mode.");const n=t.mode.toLowerCase();if(!r.includes(n))throw Error("Unsupported focus mode.");if("manual"!==n)return this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:n}]});if(!s)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let e=t.distance;return es.max&&(e=s.max),e=tt(e,s.min,s.step,s.max),this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:n,focusDistance:e}]})}if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this._video.videoWidth,e=this._video.videoHeight;i||(i=2*Math.round(Math.min(t,e)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t,e)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters._focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await this._setLocalFocus(e,i,r)}}getFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const t=this._videoTrack.getSettings().focusMode;return t?"continuous"===t?{mode:t}:{mode:t,distance:this._videoTrack.getSettings().focusDistance}:null}getFocusSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const t=this._videoTrack.getSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters._focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters._focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async _setFocusAndGetContract(t,e){const i=t=>{if(!this._bOpen||!this._videoTrack||this.video.paused||t.focusTaskId!=this._focusParameters.curFocusTaskId){this._bOpen&&this._videoTrack&&!this.video.paused||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;e=tt(e,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:"manual",focusDistance:e}]}),i(t),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/e),Math.abs(1/this._focusParameters.fds.max-1/e))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/e)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=e,await new Promise((t=>{setTimeout(t,r)})),i(t);let s=t.focusL-t.focusW/2,n=t.focusT-t.focusH/2,o=t.focusW,a=t.focusH;if(s>=this.video.videoWidth||n>=this.video.videoHeight)throw new Error("Invalid area.");s+o>this.video.videoWidth&&(o=this.video.videoWidth-s),n+a>this.video.videoHeight&&(a=this.video.videoHeight-n);const h=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:s,sy:n,sWidth:o,sHeight:a,dWidth:o,dHeight:a},null,{pixelFormat:$.RGBA});if(!h)return this._setFocusAndGetContract(t,e);const l=h.data;let c=0;for(let t=0,e=l.length-8;to&&oc)return await this._doFocusDetail(t,n,o,r,s,l,c)}else{let a=await this._setFocusAndGetContract(t,l);if(o>a)return await this._doFocusDetail(t,n,o,r,s,l,a);if(o==a)return await this._doFocusDetail(t,n,o,l,a);let c=await this._setFocusAndGetContract(t,h);if(c>o&&o{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=tt(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=tt(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=tt(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await this._setFocusAndGetContract(t,n),a=await this._setFocusAndGetContract(t,s),h=await this._setFocusAndGetContract(t,r);if(a>h&&ho&&a>o){let e=await this._setFocusAndGetContract(t,i);const s=await this._doFocusDetail(t,r,h,i,e,n,o);return this._focusParameters.isDoingFocus=0,s}if(a==h&&hh){const e=await this._doFocusDetail(t,r,h,n,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,s)}async enableTapToFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'enableTapToFocus()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error("Video is not playing.");if(!this._focusSupported)throw new Error("Tapping to focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,this._tapFocusEnabled=!1,new Error("Tapping to focus unsupported.");this._tapFocusEnabled=!0}disableTapToFocus(){this._tapFocusEnabled=!1}isTapToFocusEnabled(){return this._tapFocusEnabled}_updateVideoContainerStyle(){if(!this._video)return;if(this.singleFrameMode)return;const t=this._getSoftwareScale(),e=this._videoContainer;if("contain"===this.videoFit&&t>1){const t=this._video.videoWidth,i=this._video.videoHeight,r=window.getComputedStyle(this._elContainer),s=parseFloat(r.width),n=parseFloat(r.height),o=t/i;if(s/na?o/(i/t):n/(r/t));const c=l*(1-1/t)*(i/2-this._scaleCenter.x),u=l*(1-1/t)*(r/2-this._scaleCenter.y);this._video.style.transform=`translate(${c}px, ${u}px) scale(${t})`}this._updateVideoContainerStyle()}}getFrameSize(t,e,i,r){if(!t||!e)return null;let s,n,o,a,h=t,l=e;const c={regionLeft:0,regionTop:0,regionRight:h,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*h/100,c.regionTop=i.regionTop*l/100,c.regionRight=i.regionRight*h/100,c.regionBottom=i.regionBottom*l/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),s=Math.round(c.regionLeft),n=Math.round(c.regionTop),h=Math.round(c.regionRight-c.regionLeft),l=Math.round(c.regionBottom-c.regionTop)):(s=0,n=0,h=Math.round(h),l=Math.round(l));const u=Math.max(h,l);if(r&&r>0&&u>r){const t=r/u;h>l?(o=r,a=Math.round(l*t)):(o=Math.round(h*t),a=r)}else o=h,a=l;return o<=0||a<=0?null:{sx:s,sy:n,sWidth:h,sHeight:l,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoData()}getImage(){return this.getFrame()}_drawImage(t,e,i,r,s,n,o){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!i||!r)return null;if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;s&&(s.sx&&(a=Math.round(s.sx)),s.sy&&(h=Math.round(s.sy)),s.sWidth&&(l=Math.round(s.sWidth)),s.sHeight&&(c=Math.round(s.sHeight)),s.dx&&(u=Math.round(s.dx)),s.dy&&(d=Math.round(s.dy)),s.dWidth&&(f=Math.round(s.dWidth)),s.dHeight&&(g=Math.round(s.dHeight)));let _=$.RGBA;o&&o.pixelFormat&&(_=o.pixelFormat);const p=t;if(o&&o.bUseWebGL){(p.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},s=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},n="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(_)&&(o=_.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[s(t,t.VERTEX_SHADER,n),s(t,t.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},this._webGLBuffers=e(t),this._webGLTexture=i(t),this.shaderPixelFormat=_}const s=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},o=(t,e,i)=>{const r=t.RGBA,s=t.RGBA,n=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,s,n,i)},m=(t,e,n,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),s(t,n.positions,e.attribLocations.vertexPosition),s(t,n.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[$.GREY,$.GREY32].includes(_)?1:0);let p,m,v=Q.translate(Q.identity(),-1,-1);v=Q.scale(v,2,2),v=Q.scale(v,1/t.canvas.width,1/t.canvas.height),p=Q.translate(v,u,d),p=Q.scale(p,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,p),m=Q.translate(Q.identity(),a/i,h/r),m=Q.scale(m,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,m),t.drawArrays(t.TRIANGLES,0,6)};let v;if(o(t,this._webGLTexture,e),m(t,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),n){if(n.lengthe||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=$.RGBA;n&&n.pixelFormat&&(d=n.pixelFormat);let f,g,_,p=this._bWebGLSupported;n&&0==n.bUseWebGL&&(p=!1),p?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),f=this._reusedCvs);try{if(p)if(et._onLog&&et._onLog("DCE: _getImageData() in WebGL."),s)if(d===$.GREY){if(_=new Uint8Array(c*u*4),g=this._drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},_,{pixelFormat:d,bUseWebGL:p}),_=this._transformPixelFormat(_,g.pixelFormat,d),s){if(s.length<_.length)throw new Error("Unexpected size of the 'bufferContainer'.");s.set(_)}}else g=this._drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},s,{pixelFormat:d,bUseWebGL:p}),_=new Uint8Array(s.buffer,0,c*u*4),_=this._transformPixelFormat(_,g.pixelFormat,d);else d===$.GREY?((!this._tempDataContainer||this._tempDataContainer.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");t=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return t}_fetchingLoop(t){if(this.isDisposed&&this.disposed)return;if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();const e=()=>{const t=this.getCurrentRegion();let e=this._getVideoData(null,{region:t});if(!e)return void et._onLog;for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(e);const i=this.mapCameraEvents.get("frameaddedtobuffer");for(let t of i)t&&setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this)}),0)},i=()=>{this.isDisposed&&this.disposed||(this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.isDisposed&&this.disposed||(this._bOpen&&this.isFetchingLoopStarted()?(e(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};t&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(e(),i()):0===this.refreshInterval?e():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1,this._recordedStates.fetchingLoopStart=!1)}getFrameFromBuffer(t){return this._frameQueue&&this._frameQueue.length?t?tt.getId()>=0))}getSelectedDrawingItems(){return this._drawingLayersManager.getSelectedDrawingItems()}createDrawingStyle(t){return this._drawingLayersManager.createDrawingStyle(t)}getDrawingStyle(t){return this._drawingLayersManager.getDrawingStyle(t)}getDrawingStyles(){return this._drawingLayersManager.getDrawingStyles()}updateDrawingStyle(t,e){return this._drawingLayersManager.updateDrawingStyle(t,e)}clearDrawingLayers(){const t=this.getDrawingLayers();for(let e of t)this.deleteDrawingLayer(e.getId())}showTip(t,e,i,r,s=3e3,n=!0){this._assertOpen(),this._tipArgs.x=t,this._tipArgs.y=e,this._tipArgs.width=i,this._tipArgs.autoShowSuggestedTip=!!n,this._drawingLayerOfTip||(this._drawingLayerOfTip=this._createDrawingLayer(-1)),this._tipStyleId||(this._tipStyleId=this.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip.clearDrawingItems();const o=new Z(r||"",t,e,i,this._tipStyleId);o._fabricObject.paddingTop=15,o._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e0&&(this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}_hideTip(){this._drawingLayerOfTip&&(this.deleteDrawingLayer(this._drawingLayerOfTip.getId()),this._drawingLayerOfTip=null,this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId))}hideTip(){this._hideTip(),this._tipArgs.x=null,this._tipArgs.y=null,this._tipArgs.width=null,this._tipArgs.autoShowSuggestedTip=null}updateTipMessage(t){if(!this._drawingLayerOfTip)throw new Error("The Tip is not showing.");this._drawingLayerOfTip.getDrawingItems()[0].setAttribute("text",t),this._drawingLayerOfTip.renderAll(),this._tipArgs.duration>0&&(this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId),this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}suggestTip(t,e){this._tipArgs.autoShowSuggestedTip&&(this._drawingLayerOfTip?this.updateTipMessage(e):void 0!==this._tipArgs.x&&this.showTip(this._tipArgs.x,this._tipArgs.y,this._tipArgs.width,e,this._tipArgs.duration)),this.onTipSuggested&&setTimeout((()=>{this.isDisposed&&this.disposed||this.onTipSuggested.apply(this,[t,e])}),0)}_createControler(){if(this._controler||(this._controler=new q(this)),this._controler)return this._controler}_destroyControler(){this._controler=null}setOriginalImage(t,e,i){if(!t||!e||!i)throw new Error("Invalid arguments");this._originalImageData={imageData:t,width:e,height:i};let r=this._cvsOriginalImage;r||(r=document.createElement("canvas"),r.style.position="absolute",r.style.width="100%",r.style.height="100%",r.style.left="0",r.style.top="0",r.style.backgroundColor="white",r.style.objectFit="contain",this._cvsOriginalImage=r),r.width===e&&r.height===i||(r.width=e,r.height=i);const s=r.getContext("2d");s.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),s.putImageData(new ImageData(t,e,i),0,0)):t instanceof HTMLCanvasElement&&s.drawImage(t,0,0),document.body.contains(r)&&""===r.style.display&&this._updateDrawingLayersSize({width:e,height:i,objectFit:"contain"})}getOriginalImage(){return this._originalImageData?Object.assign({},this._originalImageData):null}async deleteOriginalImage(){await this.hideOriginalImage(),this._cvsOriginalImage&&(this._cvsOriginalImage.remove(),this._cvsOriginalImage=null),this._originalImageData=null}_showOriginalImageCvs(){this._cvsOriginalImage&&"none"==this._cvsOriginalImage.style.display&&(this._cvsOriginalImage.style.display="")}_hideOriginalImageCvs(){this._cvsOriginalImage&&(this._cvsOriginalImage.style.display="none")}showOriginalImage(){if(!this._originalImageData)throw new Error("No original image is set.");const t=this._cvsOriginalImage;if(""===t.style.display&&document.body.contains(t))return;const{width:e,height:i}=this._originalImageData;if(this._updateDrawingLayersSize({width:e,height:i,objectFit:"contain"}),this._bOpen&&(this._video&&!this._video.paused&&this._video.pause(),this._bFetchingLoopStarted&&(this.stopFetchingLoop(),this._recordedStates.fetchingLoopStart=!0),this.ifShowScanRegionMask&&this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this.ifShowScanRegionLaser&&this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none"),this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none"),this._selCam&&(this._selCam.parentElement.style.display="none")),!document.body.contains(t))if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(t);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(t)}this._showOriginalImageCvs()}async _hideOriginalImage(t){this._originalImageData&&this._cvsOriginalImage&&"none"!==this._cvsOriginalImage.style.display&&(this._updateDrawingLayersSize(),this._bOpen&&t&&(this._video&&this._recordedStates.videoPlaying&&await this.play(null,null,null,{notTriggerSingleFrameClick:!0}),this._recordedStates.fetchingLoopStart&&!this.singleFrameMode&&this.startFetchingLoop(),this.ifShowScanRegionMask&&this._cvsScanRegion&&this._recordedStates.maskShow&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this._divScanLight&&this._recordedStates.laserShow&&this.showScanRegionLaser(),this._cvsViewDecorator&&this._recordedStates.decoratorShow&&this.showViewDecorator(),this._scanRegionOverlayContainer&&this._recordedStates.overlayShow&&this.showScanRegionOverlays()),this._selCam&&(this._selCam.parentElement.style.display=""),this._hideOriginalImageCvs())}async hideOriginalImage(){return this._hideOriginalImage(!0)}dispose(t){this.UIElement&&(this._uiOriginalState&&this._uiOriginalState.inDom?this.UIElement.style.display=this._uiOriginalState.display:this.UIElement.style.display="none"),this.clearDrawingLayers(),this.close(),this.forceLoseContext(),this.setViewDecorator(null,null),this._scanRegionOverlayContainer&&this._scanRegionOverlayContainer.remove(),this._arrScanRegionOverlays.length=0,t&&this.UIElement&&this.UIElement.remove(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"isDisposed",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}et._jsVersion="3.3.1",et._jsEditVersion="20230217",et._version="JS "+et._jsVersion+"."+et._jsEditVersion,et.browserInfo=P,et._hasEngineResourceLoaded=!1,et._engineResourcePath=V,et._defaultUIElementURL="@engineResourcePath/dce.ui.html";const it={DT_Arc:class extends U{constructor(t,e,i,r,s,n){super(new R.Circle({left:t,top:e,radius:i,startAngle:r,endAngle:s}),n),this._mediaType="arc"}},DT_Polygon:X,DT_Rect:class extends U{constructor(t,e,i,r,s){super(new R.Rect({left:t,top:e,width:i,height:r}),s)}},DT_Image:class extends U{constructor(t,e,i,r){super(new R.Image(t,{left:e,top:i}),r),this.image=t}_extendSet(t,e){if("image"===t){if(e instanceof HTMLImageElement)return this._fabricObject.setElement(e),this.image=e,!0;if(e instanceof HTMLCanvasElement){const t=new Image;return t.src=e.toDataURL(),this._fabricObject.setElement(t),this.image=e,!0}throw new Error("Unsupported value.")}}_extendGet(t){if("image"===t)return this.image}},DT_Text:Z,DT_Line:class extends X{constructor(t,e,i){super([t,e],i),this._mediaType="line"}_extendSet(t,e){if("startPoint"===t||"endPoint"===t){e="startPoint"===t?[e,this.get("endPoint")]:[this.get("startPoint"),e];const i=this._fabricObject;if(i.group){const t=i.group;i.points=e.map((e=>({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new R.Control({positionHandler:G,actionHandler:Y(i>0?i-1:r,H),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}_extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,s=t.y-i.pathOffset.y;const n=R.util.transformPoint({x:r,y:s},i.calcTransformMatrix());e.push({x:n.x,y:n.y})}return"startPoint"===t?e[0]:e[1]}}},DT_Group:class extends U{constructor(t){super(new R.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.styleSelector="selected";const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.styleSelector="default";const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)}))}getChildItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}addChildItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}};function rt(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function st(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function nt(t,e,i,r){let s=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),n=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((s^n)>=0&&0!==s&&0!==n)&&(s=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),n=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),!((s^n)>=0&&0!==s&&0!==n))}class ot extends x{constructor(){super(),this._barcodeFillStyle="rgba(254,180,32,0.3)",this._barcodeStrokeStyle="rgba(254,180,32,0.9)",this._barcodeLineWidth=1,this._barcodeFillStyleBeforeVerification="rgba(248,252,0,0.2)",this._barcodeStrokeStyleBeforeVerification="transparent",this._barcodeLineWidthBeforeVerification=2,this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${et.getVersion()})`}static _fireHTTPSWarnning(){ot.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{ot.onWarning&&ot.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return et.testCameraAccess()}_fireResolutionWarning(){if(!this.singleFrameMode&&this.onWarning&&this.dce.isOpen()){const t=this.dce.getConstraints();t&&t.width<1280&&t.height<720&&setTimeout((()=>{this.onWarning&&this.onWarning({id:3,message:"Camera resolution too low, please use a higher resolution (720P or better)."})}),0)}}getUIElement(){return this.dce.getUIElement()}async setUIElement(t){await this.dce.setUIElement(t)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(t){this.dce.singleFrameMode=t,t&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let t=await this.getScanSettings();t.oneDTrustFrameCount=1,await this.updateScanSettings(t)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(t){this.onUniqueRead=t}get video(){return this.dce&&this.dce.video}set videoSrc(t){this.dce&&(this.dce.videoSrc=t)}get videoSrc(){return this.dce&&this.dce.videoSrc}set onTipSuggested(t){this.dce&&(this.dce.onTipSuggested=t)}get onTipSuggested(){return this.dce&&this.dce.onTipSuggested}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set barcodeFillStyle(t){this._barcodeFillStyle=t,this.dce&&this.dce.updateDrawingStyle(3,{fillStyle:t})}get barcodeFillStyle(){return this._barcodeFillStyle}set barcodeStrokeStyle(t){this._barcodeStrokeStyle=t,this.dce&&this.dce.updateDrawingStyle(3,{strokeStyle:t})}get barcodeStrokeStyle(){return this._barcodeStrokeStyle}set barcodeLineWidth(t){this._barcodeLineWidth=t,this.dce&&this.dce.updateDrawingStyle(3,{lineWidth:t})}get barcodeLineWidth(){return this._barcodeLineWidth}set barcodeFillStyleBeforeVerification(t){this._barcodeFillStyleBeforeVerification=t,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{fillStyle:t})}get barcodeFillStyleBeforeVerification(){return this._barcodeFillStyleBeforeVerification}set barcodeStrokeStyleBeforeVerification(t){this._barcodeStrokeStyleBeforeVerification=t,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{strokeStyle:t})}get barcodeStrokeStyleBeforeVerification(){return this._barcodeStrokeStyleBeforeVerification}set barcodeLineWidthBeforeVerification(t){this._barcodeLineWidthBeforeVerification=t,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{lineWidth:t})}get barcodeLineWidthBeforeVerification(){return this._barcodeLineWidthBeforeVerification}set regionMaskFillStyle(t){this.dce.setScanRegionMaskStyle({fillStyle:t})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(t){this.dce.setScanRegionMaskStyle({strokeStyle:t})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(t){this.dce.setScanRegionMaskStyle({lineWidth:t})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(t){this._region=t,this.dce&&(t?t instanceof Array||this.dce.setScanRegion(t):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(t){this._ifSaveOriginalImageInACanvas=t,this.dce.framePixelFormat=t?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(x._onLog&&x._onLog("createDCEInstance()"),et.defaultUIElementURL=null,this.dce=await et.createInstance(),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=it,["iPhone","iPad","Android","HarmonyOS"].includes(x.browserInfo.OS)||this.dce.setResolution(1920,1080),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"}),this.barcodeLineWidth=this._barcodeLineWidth,this.dce.on("cameraChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async t=>{if(!t)return;if(!t.data)return;let e;this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:i,sx:r,sy:s,width:n,height:o,stride:a,pixelFormat:h,timeStamp:l,_sWidth:c,_sHeight:u}=t,d={timeStamp:l};if("grey"===h)e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_GrayScaled,0,d);else if("rgba"===h)e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_ARGB_8888,0,d)}if(await this.clearMapDecodeRecord(),x.recalculateResultLocation(e,r,s,c,u,n,o),this._drawResults(e),this.onFrameRead&&this.isOpen()&&!this._bPauseScan){let t=this._cloneDecodeResults(e);this.onFrameRead(t)}if(this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let t of e)this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))})))}set maxCvsSideLength(t){this._maxCvsSideLength=t,this.dce.maxCvsSideLength=t}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(t){let e=new ot;e._instanceID=await ot.createInstanceInWorker(!0),await e.createDCEInstance(),"string"==typeof t&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return await e.dce.setUIElement(ot.defaultUIElementURL),e.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),ot._fireHTTPSWarnning(),e.singleFrameMode||await e.updateRuntimeSettings("single"),e}async decodeCurrentFrame(t){this._assertOpen();let e=null;t&&t.region&&(e=t.region);const i=this.dce._getVideoData(null,{region:e});return this._decode_DCEFrame(i)}async updateRuntimeSettings(t){let e;if("string"==typeof t)if("speed"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=0,e.localizationModes=[2,0,0,0,0,0,0,0],e.barcodeZoneMinDistanceToImageBorders=9}else if("balance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=512,e.deblurLevel=3,e.localizationModes=[2,16,0,0,0,0,0,0],e.barcodeZoneMinDistanceToImageBorders=9,e.timeout=1e5}else if("coverage"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=512,e.deblurLevel=5,e.scaleDownThreshold=1e5,e.localizationModes=[2,16,4,8,0,0,0,0],e.barcodeZoneMinDistanceToImageBorders=9,e.timeout=1e5}else if("single"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region)}else if("dense"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=0,e.deblurLevel=7,e.scaleDownThreshold=1e5,e.localizationModes=[2,8,0,0,0,0,0,0],e.minResultConfidence=0,e.barcodeZoneMinDistanceToImageBorders=9,e.timeout=1e5}else if("distance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=0,e.scaleDownThreshold=1e5,e.localizationModes=[2,8,0,0,0,0,0,0],e.barcodeZoneMinDistanceToImageBorders=9,e.timeout=1e5}else e=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(e=JSON.parse(JSON.stringify(t)),e.region instanceof Array){let i=t.region;[i.regionLeft,i.regionTop,i.regionLeft,i.regionBottom,i.regionMeasuredByPercentage].some((t=>void 0!==t))&&(e.region={regionLeft:i.regionLeft||0,regionTop:i.regionTop||0,regionRight:i.regionRight||0,regionBottom:i.regionBottom||0,regionMeasuredByPercentage:i.regionMeasuredByPercentage||0})}}if(!x._bUseFullFeature){if(0!=(e.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.BF_DATAMATRIX))||0!=e.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=e.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let t=e.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(t)):this.userDefinedRegion=null,t instanceof Array)if(t.length){for(let e=0;e{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.updateReturn)}catch(t){i(t)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),x._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(e)}})})),"string"==typeof t&&["speed","balance","coverage","dense","distance"].includes(t)&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","1"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","0"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","0"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(t){this.dce.off("played",this._onPlayed),this._onPlayed=t,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(t){const e=await this.dce.selectCamera(t);return this._fireResolutionWarning(),e}getResolution(){return this.dce.getResolution()}async setResolution(t,e){const i=await this.dce.setResolution(t,e);return this._fireResolutionWarning(),i}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(t){return this.dce.updateVideoSettings(t)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(t){return this.dce&&this.dce.setVideoFit(t)}set ifShowScanRegionMask(t){this.dce&&(this.dce.ifShowScanRegionMask=t)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}set ifSaveLastUsedCamera(t){this.dce&&(this.dce.ifSaveLastUsedCamera=t)}get ifSaveLastUsedCamera(){return this.dce&&this.dce.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){this.dce&&(this.dce.ifSkipCameraInspection=t)}get ifSkipCameraInspection(){return this.dce&&this.dce.ifSkipCameraInspection}stop(){this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.dce.stop(),this.dce.ifShowScanRegionLaser=!1,this.dce.hideViewDecorator(),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this.dce.pause()}async play(t,e,i){this.dce.ifShowScanRegionLaser=!0;const r=await this.dce.play(t,e,i);return this._fireResolutionWarning(),r}pauseScan(t){this._assertOpen(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),t&&t.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(t){return this.dce.applyConstraints(t)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(t){return this.dce.setColorTemperature(t)}getColorTemperature(){return this.dce.getColorTemperature()}async setExposureCompensation(t){return this.dce.setExposureCompensation(t)}getExposureCompensation(){return this.dce.getExposureCompensation()}async setZoom(t){return this.dce.setZoom(t)}getZoomSettings(){return this.dce.getZoomSettings()}resetZoom(){return this.dce.resetZoom()}async setFrameRate(t){return this.dce.setFrameRate(t)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(t,e){return this.dce.setFocus(t,e)}getFocus(){return this.dce.getFocus()}getFocusSettings(){return this.dce.getFocusSettings()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(!this.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return x._onLog&&x._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));x._onLog&&x._onLog("======= once read ======="),x._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return x._onLog&&x._onLog("Get invalid frame."),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{t._bUseWebGL||"grey"!==t.pixelFormat||(this.dce.framePixelFormat="rgba");let e=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:i,sx:r,sy:s,width:n,height:o,stride:a,pixelFormat:h,timeStamp:l,_sWidth:c,_sHeight:u}=t,d={timeStamp:l};if("grey"===h)e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_GrayScaled,0,d);else if("rgba"===h)e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_ARGB_8888,0,d)}if(x.recalculateResultLocation(e,r,s,c,u,n,o),0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(e),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration)),this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan&&(this.autoZoom||this.autoFocus||this.autoSuggestTip))if(e.length)this.autoZoomInFrameArray.length=0,this.autoZoomOutFrameCount=0,this.frameArrayInIdealZoom.length=0,this.suggestTipFrameArray.length=0,this.autoZoom&&this.autoFocus&&(this.nextActionInIdealZoom="focus"),this.autoFocusFrameArray.length=0,this.noIntermediateResultsCount=0;else{const t=await this.getIntermediateResults(),e=(t,e,i,r,s,n,o)=>{let a=n/r,h=o/s;t.x1=t.x1/a+e,t.x2=t.x2/a+e,t.x3=t.x3/a+e,t.x4=t.x4/a+e,t.y1=t.y1/h+i,t.y2=t.y2/h+i,t.y3=t.y3/h+i,t.y4=t.y4/h+i},i=t=>{if(!t)return null;const i={};let a,h,l,d,f;{const t=this.video.videoWidth*(1-this.autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+this.autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-this.autoZoomDetectionArea)/2,n=s,o=this.video.videoHeight*(1+this.autoZoomDetectionArea)/2;f={x1:t,x2:e,x3:i,x4:r,y1:s,y2:n,y3:o,y4:o}}const g=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const s=t.length;if(s<=2)return!1;for(let n=0;n0!=st(a.y-i)>0&&st(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}([{x:e.x1,y:e.y1},{x:e.x2,y:e.y2},{x:e.x3,y:e.y3},{x:e.x4,y:e.y4}],t.x,t.y)},r=(t,e)=>!!(nt([t[0],t[1]],[t[2],t[3]],[e.x1,e.y1],[e.x2,e.y2])||nt([t[0],t[1]],[t[2],t[3]],[e.x2,e.y2],[e.x3,e.y3])||nt([t[0],t[1]],[t[2],t[3]],[e.x3,e.y3],[e.x4,e.y4])||nt([t[0],t[1]],[t[2],t[3]],[e.x4,e.y4],[e.x1,e.y1]));return!!(i({x:t.x1,y:t.y1},e)||i({x:t.x2,y:t.y2},e)||i({x:t.x3,y:t.y3},e)||i({x:t.x4,y:t.y4},e))||(!!(i({x:e.x1,y:e.y1},t)||i({x:e.x2,y:e.y2},t)||i({x:e.x3,y:e.y3},t)||i({x:e.x4,y:e.y4},t))||!!(r([e.x1,e.y1,e.x2,e.y2],t)||r([e.x2,e.y2,e.x3,e.y3],t)||r([e.x3,e.y3,e.x4,e.y4],t)||r([e.x4,e.y4,e.x1,e.y1],t)))},_=[];for(let i of t){if(i.resultType!==S.IRT_TYPED_BARCODE_ZONE)continue;const t=i.scaleDownRatio;for(let a of i.results){if(!a)continue;const i={x1:a.x1=a.x1*t,x2:a.x2=a.x2*t,x3:a.x3=a.x3*t,x4:a.x4=a.x4*t,y1:a.y1=a.y1*t,y2:a.y2=a.y2*t,y3:a.y4=a.y3*t,y4:a.y4=a.y4*t};e(i,r,s,c,u,n,o),g(f,i)&&_.push(a)}}const p=(t=>{if(!t||!t.length)return null;const e=t=>{const e=(t.x1+t.x2+t.x3+t.x4)/4,i=(t.y1+t.y2+t.y3+t.y4)/4;return(e-n/2)*(e-n/2)+(i-o/2)*(i-o/2)};let i,r=t.filter((t=>t.barcodeFormat==y.BF_QR_CODE||t.barcodeFormat==y.BF_DATAMATRIX));if(r.length||(r=t.filter((t=>t.barcodeFormat==y.BF_ONED)),r.length||(r=t)),!r.length)return null;i=r[0];let s=e(i);if(1!=r.length)for(let t=1;t1.1*i.confidence?(i=r[t],s=n):r[t].confidence>.9*i.confidence&&n!0===t)).length>=this.suggestTipFrameLimit[1]){this.suggestTipFrameArray.length=0;const t=a.x3-a.x1,e=a.y3-a.y1;a.result.moduleSizee?t>n*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):t>.6*n&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."):t<=e&&(e>o*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):e>.6*o&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."))}if(this.autoZoom){const t=this.autoZoomIdealArea[1];let i=(1-this.autoZoomTargetBorder)/2;const h=a.x1/c,l=(c-a.x3)/c,d=a.y1/u,f=(u-a.y3)/u;if(h>t&&l>t&&d>t&&f>t&&a.result.moduleSize{}))),this.autoZoomInFrameArray.filter((t=>!0===t)).length>=this.autoZoomInFrameLimit[1]){this.autoZoomInFrameArray.length=0;const t=[(.5-i)/(.5-h),(.5-i)/(.5-l),(.5-i)/(.5-d),(.5-i)/(.5-f)].filter((t=>t>0)),e=Math.min(...t,this.autoZoomInIdealModuleSize/a.result.moduleSize),r=this.dce.getZoomSettings().factor;let s=Math.max(Math.pow(r*e,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);s=Math.min(s,e);const n=r*s;await this.setZoom({factor:n}),this.dce.clearFrameBuffer()}}else if(this.autoZoomInFrameArray.length=0,this.frameArrayInIdealZoom.push(!0),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.frameArrayInIdealZoom.filter((t=>!0===t)).length>=this.frameLimitInIdealZoom[1])if(this.frameArrayInIdealZoom.length=0,"focus"===this.nextActionInIdealZoom&&this.autoFocus){e(a,r,s,c,u,n,o);try{await this.setFocus({mode:"manual",area:{centerPoint:{x:(a.x1+a.x3)/2+"px",y:(a.y1+a.y3)/2+"px"},width:a.x3-a.x1+"px",height:a.y3-a.y1+"px"}})}catch(t){}this.dce.clearFrameBuffer(),this.nextActionInIdealZoom="zoomOut"}else{if("zoomOut"!==this.nextActionInIdealZoom&&this.autoFocus)throw new Error("Invalid action.");if(this.enableZoomOutInIdealZoom){i=this.autoZoomIdealArea[1]+this.autoZoomOutStepRate_2;const t=[(.5-i)/(.5-h),(.5-i)/(.5-l),(.5-i)/(.5-d),(.5-i)/(.5-f)].filter((t=>t>0));let e=Math.min(...t)*this.dce.getZoomSettings().factor;await this.setZoom({factor:e}),this.dce.clearFrameBuffer(),this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((t=>{})))}}}else if(this.autoFocus&&(this.autoFocusFrameArray.push(!0),this.autoFocusFrameArray.splice(0,this.autoFocusFrameArray.length-this.autoFocusFrameLimit[0]),this.autoFocusFrameArray.filter((t=>!0===t)).length>=this.autoFocusFrameLimit[1])){this.autoFocusFrameArray.length=0;try{e(a,r,s,c,u,n,o),await this.setFocus({mode:"manual",area:{centerPoint:{x:(a.x1+a.x3)/2+"px",y:(a.y1+a.y3)/2+"px"},width:a.x3-a.x1+"px",height:a.y3-a.y1+"px"}})}catch(t){}this.dce.clearFrameBuffer()}}else if(this.noIntermediateResultsCount++,this.suggestTipFrameArray.push(!1),this.autoZoom){if(this.autoZoomInFrameArray.push(!1),this.autoZoomInFrameArray.splice(0,this.autoZoomInFrameArray.length-this.autoZoomInFrameLimit[0]),this.autoZoomOutFrameCount++,this.frameArrayInIdealZoom.push(!1),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.autoZoomOutFrameCount>=this.autoZoomOutFrameLimit){this.autoZoomOutFrameCount=0;const t=this.getZoomSettings().factor;if(t>this.autoZoomOutMinValue){const e=Math.max((t-1)*this.autoZoomOutStepRate,this.autoZoomOutMinStep),i=Math.max(t-e,this.autoZoomOutMinValue);await this.setZoom({factor:i}),this.dce.clearFrameBuffer()}}this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((t=>{})))}else this.autoFocus&&(this.autoFocusFrameArray.length=0,this.setFocus({mode:"continuous"}).catch((t=>{})))}return e})().then((t=>{if(x._onLog&&x._onLog(t),this.captureAndDecodeInParallel){let t=this.array_decodeFrameTimeCost,e=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;const r=()=>{let r=0;if(this.region instanceof Array){let s=0,n=0;s=i+1>=this.region.length?0:i+1,n=s+1>=this.region.length?0:s+1,r=t[s]&&t[s].length&&e[n]&&e[n].length?Math.min(...t[s])-Math.max(...e[n]):0}else if(e&&e.length){let i=Math.min(...t),s=Math.max(...e);i&&s&&(r=i-s)}else r=0;return r>0?r:0};(()=>{if(this.region instanceof Array){for(t[i]&&t[i]instanceof Array||(t[i]=[]);t[i].length>=5;)t[i].shift();t[i].push(this._lastInnerDecodeDuration)}else{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=r()+this.intervalTime,x._onLog&&x._onLog("Next fetching frame loop interval: "+this._intervalGetVideoFrame)}if(this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&t.length){let e=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?e=t.some((t=>t.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(e=t.some((t=>0==t.resultState))),e&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&t.length){let e=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?e=t.some((t=>t.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(e=t.some((t=>0==t.resultState))),e)try{navigator.vibrate(this.vibrateDuration)}catch(t){console.warn("Vibration not allowed. User interaction required: "+(t.message||t))}}if(this.onFrameRead){t=t.filter((t=>t.resultState>=0));const e=this._cloneDecodeResults(t);this.onFrameRead(e)}if(this.onUniqueRead){t=t.filter((t=>0==t.resultState));const e=this._cloneDecodeResults(t);for(let t of e)this.onUniqueRead(t.barcodeText,t)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()}))}_getVideoFrame(){if(!this.dce)return null;let t;if(this.captureAndDecodeInParallel){x._onLog&&x._onLog("Get frame in parallel.");let e=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;t=this.dce.getFrameFromBuffer();const i=t=>{if(!t)return;let e=t.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(e)};i(t)}else x._onLog&&x._onLog("Get frame in serial."),this.dce.stopFetchingLoop(),t=this.dce.getFrame();return t}async open(){this._bindUI();const t=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),t}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const t=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),t}close(){this.dce.close(),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}async show(){this._bindUI();const t=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),t}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const t=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),t}hide(){this.dce.close(!0),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}showTip(t,e,i,r,s=3e3,n=!0){this.dce&&this.dce.showTip(t,e,i,r,s,n)}hideTip(){this.dce&&this.dce.hideTip()}updateTipMessage(t){this.dce&&this.dce.updateTipMessage(t)}async enableTapToFocus(){this.dce&&this.dce.enableTapToFocus()}disableTapToFocus(){this.dce&&this.dce.disableTapToFocus()}isTapToFocusEnabled(){return this.dce.isTapToFocusEnabled()}destroyContext(){this.close(),this.dce&&this.dce.dispose(!1),this.bDestroyed||super.destroyContext()}}var at,ht,lt,ct,ut,dt,ft,gt,_t,pt,mt,vt,yt,St,Ct,wt,bt,xt,Tt,It,Et,Ot,Rt,At,Dt,Mt;!function(t){t[t.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",t[t.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",t[t.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",t[t.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",t[t.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",t[t.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",t[t.BICM_SKIP=0]="BICM_SKIP",t[t.BICM_REV=2147483648]="BICM_REV"}(at||(at={})),function(t){t[t.BCM_AUTO=1]="BCM_AUTO",t[t.BCM_GENERAL=2]="BCM_GENERAL",t[t.BCM_SKIP=0]="BCM_SKIP",t[t.BCM_REV=2147483648]="BCM_REV"}(ht||(ht={})),function(t){t[t.BF2_NULL=0]="BF2_NULL",t[t.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",t[t.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",t[t.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",t[t.BF2_POSTNET=2097152]="BF2_POSTNET",t[t.BF2_PLANET=4194304]="BF2_PLANET",t[t.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",t[t.BF2_RM4SCC=16777216]="BF2_RM4SCC",t[t.BF2_DOTCODE=2]="BF2_DOTCODE",t[t.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",t[t.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",t[t.BF2_PHARMACODE=12]="BF2_PHARMACODE",t[t.BF2_ALL=4294967295]="BF2_ALL"}(lt||(lt={})),function(t){t[t.BM_AUTO=1]="BM_AUTO",t[t.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",t[t.BM_SKIP=0]="BM_SKIP",t[t.BM_THRESHOLD=4]="BM_THRESHOLD",t[t.BM_REV=2147483648]="BM_REV"}(ct||(ct={})),function(t){t[t.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(ut||(ut={})),function(t){t[t.CFM_GENERAL=1]="CFM_GENERAL"}(dt||(dt={})),function(t){t[t.CCM_AUTO=1]="CCM_AUTO",t[t.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",t[t.CCM_SKIP=0]="CCM_SKIP",t[t.CCM_REV=2147483648]="CCM_REV"}(ft||(ft={})),function(t){t[t.CICM_GENERAL=1]="CICM_GENERAL",t[t.CICM_SKIP=0]="CICM_SKIP",t[t.CICM_REV=2147483648]="CICM_REV"}(gt||(gt={})),function(t){t[t.CM_IGNORE=1]="CM_IGNORE",t[t.CM_OVERWRITE=2]="CM_OVERWRITE"}(_t||(_t={})),function(t){t[t.DM_SKIP=0]="DM_SKIP",t[t.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",t[t.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",t[t.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",t[t.DM_SMOOTHING=8]="DM_SMOOTHING",t[t.DM_MORPHING=16]="DM_MORPHING",t[t.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",t[t.DM_SHARPENING=64]="DM_SHARPENING",t[t.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",t[t.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(pt||(pt={})),function(t){t[t.DRM_AUTO=1]="DRM_AUTO",t[t.DRM_GENERAL=2]="DRM_GENERAL",t[t.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",t[t.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",t[t.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",t[t.DRM_SKIP=0]="DRM_SKIP",t[t.DRM_REV=2147483648]="DRM_REV"}(mt||(mt={})),function(t){t[t.DPMCRM_AUTO=1]="DPMCRM_AUTO",t[t.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",t[t.DPMCRM_SKIP=0]="DPMCRM_SKIP",t[t.DPMCRM_REV=2147483648]="DPMCRM_REV"}(vt||(vt={})),function(t){t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_REV=2147483648]="GTM_REV"}(yt||(yt={})),function(t){t[t.IPM_AUTO=1]="IPM_AUTO",t[t.IPM_GENERAL=2]="IPM_GENERAL",t[t.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",t[t.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",t[t.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",t[t.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",t[t.IPM_SKIP=0]="IPM_SKIP",t[t.IPM_REV=2147483648]="IPM_REV"}(St||(St={})),function(t){t[t.IRSM_MEMORY=1]="IRSM_MEMORY",t[t.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",t[t.IRSM_BOTH=4]="IRSM_BOTH"}(Ct||(Ct={})),function(t){t[t.LM_SKIP=0]="LM_SKIP",t[t.LM_AUTO=1]="LM_AUTO",t[t.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",t[t.LM_LINES=8]="LM_LINES",t[t.LM_STATISTICS=4]="LM_STATISTICS",t[t.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",t[t.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",t[t.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",t[t.LM_CENTRE=128]="LM_CENTRE",t[t.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",t[t.LM_REV=2147483648]="LM_REV"}(wt||(wt={})),function(t){t[t.PDFRM_RASTER=1]="PDFRM_RASTER",t[t.PDFRM_AUTO=2]="PDFRM_AUTO",t[t.PDFRM_VECTOR=4]="PDFRM_VECTOR",t[t.PDFRM_REV=2147483648]="PDFRM_REV"}(bt||(bt={})),function(t){t[t.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",t[t.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",t[t.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",t[t.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(xt||(xt={})),function(t){t[t.RPM_AUTO=1]="RPM_AUTO",t[t.RPM_GENERAL=2]="RPM_GENERAL",t[t.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",t[t.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",t[t.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",t[t.RPM_SKIP=0]="RPM_SKIP",t[t.RPM_REV=2147483648]="RPM_REV"}(Tt||(Tt={})),function(t){t[t.RCT_PIXEL=1]="RCT_PIXEL",t[t.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(It||(It={})),function(t){t[t.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",t[t.RT_RAW_TEXT=1]="RT_RAW_TEXT",t[t.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",t[t.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(Et||(Et={})),function(t){t[t.SUM_AUTO=1]="SUM_AUTO",t[t.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",t[t.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",t[t.SUM_SKIP=0]="SUM_SKIP",t[t.SUM_REV=2147483648]="SUM_REV"}(Ot||(Ot={})),function(t){t[t.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",t[t.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",t[t.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",t[t.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",t[t.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",t[t.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(Rt||(Rt={})),function(t){t[t.TFM_AUTO=1]="TFM_AUTO",t[t.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",t[t.TFM_SKIP=0]="TFM_SKIP",t[t.TFM_REV=2147483648]="TFM_REV"}(At||(At={})),function(t){t[t.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",t[t.TROM_POSITION=2]="TROM_POSITION",t[t.TROM_FORMAT=4]="TROM_FORMAT",t[t.TROM_SKIP=0]="TROM_SKIP",t[t.TROM_REV=2147483648]="TROM_REV"}(Dt||(Dt={})),function(t){t[t.TDM_AUTO=1]="TDM_AUTO",t[t.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",t[t.TDM_SKIP=0]="TDM_SKIP",t[t.TDM_REV=2147483648]="TDM_REV"}(Mt||(Mt={}));export{x as BarcodeReader,ot as BarcodeScanner,at as EnumBarcodeColourMode,ht as EnumBarcodeComplementMode,y as EnumBarcodeFormat,lt as EnumBarcodeFormat_2,ct as EnumBinarizationMode,ut as EnumClarityCalculationMethod,dt as EnumClarityFilterMode,ft as EnumColourClusteringMode,gt as EnumColourConversionMode,_t as EnumConflictMode,vt as EnumDPMCodeReadingMode,pt as EnumDeblurMode,mt as EnumDeformationResistingMode,m as EnumErrorCode,yt as EnumGrayscaleTransformationMode,v as EnumIMResultDataType,p as EnumImagePixelFormat,St as EnumImagePreprocessingMode,Ct as EnumIntermediateResultSavingMode,S as EnumIntermediateResultType,wt as EnumLocalizationMode,bt as EnumPDFReadingMode,xt as EnumQRCodeErrorCorrectionLevel,Tt as EnumRegionPredetectionMode,It as EnumResultCoordinateType,Et as EnumResultType,Ot as EnumScaleUpMode,Rt as EnumTerminatePhase,At as EnumTextFilterMode,Dt as EnumTextResultOrderMode,Mt as EnumTextureDetectionMode}; + */const A="undefined"==typeof self;let D,M,F,L,P;if("undefined"!=typeof navigator&&(D=navigator,M=D.userAgent,F=D.platform,L=D.mediaDevices),!A){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:D.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:F,search:"Win"},Mac:{str:F},Linux:{str:F}};let i="unknownBrowser",r=0,s="unknownOS";for(let e in t){const s=t[e]||{};let n=s.str||M,o=s.search||e,a=s.verStr||M,h=s.verSearch||e;if(h instanceof Array||(h=[h]),-1!=n.indexOf(o)){i=e;for(let t of h){let e=a.indexOf(t);if(-1!=e){r=parseFloat(a.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||M,n=i.search||t;if(-1!=r.indexOf(n)){s=t;break}}"Linux"==s&&-1!=M.indexOf("Windows NT")&&(s="HarmonyOS"),P={browser:i,version:r,OS:s}}A&&(P={browser:"ssr",version:0,OS:"ssr"});const k="undefined"!=typeof WebAssembly&&M&&!(/Safari/.test(M)&&!/Chrome/.test(M)&&/\(.+\s11_2_([2-6]).*\)/.test(M)),B=!("undefined"==typeof Worker),N=!(!L||!L.getUserMedia),j=async()=>{let t=!1;if(N)try{(await L.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===P.browser&&P.version>66||"Safari"===P.browser&&P.version>13||"OPR"===P.browser&&P.version>43||"Edge"===P.browser&&P.version;const V=(()=>{if(!A&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"})();class U{constructor(t,e){this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapStyle=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,this._setFabricObject(t),this._mediaType=t.type,this.styleSelector="default",this.styleId=e}get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.styleSelector="selected"})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.styleSelector="selected":this.styleSelector="default","textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}_on(t,e){if(!e)return;const i=t.toLowerCase(),r=this.mapEvent_Callbacks.get(i);if(!r)throw new Error(`Event '${t}' does not exist.`);let s=r.get(e);s||(s=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const r={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,s,n;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,s=t+window.scrollX,n=e+window.scrollY;const a=this._drawingLayer.fabricCanvas.lowerCanvasEl.width,h=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,l=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),c=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),u=l/c,d=a/h,f=this._drawingLayer._getObjectFit();let g,_,p,m,v=1;if("contain"===f)u0?i-1:r,H),actionName:"modifyPolygon",pointIndex:i}),t}),{})}_extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,r){return t["p"+r]=new R.Control({positionHandler:G,actionHandler:Y(r>0?r-1:i,H),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}_extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let r=i.x-e.pathOffset.x,s=i.y-e.pathOffset.y;const n=R.util.transformPoint({x:r,y:s},e.calcTransformMatrix());t.push({x:n.x,y:n.y})}return t}}}const z=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let r=0;ri&&(i=s.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let s=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(s)}}})(e),(t=>{let e="";for(let i=0;im?(g=d,_=d/p,{x:s.x*i.width,y:(s.y-(f-_)/2)*i.width}):(g=f*p,_=f,{x:(s.x-(d-g)/2)*i.height,y:s.y*i.height}):"cover"===l?p>m?{x:(c-i.height*d)/2+s.x*i.height,y:s.y*i.height}:{x:s.x*i.width,y:(u-i.width*f)/2+s.y*i.width}:{x:s.x*i.width,y:s.y*i.height}}return i={width:1,height:1},{x:s.x*i.width,y:s.y*i.height}},R.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,r=this._getEventPrefix();R.util.addListener(R.document,"touchend",this._onTouchEnd,{passive:!1}),R.util.addListener(R.document,"touchmove",this._onMouseMove,{passive:!1}),R.util.removeListener(i,r+"down",this._onMouseDown)},R.Textbox.prototype._wrapLine=function(t,e,i,r){const s=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),n=!(!s||!s.length);var o=0,a=this.splitByGrapheme||n,h=[],l=[],c=a?R.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,_=0,p=0,m=!0,v=this._getWidthOfCharSpacing();r=r||0,0===c.length&&c.push([]),i-=r;for(var y=0;yi&&!m?(h.push(l),l=[],o=g,m=!0):o+=v,m||a||l.push(f),l=l.concat(u),_=a?0:this._measureWord([f],e,d),d++,m=!1,g>p&&(p=g);return y&&h.push(l),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),h});class K{constructor(t,e,i,r){let s,n;switch(this.mapMediaType_Style=new Map,this.mode="viewer",this.onSelectionChange=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas")?this.fabricCanvas=t.getFabricCanvas():(this.fabricCanvas=new R.Canvas(t,Object.assign(r,{allowTouchScrolling:!0})),this.fabricCanvas.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),this.fabricCanvas.lowerCanvasEl.className="",this.fabricCanvas.upperCanvasEl.className="",this.fabricCanvas.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChange&&t.onSelectionChange(i,[])}),0)}})),this.fabricCanvas.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let r of e){const e=r.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let r of i)t.hasDrawingItem(r)&&e.push(r);e.length>0&&t.onSelectionChange&&t.onSelectionChange([],e)}),0)}})),this.fabricCanvas.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,r=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!r.includes(e)&&r.push(e)}for(let t of r){const r=[],s=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&r.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&s.push(i)}setTimeout((()=>{t.onSelectionChange&&t.onSelectionChange(r,s)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas),this.id=e,this._mapDrawingStyles=i,e){case 1:s=i.get(1),n=i.get(5);break;case 2:s=i.get(2),n=i.get(6);break;case 3:s=i.get(3),n=i.get(7);break;default:s=i.get(4),n=i.get(8)}for(let t of U.arrMediaTypes)this.mapMediaType_Style.set(t,{default:s,selected:n})}getId(){return this.id}_getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=this._mapDrawingStyles.get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyleId(t){return t.styleId?t.styleId:this.mapMediaType_Style.get(t._mediaType)[t.styleSelector].styleId}_getItemCurrentStyle(t){if(t.styleId)return this._getDrawingStyle(t.styleId);return t._mapStyle.get(t.styleSelector)||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,r){let s;switch(t){case"rect":s=this.fabricCanvas.getObjects("rect");break;case"arc":s=this.fabricCanvas.getObjects("circle");break;case"polygon":s=this.fabricCanvas.getObjects("polygon");break;case"image":s=this.fabricCanvas.getObjects("image");break;case"text":s=this.fabricCanvas.getObjects("textbox");break;case"line":s=this.fabricCanvas.getObjects("line");break;case"path":s=this.fabricCanvas.getObjects("path")}for(let t of s){if(!this._arrFabricObject.includes(t))continue;const r=t.getDrawingItem();r.styleSelector===e&&this._changeItemStyle(r,i,!0)}r||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const r=t._getFabricObject();"number"==typeof t.styleId&&(e=this._getDrawingStyle(t.styleId)),r.strokeWidth=e.lineWidth,"fill"===e.paintMode?(r.fill=e.fillStyle,r.stroke=e.fillStyle):"stroke"===e.paintMode?(r.fill="transparent",r.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(r.fill=e.fillStyle,r.stroke=e.strokeStyle),r.fontFamily&&(r.fontFamily=e.fontFamily),r.fontSize&&(r.fontSize=e.fontSize),r.group||(r.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const r=t.getChildItems();if("add"===i){if(r.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=this._getDrawingStyle(e.styleId);else{i=this.mapMediaType_Style.get(e._mediaType)[t.styleSelector];const r=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},s=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!r.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){let i=t._getFabricObject();const r=this.fabricCanvas.getObjects();let s,n;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){s=t.getChildItems();for(let t of s)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(s){for(let t of s){const e=this.mapMediaType_Style.get(t._mediaType);for(let i of U.arrStyleSelectors)t._mapStyle.set(i,e[i]);if(t.styleId)n=this._getDrawingStyle(t.styleId);else{n=e.default;const i=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected,!0)},r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default,!0)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,n,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapMediaType_Style.get(t._mediaType);for(let i of U.arrStyleSelectors)t._mapStyle.set(i,e[i]);if(t.styleId)n=this._getDrawingStyle(t.styleId);else{n=e.default;const i=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).selected)},r=()=>{this._changeItemStyle(t,this.mapMediaType_Style.get(t._mediaType).default)};t._on("selected",i),t._on("deselected",r),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=r}this._changeItemStyle(t,n)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const o=this._arrFabricObject.length;let a=r.length;if(o)a=r.indexOf(this._arrFabricObject[o-1])+1;else for(let e=0;e{for(let e of this._arrDrawingLayer)if(e.getId()===t)return!0;return!1};if(void 0===e){for(let t=100;;t++)if(!i(t)){e=t;break}}else if(i(e))throw new Error("Existed drawing layer id.");const r=new K(t,e,this._mapDrawingStyles,{enableRetinaScaling:!1});return r._manager=this,this._arrDrawingLayer.push(r),this._switchPointerEvent(),r}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._arrDrawingLayer[0].fabricCanvas.getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){this._arrDrawingLayer.length&&(this._arrDrawingLayer[0].fabricCanvas.wrapperEl.style.display=t?"block":"none")}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class q{constructor(t){this._controlTarget=null,this._arrUsers=[],this._mapAction_UserArgs=new Map,this._mapProperty_UserValue=new Map,this._mapAction_Callbacks=new Map,this._controlTarget=t}setControlTarget(t){this._controlTarget=t}getControlTarget(){return this._controlTarget}register(t){this._arrUsers.includes(t)||this._arrUsers.push(t)}logout(t){const e=this._arrUsers.indexOf(t);-1!==e&&(this.clearUserDisiredAction({user:t}),this.clearUserDisiredValue({user:t}),this._arrUsers.splice(e,1))}getRegisteredUsers(){return this._arrUsers}ifUserExisted(t){return this._arrUsers.includes(t)}setDisiredValue(t,e,i,r){if(!this._arrUsers.includes(t))throw new Error("Unregistered user.");r&&(this._controlTarget[e]=i),this._mapProperty_UserValue.get(e)?this._mapProperty_UserValue.get(e).set(t,i):this._mapProperty_UserValue.set(e,new Map([[t,i]]))}clearUserDisiredValue(t){if(t&&(t.user||t.property)){if(t.property&&t.user){const e=this._mapProperty_UserValue.get(t.property);if(!e)return;e.delete(t.user)}else if(t.property)this._mapProperty_UserValue.delete(t.property);else if(t.user)for(let e of this._mapProperty_UserValue.values())e.delete(t.user)}else this._mapProperty_UserValue=new Map}getValue(t){if(!this._controlTarget)throw new Error("Control target is not set.");return this._controlTarget[t]}getPropertyDisiredValue(t){if(this._mapProperty_UserValue.get(t)){const e=[],i=this._mapProperty_UserValue.get(t);for(let t of i.values())e.push(t);return e}return null}setDisiredAction(t,e,i,r){if(!this._arrUsers.includes(t))throw new Error("Unregistered user.");return i||(i=[]),r?this._controlTarget[e](...i):(this._mapAction_UserArgs.get(e)?this._mapAction_UserArgs.get(e).set(t,i):this._mapAction_UserArgs.set(e,new Map([[t,i]])),this._render(e))}clearUserDisiredAction(t){if(t&&(t.user||t.actionName)){if(t.actionName&&t.user){const e=this._mapAction_UserArgs.get(t.actionName);if(!e)return;e.delete(t.user)}else if(t.actionName)this._mapAction_UserArgs.delete(t.actionName);else if(t.user)for(let e of this._mapAction_UserArgs.values())e.delete(t.user);this.render()}else this._mapAction_UserArgs=new Map}addCallback(t,e){const i=this._mapAction_Callbacks.get(t);i?i.push(e):this._mapAction_Callbacks.set(t,[e])}removeCallback(t,e){const i=this._mapAction_Callbacks.get(t);if(!i)return;const r=i.indexOf(e);-1!==r&&i.splice(r,1)}clearCallback(t){t?this._mapAction_Callbacks.delete(t):this._mapAction_Callbacks.clear()}_fireCallback(t){const e=this._mapAction_Callbacks.get(t);if(e)for(let t of e){if(!t)return;setTimeout(t.bind(this._controlTarget),0)}}_render(t){const e=this._mapAction_UserArgs.get(t);if(!e)throw new Error("Unrecorded action.");if(e.size===this._arrUsers.length){let i=[];for(let t of e.values())t.length>0&&(i=t);if(this._controlTarget[t]){const e=this._controlTarget[t](...i);return this._mapAction_UserArgs.delete(t),this._fireCallback(t),e}}}render(t){if(t)return this._render(t);for(let t of this._mapAction_UserArgs.keys())this._render(t)}}class Q{static multiply(t,e){const i=[];for(let r=0;r<3;r++){const s=e.slice(3*r,3*r+3);for(let e=0;e<3;e++){const r=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*s[i]),0);i.push(r)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Q.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),r=Math.sin(e);return Q.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return Q.multiply(t,[e,0,0,0,i,0,0,0,1])}}var $;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}($||($={}));const tt=(t,e,i,r)=>{let s=e+Math.round((t-e)/i)*i;return r&&(s=Math.min(s,r)),s};class et{constructor(){this._maxCvsSideLength=void 0,this._defaultMaxCvsSideLength=null,this._predefinedResolutions=[{width:160,height:120},{width:320,height:240},{width:480,height:360},{width:640,height:480},{width:800,height:600},{width:960,height:720},{width:1280,height:720},{width:1920,height:1080},{width:2560,height:1440},{width:3840,height:2160}],this._mapCameraResolutions=new Map,this._bWebGLSupported=!0,this.extraBindings=[],this._singleFrameMode=!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia),this._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameModeIpt=null,this._clickIptSingleFrameMode=()=>{if(this.singleFrameMode&&!this.getDrawingLayers().some((t=>"editor"==t.getMode()))){if(!this._singleFrameModeIpt){const t=document.createElement("input");this._singleFrameModeIpt=t,t.setAttribute("type","file"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),t.setAttribute("capture",""),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";const i=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var r;return e||(i=await(r=t,new Promise(((t,e)=>{let i=URL.createObjectURL(r),s=new Image;s.dbrObjUrl=i,s.src=i,s.onload=()=>{t(s)},s.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(e),r=i instanceof HTMLImageElement?i.naturalWidth:i.width,s=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=s;const n=t=>{const e=Date.now();if(0===r||0===s)return null;if(t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");const i=this._scanRegion,n=this.getFrameSize(r,s,i,this.maxCvsSideLength);if(!n)return null;let o=!0;r===n.sWidth&&s===n.sHeight&&(o=!1);const a=this.mapPixelFormatString_Enum.get(this.framePixelFormat.toLowerCase()),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:n.sx,sy:n.sy,width:n.dWidth,height:n.dHeight,colorMode:null,pixelFormat:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:n.sWidth,_sHeight:n.sHeight,_bUseWebGL:null},l=this._getImageData(t,r,s,n,null,{pixelFormat:a});if(!l)return null;const c=Date.now();return h.data=l.data,h.pixelFormat=h.colorMode=l.pixelFormat,h._bUseWebGL=l._bUseWebGL,h.timeSpent=c-e,h.timeStamp=c,l.pixelFormat===$.GREY?h.stride=h.width:h.stride=4*h.width,h};(t=>{let e=this._cvsSingleFrameMode;if(!e){if(e=document.createElement("canvas"),!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(e),e.style.position="absolute",e.style.width="100%",e.style.height="100%",e.style.left="0",e.style.top="0",e.style.objectFit="contain",e.style.pointerEvents="none",this._cvsSingleFrameMode=e}e.width==r&&e.height==s||(e.width=r,e.height=s);const i=e.getContext("2d");i.clearRect(0,0,e.width,e.height),i.drawImage(t,0,0)})(i),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t);let o;this._updateDrawingLayersSize();try{o=n(i)}catch(t){throw t}const a=this.mapCameraEvents.get("singleframeacquired");for(let t of a)if(t)try{const e={data:new Uint8Array(o.data),region:JSON.parse(JSON.stringify(o.region)),sx:o.sx,sy:o.sy,width:o.width,height:o.height,stride:o.stride,colorMode:o.colorMode,pixelFormat:o.pixelFormat,timeSpent:o.timeSpent,timeStamp:o.timeStamp,isCropped:o.isCropped,toCanvas:o.toCanvas,_sWidth:o._sWidth,_sHeight:o._sHeight,_bUseWebGL:o._bUseWebGL};await t.apply(this,[e])}catch(t){console.error(t)}})),t.style.position="fixed",t.style.left="-1px",t.style.top="-1px",t.style.width="1px",t.style.height="1px",t.style.backgroundColor="transparent",t.style.color="transparent",document.body.appendChild(t)}this._singleFrameModeIpt.click()}},this.styleEls=[],this._framePixelFormat=void 0,this._defaultFramePixelFormat="rgba",this.mapPixelFormatString_Enum=new Map([["grey",$.GREY],["grey32",$.GREY32],["rgba",$.RGBA],["rbga",$.RBGA],["grba",$.GRBA],["gbra",$.GBRA],["brga",$.BRGA],["bgra",$.BGRA]]),this.shaderPixelFormat=$.RGBA,this.maxVideoCvsLength=3,this._reusedCvs=null,this._reusedWebGLCvs=null,this._tempDataContainer=null,this._webGLTexture=null,this._webGLProgramInfo=null,this._webGLBuffers=null,this._softwareScale=1,this._scaleCenter={x:0,y:0},this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,_focusArea:null},this._tapFocusEnabled=!0,this._focusSupported=!0,this._tapDoFocus=async t=>{if(this._touchMoved)return void(this._touchMoved=!1);if(!this._tapFocusEnabled)return;if(!this._bOpen)return;if(this.singleFrameMode)return;if(!this._video||this._video.paused)return;if(!this._videoTrack)return;if(!this._focusSupported)return;if(this.getDrawingLayers().some((t=>"editor"==t.getMode())))return;if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let e,i,r,s;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)e=t.clientX,i=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;e=t.changedTouches[0].clientX,i=t.changedTouches[0].clientY}const n=this.getVideoFit(),o=this._video.videoWidth,a=this._video.videoHeight,h=this._elContainer.getBoundingClientRect(),l=h.left,c=h.top,u=window.getComputedStyle(this._elContainer),d=parseFloat(u.width),f=parseFloat(u.height),g=d/f,_=o/a;let p=1;if("contain"===n)_>g?(p=d/o,r=(e-l)/p,s=(i-c-(f-d/_)/2)/p):(p=f/a,s=(i-c)/p,r=(e-l-(d-f*_)/2)/p);else{if("cover"!==n)throw new Error("Unsupported object-fit.");_>g?(p=f/a,s=(i-c)/p,r=(e-l+(f*_-d)/2)/p):(p=d/o,r=(e-l)/p,s=(i-c+(d/_-f)/2)/p)}const m={x:r+"px",y:s+"px"},v=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=v;await this._setLocalFocus(m,v,y,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance),this._focusParameters.taskBackToContinous=setTimeout((()=>{this._videoTrack&&this._videoTrack.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime)},this._touchMoved=!1,this._touchMoveEvent=()=>{this._touchMoved=!0},this._recordedStates={},this.playCallbackInfo=null,this._toCanvas=function(){const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,"grey"===(this.pixelFormat||this.colorMode)){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let t,e;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];t=i.getAttribute("data-width"),e=i.getAttribute("data-height")}await this.setResolution(t,e),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this.singleFrameMode)if("visible"===document.visibilityState){if(this._bOpen&&this._vc_bPlayingVideoBeforeHide)if(this.videoSrc)this._video.play();else if(this._video.srcObject){const t=this._video.srcObject.getTracks()[0];this._video.srcObject.active&&t&&!t.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(["iPhone","iPad"].includes(P.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let t of this._arrScanRegionOverlays)t&&(t.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&(t.style.display="",this._updateScanRegionOverlay(t));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null}static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:k,worker:B,getUserMedia:N,camera:await j(),browser:P.browser,version:P.version,OS:P.OS}))()}static set engineResourcePath(t){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");et._engineResourcePath=(t=>{if(null==t&&(t="./"),!A){let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(t)}static get engineResourcePath(){return this._engineResourcePath}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static isDCEFrame(t){return!(!t||"object"!=typeof t||Array.isArray(t))&&"data"in t&&"region"in t&&"sx"in t&&"sy"in t&&"width"in t&&"height"in t&&("colorMode"in t||"pixelFormat"in t)&&"timeSpent"in t&&"timeStamp"in t&&"isCropped"in t&&"toCanvas"in t&&"_sWidth"in t&&"_sHeight"in t&&"_bUseWebGL"in t}static async testCameraAccess(){try{if(!navigator||!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return{ok:!1,message:"Insecure context."};(await navigator.mediaDevices.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()}))}catch(t){if("OverconstrainedError"===t.name||"NotFoundError"===t.name)return{ok:!1,message:"No camera detected."};if("NotAllowedError"===t.name)return{ok:!1,message:"No permission to access camera."};if("AbortError"===t.name)return{ok:!1,message:"Some problem occurred which prevented the device from being used."};if("NotReadableError"===t.name)return{ok:!1,message:"A hardware error occurred."};if("SecurityError"===t.name)return{ok:!1,message:"User media support is disabled."};throw t}return{ok:!0,message:"Successfully accessed the camera."}}set maxCvsSideLength(t){if(t<=0)throw new Error("Invalid value.");this._maxCvsSideLength=t}get maxCvsSideLength(){if(void 0!==this._maxCvsSideLength)return this._maxCvsSideLength;if(this._controler){const t=this._controler.getPropertyDisiredValue("maxCvsSideLength");if(t&&1===t.length)return t[0]}return this._defaultMaxCvsSideLength}static set defaultUIElementURL(t){et._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=et._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",et.engineResourcePath)}getUIElement(){return this.UIElement}async setUIElement(t){if(this._bOpen)throw new Error("It is not allowed to change the UIElement when the camera is open.");if("string"==typeof t||t instanceof String){if(!t.trim().startsWith("<")){let e=await fetch(t);if(!e.ok)throw Error("setUIElement(elementOrUrl): Network Error: "+e.statusText);t=await e.text()}if(!t.trim().startsWith("<"))throw Error("setUIElement(elementOrUrl): Can't get valid HTMLElement.");let e=document.createElement("div");e.innerHTML=t;for(let t=0;t100||t.regionTop>100||t.regionRight>100||t.regionBottom>100)))}set scanRegion(t){if(!this._checkValidRegion(t))throw new Error("Invalid region.");this._scanRegion=JSON.parse(JSON.stringify(t)),this._updateScanRegionCanvas(),this._updateScanAreaDiv();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t)}setScanRegion(t){this.scanRegion=t}getScanRegion(){return JSON.parse(JSON.stringify(this._scanRegion))}_calculateCvsSize(){if(!this._bOpen)return null;let t,e,i;if(this.singleFrameMode)t=this._imgWidth,e=this._imgHeight,i="contain";else{if(!this._video)return null;t=this._video.videoWidth,e=this._video.videoHeight,i=this.getVideoFit()}return{width:t,height:e,objectFit:i}}addScanRegionOverlayCanvas(){this._assertOpen();const t=document.createElement("canvas");if(this._updateScanRegionOverlay(t),!this._scanRegionOverlayContainer){const t=document.createElement("div");if(this._scanRegionOverlayContainer=t,t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.overflow="hidden",t.style.pointerEvents="none",this._layerBaseCvs)this._layerBaseCvs.parentElement.after(t);else if(this._cvsScanRegion)this._cvsScanRegion.after(t);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(t);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(t);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(t)}this._recordedStates.overlayShow=!0}return this._scanRegionOverlayContainer.append(t),this._arrScanRegionOverlays.push(t),t}removeScanRegionOverlayCanvas(t){const e=this._arrScanRegionOverlays.indexOf(t);-1!==e&&(t.remove(),this._arrScanRegionOverlays.splice(e,1))}_updateScanRegionOverlay(t){if(!t)return;const e=this._calculateCvsSize();if(!e)return;const{width:i,height:r,objectFit:s}=e;if(i<=0||r<=0)return t.width=0,void(t.height=0);const n=this._getRegionInPixels(i,r,this._scanRegion),o=this.getFrameSize(i,r,this._scanRegion,this.maxCvsSideLength),a=o.dWidth,h=o.dHeight;t.width==a&&t.height==h||(t.width=a,t.height=h);const l=window.getComputedStyle(this._elContainer),c=parseFloat(l.width),u=parseFloat(l.height),d=c/u,f=i/r;let g,_,p,m,v=1;"contain"===s?(f>d?(v=c/i,g=0,_=(u-r*v)/2):(v=u/r,g=(c-i*v)/2,_=0),g+=n.regionLeft*v,_+=n.regionTop*v,p=(n.regionRight-n.regionLeft)*v,m=(n.regionBottom-n.regionTop)*v):"cover"===s?(f>d?(v=u/r,g=n.regionLeft*v-(i*v-c)/2,_=n.regionTop*v):(v=c/i,g=n.regionLeft*v,_=n.regionTop*v-(r*v-u)/2),p=(n.regionRight-n.regionLeft)*v,m=(n.regionBottom-n.regionTop)*v):(g=0,_=0,p=0,m=0),t.style.position="absolute",t.style.left=g+"px",t.style.top=_+"px",t.style.width=p+"px",t.style.height=m+"px"}showScanRegionOverlays(){this._scanRegionOverlayContainer&&("none"==this._scanRegionOverlayContainer.style.display&&(this._scanRegionOverlayContainer.style.display=""),this._recordedStates.overlayShow=!0)}hideScanRegionOverlays(){this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none",this._recordedStates.overlayShow=!1)}setViewDecorator(t,e){if(!t)return void(this._cvsViewDecorator&&(this._cvsViewDecorator.remove(),this._cvsViewDecorator=null));if(!e)throw new Error("Invalid area.");this._assertOpen();let i=[];if("string"==typeof t?i.push(t):Array.isArray(t)&&(i=JSON.parse(JSON.stringify(t))),!this._cvsViewDecorator){if(this._cvsViewDecorator=document.createElement("canvas"),this._scanRegionOverlayContainer)this._scanRegionOverlayContainer.after(this._cvsViewDecorator);else if(this._layerBaseCvs)this._layerBaseCvs.parentElement.after(this._cvsViewDecorator);else if(this._cvsScanRegion)this._cvsScanRegion.after(this._cvsViewDecorator);else if(this._cvsOriginalImage)this._cvsOriginalImage.after(this._cvsViewDecorator);else if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(this._cvsViewDecorator);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(this._cvsViewDecorator)}this._recordedStates.decoratorShow=!0}this._decoratorArea=JSON.parse(JSON.stringify(e)),this._decoratorType.length=0;const r=["rectangle","focus"],s=["crossline","crosshair"];let n=!1,o=!1;for(let t of i)t=t.toLowerCase(),r.includes(t)&&!n&&(n=!0,this._decoratorType.push(t)),s.includes(t)&&!o&&(o=!0,!this._decoratorType.includes(t)&&this._decoratorType.push(t));this._updateViewDecorator()}getViewDecorator(){return{type:JSON.parse(JSON.stringify(this._decoratorType)),area:JSON.parse(JSON.stringify(this._decoratorArea)),canvas:this._cvsViewDecorator}}showViewDecorator(){this._cvsViewDecorator&&("none"==this._cvsViewDecorator.style.display&&(this._cvsViewDecorator.style.display=""),this._recordedStates.decoratorShow=!0)}hideViewDecorator(){this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none",this._recordedStates.decoratorShow=!1)}setViewDecoratorLineWidth(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("lineWidth"))throw new Error(`It is not allowed to change the property 'lineWidth' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].lineWidth=e,this._updateViewDecorator()}setViewDecoratorStrokeStyle(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("strokeStyle"))throw new Error(`It is not allowed to change the property 'strokeStyle' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].strokeStyle=e,this._updateViewDecorator()}setViewDecoratorFillStyle(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("fillStyle"))throw new Error(`It is not allowed to change the property 'fillStyle' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].fillStyle=e,this._updateViewDecorator()}setViewDecoratorMaskFillStyle(t,e){if("string"!=typeof t)throw new Error("The 'type' should be a string.");if(t=t.toLowerCase(),!this._viewDecoratorInfo.hasOwnProperty(t))throw new Error(`The type of '${t}' doesn't exist.`);if(!this._viewDecoratorInfo[t].hasOwnProperty("maskFillStyle"))throw new Error(`It is not allowed to change the property 'maskFillStyle' when the decorator type is '${t}'.`);this._viewDecoratorInfo[t].maskFillStyle=e,this._updateViewDecorator()}_updateViewDecorator(){if(!this._bOpen)return;if(!this._cvsViewDecorator||!this._decoratorArea)return;let t;if(this.singleFrameMode)t="contain";else{if(!this._video)return;t=this.getVideoFit()}const e=this._cvsViewDecorator;e.style.position="absolute",e.style.width="100%",e.style.height="100%",e.style.left="0",e.style.top="0",e.style.objectFit=t,e.style.pointerEvents="none";const i=this.getVisibleRegion(!0),r=i.regionRight-i.regionLeft,s=i.regionBottom-i.regionTop;if(e.width==r&&e.height==s||(e.width=r,e.height=s),r<=0||s<=0)return;const n=e.getContext("2d");n.clearRect(0,0,e.width,e.height);const o=this._decoratorArea.x/100*r,a=this._decoratorArea.y/100*s,h=this._decoratorArea.width/100*r,l=this._decoratorArea.height/100*s;for(let t of this._decoratorType){if("rectangle"===t){n.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,n.fillRect(0,0,e.width,e.height),n.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),n.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,n.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),n.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,n.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const t=n.lineWidth/2;n.strokeRect(Math.round(o-t),Math.round(a-t),Math.round(h+n.lineWidth),Math.round(l+n.lineWidth))}if("focus"===t){n.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,n.fillRect(0,0,e.width,e.height),n.clearRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),n.fillStyle=this._viewDecoratorInfo.focus.fillStyle,n.fillRect(Math.round(o),Math.round(a),Math.round(h),Math.round(l)),n.lineWidth=this._viewDecoratorInfo.focus.lineWidth,n.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const t=n.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];n.beginPath();for(let t=0;t{const t=parseFloat(window.getComputedStyle(this._elContainer).width),e=parseFloat(window.getComputedStyle(this._elContainer).height);let n,o={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===s?t/ethis.maxNumberOfFramesInBuffer;)this._frameQueue.shift()}get maxNumberOfFramesInBuffer(){if(void 0!==this._maxNumberOfFramesInBuffer)return this._maxNumberOfFramesInBuffer;if(this._controler){const t=this._controler.getPropertyDisiredValue("maxNumberOfFramesInBuffer");if(t&&1===t.length)return t[0]}return this._defaultMaxNumberOfFramesInBuffer}get numberOfFramesInBuffer(){return this._frameQueue.length}set refreshInterval(t){this._refreshInterval=t}get refreshInterval(){if(void 0!==this._refreshInterval)return this._refreshInterval;if(this._controler){const t=this._controler.getPropertyDisiredValue("refreshInterval");if(t&&1===t.length)return t[0]}return this._defaultRefreshInterval}static async createInstance(t){let e=new et;("string"==typeof t||t instanceof String)&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return this._hasEngineResourceLoaded=!0,e._drawingLayersManager=new J,e}static async playVideo(t,e,i){return new Promise(((r,s)=>{t||s(new Error("Invalid video element.")),e||s(new Error("Invalid source.")),t.onloadedmetadata=async()=>{t.onloadedmetadata=null,await t.play(),r(t)},"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,void 0!==i&&setTimeout((()=>s(new Error("Failed to play video. Timeout."))),i)}))}static findBestRearCamera(t){if(!t||!t.length)return null;const e=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","后面","後面","背面","后置","後置","背置","задней","الخلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","takakamera","belakang","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक"];for(let i of t){const t=i.label.toLowerCase();if(t&&e.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return i.deviceId}return["Android","HarmonyOS"].includes(P.OS)?t[t.length-1].deviceId:null}async play(t,e,i,r){if(this._video&&this.videoSrc){const t=await et.playVideo(this._video,this.videoSrc,4e3);if(!this._video)return t.pause(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};const e={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};this.playCallbackInfo=JSON.parse(JSON.stringify(e));const i=this.mapCameraEvents.get("played");for(let t of i){if(!t)continue;const i=JSON.parse(JSON.stringify(e));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[i])}),0)}return this._recordedStates.videoPlaying=!0,e}if(this.singleFrameMode)return r&&r.notTriggerSingleFrameClick||this._clickIptSingleFrameMode(),this.playCallbackInfo={width:0,height:0,deviceId:null},{width:0,height:0,deviceId:null};if(!this._video)throw new Error("'video' is null or undefined.");const s=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,s{var r;try{this._video&&this._video.srcObject&&this.stop(),et._onLog&&et._onLog("DCE: ======before video========");const s=()=>{if(!this._video)throw a&&a.getTracks().forEach((t=>{t.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},n=this.getVideoSettings();let o,a;if("boolean"==typeof n.video&&(n.video={}),t)delete n.video.facingMode,n.video.deviceId={exact:t};else if(n.video.deviceId);else if(this._lastDeviceId)delete n.video.facingMode,n.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&et.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete n.video.facingMode,n.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const t=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),e=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));t&&e&&(n.video.width=t,n.video.height=e)}else if(this.ifSkipCameraInspection);else if(n.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let t=n.video.facingMode;if(t instanceof Array&&t.length&&(t=t[0]),t=t.exact||t.ideal||t,"environment"===t){o=!0;const t=et.findBestRearCamera(this._allCameras);t&&(delete n.video.facingMode,n.video.deviceId={ideal:t})}}e&&(n.video.width={ideal:e}),i&&(n.video.height={ideal:i}),et._onLog&&et._onLog("DCE: ======try getUserMedia========");let h=[0,500],l=null;const c=async t=>{for(let e of h){e&&await new Promise((t=>setTimeout(t,e))),s();try{et._onLog&&et._onLog("DCE: ask "+JSON.stringify(t)),a=await navigator.mediaDevices.getUserMedia(t);break}catch(t){l=t,et._onLog&&et._onLog("DCE: "+t.message||t)}}};let u;if(await c(n),a||(et._onLog&&et._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(n)),"object"==typeof u.video&&(["iPhone","iPad"].includes(P.OS)?(e>=1280||i>=1280?u.video.width=1280:e>=640||i>=640?u.video.width=640:(e<640||i<640)&&(u.video.width=320),delete u.video.height):o&&!n.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0),et._onLog&&et._onLog("DCE: "+u),await c(u)),a||(h=[1e3,2e3],await c(n)),a||await c(u),!a)throw l;const d=()=>{const t=a.getVideoTracks();let e,i;if(t.length&&(e=this._videoTrack=t[0]),this._video&&e){const t=e.getSettings();if(t)for(let r of this._allCameras)if(t.deviceId===r.deviceId){r._checked=!0,r.label=e.label,i=r;break}}this._currentCamera=i};if(await this.getAllCameras(!1),s(),o){d();const t=et.findBestRearCamera(this._allCameras),e=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;t&&t!=e&&(a.getTracks().forEach((t=>{t.stop()})),h=[0,500,1e3,2e3],await c(n))}et._onLog&&et._onLog("DCE: ======play video========"),s(),await et.playVideo(this._video,a,4e3),s(),et._onLog&&et._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=f,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),et._onLog&&et._onLog("DCE: got "+f),d(),this._renderSelCameraInfo();const g={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};g.deviceId&&(this._lastDeviceId=g.deviceId,this.ifSaveLastUsedCamera&&et.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),n.video.width&&n.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(n.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(n.video.height)))));const _=this.mapCameraEvents.get("played");for(let t of _){if(!t)continue;const e=JSON.parse(JSON.stringify(g));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}return this.promisePlay=null,g}catch(t){throw this.promisePlay=null,this._bgLoading&&(this._bgLoading.style.display="none"),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}})();const n=await this.promisePlay;return this.playCallbackInfo=JSON.parse(JSON.stringify(n)),this._recordedStates.videoPlaying=!0,n}async resume(){this._assertOpen(),this._video&&(await this._video.play(),this._recordedStates.videoPlaying=!0),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const t=[this.UIElement];for(let e=0;e','','',''].join(""),this._optGotRsl=this._optGotRsl||this._selRsl.options[0])):!this._optGotRsl&&e.classList.contains("dce-opt-gotResolution")?this._optGotRsl=e:!this._btnClose&&e.classList.contains("dce-btn-close")?this._btnClose=e:!this._selMinLtr&&e.classList.contains("dlr-sel-minletter")?(this._selMinLtr=e,this._selMinLtr.options.length||(this._selMinLtr.innerHTML=[this._optGotMinLtr?"":'','','','','','','','','','',''].join(""),this._optGotMinLtr=this._optGotMinLtr||this._selMinLtr.options[0])):!this._optGotMinLtr&&e.classList.contains("dlr-opt-gotMinLtr")&&(this._optGotMinLtr=e);if(this.extraBindings&&this.extraBindings.length)for(let i of this.extraBindings)try{i(e)}catch(t){}}if(!this._video)throw this._unbindUI(),Error(`Can not find the video container element with class '${this.containerClassName}'`);this.singleFrameMode||this.videoSrc?(this.singleFrameMode&&(this._elContainer&&(this._elContainer.addEventListener("click",this._clickIptSingleFrameMode),this._elContainer.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._elContainer&&(["Android","HarmonyOS"].includes(P.OS)?(this._elContainer.addEventListener("touchend",this._tapDoFocus),this._elContainer.addEventListener("touchmove",this._touchMoveEvent)):this._elContainer.addEventListener("click",this._tapDoFocus)),this._selCam&&(this._selCam.style.display="block",this._selCam.addEventListener("change",this._onCameraSelChange)),this._selRsl&&(this._selRsl.style.display="block",this._selRsl.addEventListener("change",this._onResolutionSelChange)),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._bgLoading&&(this._bgLoading.style.display="block")),this._btnClose&&this._btnClose.addEventListener("click",this._onCloseBtnClick),document.addEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&(this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{for(let e of t)e.target===this._elContainer&&this._updateLayers()}))),this._elContainer&&this._resizeObserver.observe(this._elContainer)),window.addEventListener("resize",this._updateLayers)}_unbindUI(){this.singleFrameMode?(this._elContainer&&(this._elContainer.removeEventListener("click",this._clickIptSingleFrameMode),this._elContainer.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._bgLoading&&(this._bgLoading.style.display="none"),this._elContainer&&(this._elContainer.removeEventListener("click",this._tapDoFocus),this._elContainer.removeEventListener("touchend",this._tapDoFocus),this._elContainer.removeEventListener("touchmove",this._touchMoveEvent)),this._selCam&&this._selCam.removeEventListener("change",this._onCameraSelChange),this._selRsl&&this._selRsl.removeEventListener("change",this._onResolutionSelChange),this._btnClose&&this._btnClose.removeEventListener("click",this._onCloseBtnClick),this.hideScanRegionLaser(),this.hideViewDecorator(),this.hideScanRegionOverlays(),this._drawingLayersManager.setVisible(!1),this._hideOriginalImageCvs(),this._videoContainer&&this._videoContainer.remove(),this._video=null,this._videoContainer=null,this._elContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._cvsScanRegion&&(this._cvsScanRegion.remove(),this._cvsScanRegion=null),this._singleFrameModeIpt&&(this._singleFrameModeIpt.remove(),this._singleFrameModeIpt=null),this._cvsSingleFrameMode&&(this._cvsSingleFrameMode.remove(),this._cvsSingleFrameMode=null),document.removeEventListener("visibilitychange",this._ev_documentHideEvent),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._updateLayers)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}async open(t){this.UIElement||await this.setUIElement(et.defaultUIElementURL),this._bindUI(),t&&this.appendAndShowUI();let e=await this.play();this.bOpen=!0,this._focusParameters.fds=null,this._focusParameters.kTimeout=void 0,this._focusSupported=!0,this._tapFocusEnabled&&!this.singleFrameMode&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,this._focusParameters.fds||(this._focusSupported=!1,this._tapFocusEnabled=!1));const i=this.mapCameraEvents.get("cameraopen");for(let t of i){if(!t)continue;const i=JSON.parse(JSON.stringify(e));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[i])}),0)}return e}close(t){if(!this._video)return;this.stop(),this._hideOriginalImage(!1),this.hideTip(),this._unbindUI(),t&&this.hideUI(),this.stopFetchingLoop(),this.bOpen=!1;const e=this.mapCameraEvents.get("cameraclose");for(let t of e){if(!t)continue;const e={width:0,height:0,deviceId:null};setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}stop(){this._video&&this._video.srcObject&&(this._video.srcObject.getTracks().forEach((t=>{t.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(this._video.pause(),this._video.currentTime=0),this._bgLoading&&(this._bgLoading.style.animationPlayState=""),this._frameQueue.length=0,this._reusedCvs&&this._reusedCvs.ctx2d&&this._reusedCvs.ctx2d.clearRect(0,0,this._reusedCvs.width,this._reusedCvs.height),this.forceLoseContext()}async getAllCameras(t=!0){let e=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));if(t&&e&&e.length&&!e[0].deviceId){let t=await navigator.mediaDevices.getUserMedia({video:!0});e=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}const i=[],r=[];if(this._allCameras)for(let t of this._allCameras)t._checked&&r.push(t);for(let t=0;t{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}if(r!==n.width||s!==n.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const t=this.mapCameraEvents.get("resolutionchange");for(let e of t){if(!e)continue;const t=JSON.parse(JSON.stringify(n));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return n}getResolution(){if(this._bOpen)return[this._video.videoWidth,this._video.videoHeight];{let t=0,e=0;const i=this.videoSettings.video.width,r=this.videoSettings.video.height;return i&&(t=i.exact||i.ideal||i),r&&(e=r.exact||r.ideal||r),[t,e]}}async setResolution(t,e){let i,r;if(t instanceof Array?(i=t[0],r=t[1]):(i=t,r=e),this.videoSettings.video.width={ideal:i},this.videoSettings.video.height={ideal:r},!this._bOpen||this._video.paused)return null;const s=this._video.videoWidth,n=this._video.videoHeight,o=await this.play(null,i,r);if(s!==o.width||n!==o.height){this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&this._updateScanRegionOverlay(t);this._updateDrawingLayersSize(),this._updateVideoContainerStyle();const t=this.mapCameraEvents.get("resolutionchange");for(let e of t){if(!e)continue;const t=JSON.parse(JSON.stringify(o));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return o}async getResolutions(t){let e="";const i=(t,e)=>{const i=this._mapCameraResolutions.get(t);if(!i||!i.length)return!1;for(let t of i)if(t[0]===e.width&&t[1]===e.height)return!0;return!1},r=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let s=null;try{s=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!s)return null;const n=s.getVideoTracks();let o=null;try{const t=n[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=s,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return n.forEach((t=>{t.stop()})),o};if(!this._bOpen){const s=this.videoSettings.video.deviceId;if(!s)return null;if(e=s.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:s.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!e)return null;let n=this._mapCameraResolutions.get(e);if(n&&!t)return this._mapCameraResolutions.get(e);this._mapCameraResolutions.set(e,[]),n=this._mapCameraResolutions.get(e);for(let t of this._predefinedResolutions){const s=await r(e,t.width,t.height);s&&!i(e,s)&&n.push([s.width,s.height])}return n}if(this._currentCamera){e=this._currentCamera.deviceId;let r=this._mapCameraResolutions.get(e);if(r&&!t)return this._mapCameraResolutions.get(e);this._mapCameraResolutions.set(e,[]),r=this._mapCameraResolutions.get(e);const s=this.getConstraints();for(let t of this._predefinedResolutions){await this._videoTrack.applyConstraints({width:{ideal:t.width},height:{ideal:t.height}});const s=this._videoTrack.getSettings(),n={width:s.width,height:s.height};i(e,n)||r.push([n.width,n.height])}return await this._videoTrack.applyConstraints(s),r}return null}on(t,e){if(!e)return;const i=this.mapCameraEvents.get(t.toLowerCase());if(!i)throw new Error(`Event '${t}' does not exist.`);i.includes(e)||i.push(e)}off(t,e){const i=this.mapCameraEvents.get(t.toLowerCase());if(!i)throw new Error(`Event '${t}' does not exist.`);const r=i.indexOf(e);-1!==r&&i.splice(r,1)}offAll(t){if(t){if("string"==typeof t){const e=this.mapCameraEvents.get(t);e&&(e.length=0)}}else for(let t of this.mapCameraEvents.values())t&&(t.length=0)}getVideoSettings(){return JSON.parse(JSON.stringify(this.videoSettings))}updateVideoSettings(t){if(this.videoSettings=JSON.parse(JSON.stringify(t)),this._lastDeviceId=null,this._bOpen)return this.play()}isOpen(){return this._bOpen}getCapabilities(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'applyConstraints()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error('"_videoTrack" is null.');if(!this._videoTrack.applyConstraints)throw Error("Not supported.");return await this._videoTrack.applyConstraints(t)}async turnOnTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOnTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!0}]});throw Error("Not supported.")}async turnOffTorch(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'turnOffTorch()' is unavailable in singleFrameMode.");if(this.getCapabilities().torch)return await this._videoTrack.applyConstraints({advanced:[{torch:!1}]});throw Error("Not supported.")}async setColorTemperature(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setColorTemperature()' is unavailable in singleFrameMode.");let e=this.getCapabilities().colorTemperature;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),await this._videoTrack.applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]})}getColorTemperature(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setExposureCompensation()' is unavailable in singleFrameMode.");let e=this.getCapabilities().exposureCompensation;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),await this._videoTrack.applyConstraints({advanced:[{exposureCompensation:t}]})}getExposureCompensation(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setHardwareScale()' is unavailable in singleFrameMode.");if(t<1)throw new RangeError("Invalid value.");if(!this._videoTrack)return;const e=this.getCapabilities().zoom;if(!e)throw new Error("Not supported.");return te.max&&(t=e.max),t=tt(t,e.min,e.step,e.max),await this._videoTrack.applyConstraints({advanced:[{zoom:t}]}),t}_getHardwareScale(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(t,e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setSoftwareScale()' is unavailable in singleFrameMode.");if(t<1)throw new RangeError("Invalid value.");e&&this._setScaleCenter(e),this._softwareScale=t,this._scaleVideo(t,e)}_getSoftwareScale(){return this._softwareScale}_setScaleCenter(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_setScaleCenter()' is unavailable in singleFrameMode.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid center.");const e=this._video.videoWidth,i=this._video.videoHeight;let r=0,s=0;if(t.x.endsWith("px"))r=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.x)/100*e}if(t.y.endsWith("px"))s=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");s=parseFloat(t.y)/100*i}if(NaN==r||NaN==s)throw new Error("Invalid scale center.");this._scaleCenter={x:r,y:s}}_resetScaleCenter(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_resetScaleCenter()' is unavailable in singleFrameMode.");const t=this._video.videoWidth,e=this._video.videoHeight;this._scaleCenter={x:t/2,y:e/2}}_isVideoCenter(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_isVideoCenter()' is unavailable in singleFrameMode.");return t&&t.x==this._video.videoWidth/2&&t.y==this._video.videoHeight/2}async _setZoom(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(t<1)throw new RangeError("Invalid value.");this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const e=await this._setHardwareScale(t);let i=this._getHardwareScale();1==i&&1!=e&&(i=e),t>i?this._setSoftwareScale(t/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(t)}catch(e){if("Not supported."!==(e.message||e))throw e;this._setSoftwareScale(t)}}async setZoom(t){if("number"!=typeof t&&"object"!=typeof t)throw new TypeError("Illegal type of argument.");if("number"==typeof t)return this._setZoom(t);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setZoom()' is unavailable in singleFrameMode.");if(t){if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid value.");t.centerPoint?this._setScaleCenter(t.centerPoint):this._resetScaleCenter();try{if(this._isVideoCenter(this._scaleCenter)){const e=await this._setHardwareScale(t.factor);let i=this._getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this._setSoftwareScale(t.factor/i):this._setSoftwareScale(1)}else await this._setHardwareScale(1),this._setSoftwareScale(t.factor)}catch(e){if("Not supported."!==(e.message||e))throw e;this._setSoftwareScale(t.factor)}}}getZoom(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?{factor:this._getHardwareScale()*this._softwareScale}:null}async resetZoom(){await this.setZoom({factor:1})}async setFrameRate(t){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFrameRate()' is unavailable in singleFrameMode.");let e=this.getCapabilities().frameRate;if(!e)throw Error("Not supported.");return te.max&&(t=e.max),await this._videoTrack.applyConstraints({width:{ideal:Math.max(this._video.videoWidth,this._video.videoHeight)},frameRate:t})}getFrameRate(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(t,e){if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if("string"!=typeof t)throw Error("Invalid focus mode.");t=t.toLowerCase();const i=this.getCapabilities().focusMode,r=this.getCapabilities().focusDistance;if(!i)throw Error("Not supported.");if(!i.includes(t))throw Error("Unsupported mode.");if(e>=0){if(!r)throw Error("Manual focus unsupported.");return er.max&&(e=r.max),e=tt(e,r.min,r.step,r.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:t,focusDistance:e}]})}return await this._videoTrack.applyConstraints({advanced:[{focusMode:t}]})}async setFocus(t,e){if("string"==typeof t)return this._setFocus(t,e);if(this._assertOpen(),this.singleFrameMode)throw new Error("'setFocus()' is unavailable in singleFrameMode.");if(!t)return;const i=this.getCapabilities(),r=i.focusMode,s=i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw Error("Invalid focus mode.");const n=t.mode.toLowerCase();if(!r.includes(n))throw Error("Unsupported focus mode.");if("manual"!==n)return this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:n}]});if(!s)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let e=t.distance;return es.max&&(e=s.max),e=tt(e,s.min,s.step,s.max),this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:n,focusDistance:e}]})}if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,r=t.area.height;if(!i||!r){const t=this._video.videoWidth,e=this._video.videoHeight;i||(i=2*Math.round(Math.min(t,e)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),r||(r=2*Math.round(Math.min(t,e)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters._focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:r},await this._setLocalFocus(e,i,r)}}getFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const t=this._videoTrack.getSettings().focusMode;return t?"continuous"===t?{mode:t}:{mode:t,distance:this._videoTrack.getSettings().focusDistance}:null}getFocusSettings(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;const t=this._videoTrack.getSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters._focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters._focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async _setFocusAndGetContract(t,e){const i=t=>{if(!this._bOpen||!this._videoTrack||this.video.paused||t.focusTaskId!=this._focusParameters.curFocusTaskId){this._bOpen&&this._videoTrack&&!this.video.paused||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;e=tt(e,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:"manual",focusDistance:e}]}),i(t),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/e),Math.abs(1/this._focusParameters.fds.max-1/e))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/e)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=e,await new Promise((t=>{setTimeout(t,r)})),i(t);let s=t.focusL-t.focusW/2,n=t.focusT-t.focusH/2,o=t.focusW,a=t.focusH;if(s>=this.video.videoWidth||n>=this.video.videoHeight)throw new Error("Invalid area.");s+o>this.video.videoWidth&&(o=this.video.videoWidth-s),n+a>this.video.videoHeight&&(a=this.video.videoHeight-n);const h=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:s,sy:n,sWidth:o,sHeight:a,dWidth:o,dHeight:a},null,{pixelFormat:$.RGBA});if(!h)return this._setFocusAndGetContract(t,e);const l=h.data;let c=0;for(let t=0,e=l.length-8;to&&oc)return await this._doFocusDetail(t,n,o,r,s,l,c)}else{let a=await this._setFocusAndGetContract(t,l);if(o>a)return await this._doFocusDetail(t,n,o,r,s,l,a);if(o==a)return await this._doFocusDetail(t,n,o,l,a);let c=await this._setFocusAndGetContract(t,h);if(c>o&&o{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=tt(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=tt(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=tt(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await this._setFocusAndGetContract(t,n),a=await this._setFocusAndGetContract(t,s),h=await this._setFocusAndGetContract(t,r);if(a>h&&ho&&a>o){let e=await this._setFocusAndGetContract(t,i);const s=await this._doFocusDetail(t,r,h,i,e,n,o);return this._focusParameters.isDoingFocus=0,s}if(a==h&&hh){const e=await this._doFocusDetail(t,r,h,n,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,s)}async enableTapToFocus(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'enableTapToFocus()' is unavailable in singleFrameMode.");if(!this._videoTrack)throw new Error("Video is not playing.");if(!this._focusSupported)throw new Error("Tapping to focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=(await this.getCapabilities()).focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,this._tapFocusEnabled=!1,new Error("Tapping to focus unsupported.");this._tapFocusEnabled=!0}disableTapToFocus(){this._tapFocusEnabled=!1}isTapToFocusEnabled(){return this._tapFocusEnabled}_updateVideoContainerStyle(){if(!this._video)return;if(this.singleFrameMode)return;const t=this._getSoftwareScale(),e=this._videoContainer;if("contain"===this.videoFit&&t>1){const t=this._video.videoWidth,i=this._video.videoHeight,r=window.getComputedStyle(this._elContainer),s=parseFloat(r.width),n=parseFloat(r.height),o=t/i;if(s/na?o/(i/t):n/(r/t));const c=l*(1-1/t)*(i/2-this._scaleCenter.x),u=l*(1-1/t)*(r/2-this._scaleCenter.y);this._video.style.transform=`translate(${c}px, ${u}px) scale(${t})`}this._updateVideoContainerStyle()}}getFrameSize(t,e,i,r){if(!t||!e)return null;let s,n,o,a,h=t,l=e;const c={regionLeft:0,regionTop:0,regionRight:h,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*h/100,c.regionTop=i.regionTop*l/100,c.regionRight=i.regionRight*h/100,c.regionBottom=i.regionBottom*l/100):(c.regionLeft=i.regionLeft,c.regionTop=i.regionTop,c.regionRight=i.regionRight,c.regionBottom=i.regionBottom),s=Math.round(c.regionLeft),n=Math.round(c.regionTop),h=Math.round(c.regionRight-c.regionLeft),l=Math.round(c.regionBottom-c.regionTop)):(s=0,n=0,h=Math.round(h),l=Math.round(l));const u=Math.max(h,l);if(r&&r>0&&u>r){const t=r/u;h>l?(o=r,a=Math.round(l*t)):(o=Math.round(h*t),a=r)}else o=h,a=l;return o<=0||a<=0?null:{sx:s,sy:n,sWidth:h,sHeight:l,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this.singleFrameMode)throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoData()}getImage(){return this.getFrame()}_drawImage(t,e,i,r,s,n,o){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!i||!r)return null;if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let a=0,h=0,l=i,c=r,u=0,d=0,f=i,g=r;s&&(s.sx&&(a=Math.round(s.sx)),s.sy&&(h=Math.round(s.sy)),s.sWidth&&(l=Math.round(s.sWidth)),s.sHeight&&(c=Math.round(s.sHeight)),s.dx&&(u=Math.round(s.dx)),s.dy&&(d=Math.round(s.dy)),s.dWidth&&(f=Math.round(s.dWidth)),s.dHeight&&(g=Math.round(s.dHeight)));let _=$.RGBA;o&&o.pixelFormat&&(_=o.pixelFormat);const p=t;if(o&&o.bUseWebGL){(p.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},r=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},s=(t,e,i)=>{const r=t.createShader(e);if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(r)}.`);throw e.name="WebGLError",e}return r},n="\n attribute vec2 a_position;\n attribute vec2 a_texCoord;\n\n uniform mat3 u_matrix;\n uniform mat3 u_textureMatrix;\n\n varying vec2 v_texCoord;\n void main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\n v_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n }\n ";let o="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(_)&&(o=_.slice(0,3));const a=`\n precision mediump float;\n varying vec2 v_texCoord;\n uniform sampler2D u_image;\n uniform float uColorFactor;\n\n void main() {\n vec4 sample = texture2D(u_image, v_texCoord);\n float grey = 0.21 * sample.r + 0.71 * sample.g + 0.07 * sample.b;\n gl_FragColor = vec4(sample.${o} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n }\n `,h=r(t,[s(t,t.VERTEX_SHADER,n),s(t,t.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:h,attribLocations:{vertexPosition:t.getAttribLocation(h,"a_position"),texPosition:t.getAttribLocation(h,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(h,"u_image"),uColorFactor:t.getUniformLocation(h,"uColorFactor"),uMatrix:t.getUniformLocation(h,"u_matrix"),uTextureMatrix:t.getUniformLocation(h,"u_textureMatrix")}},this._webGLBuffers=e(t),this._webGLTexture=i(t),this.shaderPixelFormat=_}const s=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},o=(t,e,i)=>{const r=t.RGBA,s=t.RGBA,n=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,s,n,i)},m=(t,e,n,o)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),s(t,n.positions,e.attribLocations.vertexPosition),s(t,n.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,o),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[$.GREY,$.GREY32].includes(_)?1:0);let p,m,v=Q.translate(Q.identity(),-1,-1);v=Q.scale(v,2,2),v=Q.scale(v,1/t.canvas.width,1/t.canvas.height),p=Q.translate(v,u,d),p=Q.scale(p,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,p),m=Q.translate(Q.identity(),a/i,h/r),m=Q.scale(m,l/i,c/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,m),t.drawArrays(t.TRIANGLES,0,6)};let v;if(o(t,this._webGLTexture,e),m(t,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),n){if(n.lengthe||r.sy>i||r.sx+r.sWidth>e||r.sy+r.sHeight>i)throw new Error("Invalid position.");if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");const o=Math.round(r.sx),a=Math.round(r.sy),h=Math.round(r.sWidth),l=Math.round(r.sHeight),c=Math.round(r.dWidth),u=Math.round(r.dHeight);let d=$.RGBA;n&&n.pixelFormat&&(d=n.pixelFormat);let f,g,_,p=this._bWebGLSupported;n&&0==n.bUseWebGL&&(p=!1),p?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),f=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),f=this._reusedCvs);try{if(p)if(et._onLog&&et._onLog("DCE: _getImageData() in WebGL."),s)if(d===$.GREY){if(_=new Uint8Array(c*u*4),g=this._drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},_,{pixelFormat:d,bUseWebGL:p}),_=this._transformPixelFormat(_,g.pixelFormat,d),s){if(s.length<_.length)throw new Error("Unexpected size of the 'bufferContainer'.");s.set(_)}}else g=this._drawImage(f,t,e,i,{sx:o,sy:a,sWidth:h,sHeight:l,dWidth:c,dHeight:u},s,{pixelFormat:d,bUseWebGL:p}),_=new Uint8Array(s.buffer,0,c*u*4),_=this._transformPixelFormat(_,g.pixelFormat,d);else d===$.GREY?((!this._tempDataContainer||this._tempDataContainer.length=this.croppingRegions.length||this._croppingRegionIndex<0)throw new Error("The 'croppingRegionIndex' is out of bounds.");t=this.croppingRegions[this._croppingRegionIndex],this.bIncreaseRegionIndexAuto&&++this._croppingRegionIndex>=this.croppingRegions.length&&(this._croppingRegionIndex=0)}return t}_fetchingLoop(t){if(this.isDisposed&&this.disposed)return;if(!this._bOpen||!this.isFetchingLoopStarted())return void this.stopFetchingLoop();const e=()=>{const t=this.getCurrentRegion();let e=this._getVideoData(null,{region:t});if(!e)return void et._onLog;for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(e);const i=this.mapCameraEvents.get("frameaddedtobuffer");for(let t of i)t&&setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this)}),0)},i=()=>{this.isDisposed&&this.disposed||(this._frameLoopTimeoutId2&&clearTimeout(this._frameLoopTimeoutId2),this.refreshInterval<=0||(this._frameLoopTimeoutId2=setTimeout((()=>{this.isDisposed&&this.disposed||(this._bOpen&&this.isFetchingLoopStarted()?(e(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};t&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(e(),i()):0===this.refreshInterval?e():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this.singleFrameMode)throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameQueue.length=0,this._bFetchingLoopStarted=!1,this._recordedStates.fetchingLoopStart=!1)}getFrameFromBuffer(t){return this._frameQueue&&this._frameQueue.length?t?tt.getId()>=0))}getSelectedDrawingItems(){return this._drawingLayersManager.getSelectedDrawingItems()}createDrawingStyle(t){return this._drawingLayersManager.createDrawingStyle(t)}getDrawingStyle(t){return this._drawingLayersManager.getDrawingStyle(t)}getDrawingStyles(){return this._drawingLayersManager.getDrawingStyles()}updateDrawingStyle(t,e){return this._drawingLayersManager.updateDrawingStyle(t,e)}clearDrawingLayers(){const t=this.getDrawingLayers();for(let e of t)this.deleteDrawingLayer(e.getId())}showTip(t,e,i,r,s=3e3,n=!0){this._assertOpen(),this._tipArgs.x=t,this._tipArgs.y=e,this._tipArgs.width=i,this._tipArgs.autoShowSuggestedTip=!!n,this._drawingLayerOfTip||(this._drawingLayerOfTip=this._createDrawingLayer(-1)),this._tipStyleId||(this._tipStyleId=this.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip.clearDrawingItems();const o=new Z(r||"",t,e,i,this._tipStyleId);o._fabricObject.paddingTop=15,o._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e0&&(this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}_hideTip(){this._drawingLayerOfTip&&(this.deleteDrawingLayer(this._drawingLayerOfTip.getId()),this._drawingLayerOfTip=null,this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId))}hideTip(){this._hideTip(),this._tipArgs.x=null,this._tipArgs.y=null,this._tipArgs.width=null,this._tipArgs.autoShowSuggestedTip=null}updateTipMessage(t){if(!this._drawingLayerOfTip)throw new Error("The Tip is not showing.");this._drawingLayerOfTip.getDrawingItems()[0].setAttribute("text",t),this._drawingLayerOfTip.renderAll(),this._tipArgs.duration>0&&(this._hideTipTimeoutId&&clearTimeout(this._hideTipTimeoutId),this._hideTipTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._hideTip()}),this._tipArgs.duration))}suggestTip(t,e){this._tipArgs.autoShowSuggestedTip&&(this._drawingLayerOfTip?this.updateTipMessage(e):void 0!==this._tipArgs.x&&this.showTip(this._tipArgs.x,this._tipArgs.y,this._tipArgs.width,e,this._tipArgs.duration)),this.onTipSuggested&&setTimeout((()=>{this.isDisposed&&this.disposed||this.onTipSuggested.apply(this,[t,e])}),0)}_createControler(){if(this._controler||(this._controler=new q(this)),this._controler)return this._controler}_destroyControler(){this._controler=null}setOriginalImage(t,e,i){if(!t||!e||!i)throw new Error("Invalid arguments");this._originalImageData={imageData:t,width:e,height:i};let r=this._cvsOriginalImage;r||(r=document.createElement("canvas"),r.style.position="absolute",r.style.width="100%",r.style.height="100%",r.style.left="0",r.style.top="0",r.style.backgroundColor="white",r.style.objectFit="contain",this._cvsOriginalImage=r),r.width===e&&r.height===i||(r.width=e,r.height=i);const s=r.getContext("2d");s.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),s.putImageData(new ImageData(t,e,i),0,0)):t instanceof HTMLCanvasElement&&s.drawImage(t,0,0),document.body.contains(r)&&""===r.style.display&&this._updateDrawingLayersSize({width:e,height:i,objectFit:"contain"})}getOriginalImage(){return this._originalImageData?Object.assign({},this._originalImageData):null}async deleteOriginalImage(){await this.hideOriginalImage(),this._cvsOriginalImage&&(this._cvsOriginalImage.remove(),this._cvsOriginalImage=null),this._originalImageData=null}_showOriginalImageCvs(){this._cvsOriginalImage&&"none"==this._cvsOriginalImage.style.display&&(this._cvsOriginalImage.style.display="")}_hideOriginalImageCvs(){this._cvsOriginalImage&&(this._cvsOriginalImage.style.display="none")}showOriginalImage(){if(!this._originalImageData)throw new Error("No original image is set.");const t=this._cvsOriginalImage;if(""===t.style.display&&document.body.contains(t))return;const{width:e,height:i}=this._originalImageData;if(this._updateDrawingLayersSize({width:e,height:i,objectFit:"contain"}),this._bOpen&&(this._video&&!this._video.paused&&this._video.pause(),this._bFetchingLoopStarted&&(this.stopFetchingLoop(),this._recordedStates.fetchingLoopStart=!0),this.ifShowScanRegionMask&&this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this.ifShowScanRegionLaser&&this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none"),this._scanRegionOverlayContainer&&(this._scanRegionOverlayContainer.style.display="none"),this._selCam&&(this._selCam.parentElement.style.display="none")),!document.body.contains(t))if(this._cvsSingleFrameMode)this._cvsSingleFrameMode.after(t);else{if(!this._videoContainer)throw new Error("Unable to find video element");this._videoContainer.after(t)}this._showOriginalImageCvs()}async _hideOriginalImage(t){this._originalImageData&&this._cvsOriginalImage&&"none"!==this._cvsOriginalImage.style.display&&(this._updateDrawingLayersSize(),this._bOpen&&t&&(this._video&&this._recordedStates.videoPlaying&&await this.play(null,null,null,{notTriggerSingleFrameClick:!0}),this._recordedStates.fetchingLoopStart&&!this.singleFrameMode&&this.startFetchingLoop(),this.ifShowScanRegionMask&&this._cvsScanRegion&&this._recordedStates.maskShow&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this._divScanLight&&this._recordedStates.laserShow&&this.showScanRegionLaser(),this._cvsViewDecorator&&this._recordedStates.decoratorShow&&this.showViewDecorator(),this._scanRegionOverlayContainer&&this._recordedStates.overlayShow&&this.showScanRegionOverlays()),this._selCam&&(this._selCam.parentElement.style.display=""),this._hideOriginalImageCvs())}async hideOriginalImage(){return this._hideOriginalImage(!0)}dispose(t){this.UIElement&&(this._uiOriginalState&&this._uiOriginalState.inDom?this.UIElement.style.display=this._uiOriginalState.display:this.UIElement.style.display="none"),this.clearDrawingLayers(),this.close(),this.forceLoseContext(),this.setViewDecorator(null,null),this._scanRegionOverlayContainer&&this._scanRegionOverlayContainer.remove(),this._arrScanRegionOverlays.length=0,t&&this.UIElement&&this.UIElement.remove(),this.__proto__=null;for(let t in this)delete this[t];Object.defineProperty(this,"isCameraEnhancer",{value:!0}),Object.defineProperty(this,"isDisposed",{value:!0}),Object.defineProperty(this,"disposed",{value:!0})}}et._jsVersion="3.3.1",et._jsEditVersion="20230217",et._version="JS "+et._jsVersion+"."+et._jsEditVersion,et.browserInfo=P,et._hasEngineResourceLoaded=!1,et._engineResourcePath=V,et._defaultUIElementURL="@engineResourcePath/dce.ui.html";const it={DT_Arc:class extends U{constructor(t,e,i,r,s,n){super(new R.Circle({left:t,top:e,radius:i,startAngle:r,endAngle:s}),n),this._mediaType="arc"}},DT_Polygon:X,DT_Rect:class extends U{constructor(t,e,i,r,s){super(new R.Rect({left:t,top:e,width:i,height:r}),s)}},DT_Image:class extends U{constructor(t,e,i,r){super(new R.Image(t,{left:e,top:i}),r),this.image=t}_extendSet(t,e){if("image"===t){if(e instanceof HTMLImageElement)return this._fabricObject.setElement(e),this.image=e,!0;if(e instanceof HTMLCanvasElement){const t=new Image;return t.src=e.toDataURL(),this._fabricObject.setElement(t),this.image=e,!0}throw new Error("Unsupported value.")}}_extendGet(t){if("image"===t)return this.image}},DT_Text:Z,DT_Line:class extends X{constructor(t,e,i){super([t,e],i),this._mediaType="line"}_extendSet(t,e){if("startPoint"===t||"endPoint"===t){e="startPoint"===t?[e,this.get("endPoint")]:[this.get("startPoint"),e];const i=this._fabricObject;if(i.group){const t=i.group;i.points=e.map((e=>({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const r=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new R.Control({positionHandler:G,actionHandler:Y(i>0?i-1:r,H),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}_extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let r=t.x-i.pathOffset.x,s=t.y-i.pathOffset.y;const n=R.util.transformPoint({x:r,y:s},i.calcTransformMatrix());e.push({x:n.x,y:n.y})}return"startPoint"===t?e[0]:e[1]}}},DT_Group:class extends U{constructor(t){super(new R.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.styleSelector="selected";const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.styleSelector="default";const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)}))}getChildItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}addChildItem(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}};function rt(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function st(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function nt(t,e,i,r){let s=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),n=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((s^n)>=0&&0!==s&&0!==n)&&(s=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),n=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),!((s^n)>=0&&0!==s&&0!==n))}class ot extends x{constructor(){super(),this._barcodeFillStyle="rgba(254,180,32,0.3)",this._barcodeStrokeStyle="rgba(254,180,32,0.9)",this._barcodeLineWidth=1,this._barcodeFillStyleBeforeVerification="rgba(248,252,0,0.2)",this._barcodeStrokeStyleBeforeVerification="transparent",this._barcodeLineWidthBeforeVerification=2,this.bFilterRegionInJs=!0,this._onCameraSelChange=()=>{},this._onResolutionSelChange=()=>{},this._onCloseBtnClick=()=>{},this._onPlayed=null}static get version(){return this._version+`(DCE ${et.getVersion()})`}static _fireHTTPSWarnning(){ot.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{ot.onWarning&&ot.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return et.testCameraAccess()}_fireResolutionWarning(){if(!this.singleFrameMode&&this.onWarning&&this.dce.isOpen()){const t=this.dce.getConstraints();t&&t.width<1280&&t.height<720&&setTimeout((()=>{this.onWarning&&this.onWarning({id:3,message:"Camera resolution too low, please use a higher resolution (720P or better)."})}),0)}}getUIElement(){return this.dce.getUIElement()}async setUIElement(t){await this.dce.setUIElement(t)}get singleFrameMode(){return this.dce.singleFrameMode}set singleFrameMode(t){this.dce.singleFrameMode=t,t&&(this.dce.ifShowScanRegionLaser=!1,(async()=>{let t=await this.getScanSettings();t.oneDTrustFrameCount=1,await this.updateScanSettings(t)})())}get onUnduplicatedRead(){return this.onUniqueRead}set onUnduplicatedRead(t){this.onUniqueRead=t}get video(){return this.dce&&this.dce.video}set videoSrc(t){this.dce&&(this.dce.videoSrc=t)}get videoSrc(){return this.dce&&this.dce.videoSrc}set onTipSuggested(t){this.dce&&(this.dce.onTipSuggested=t)}get onTipSuggested(){return this.dce&&this.dce.onTipSuggested}_assertOpen(){if(!this.dce.isOpen())throw Error("The scanner is not open.")}set barcodeFillStyle(t){this._barcodeFillStyle=t,this.dce&&this.dce.updateDrawingStyle(3,{fillStyle:t})}get barcodeFillStyle(){return this._barcodeFillStyle}set barcodeStrokeStyle(t){this._barcodeStrokeStyle=t,this.dce&&this.dce.updateDrawingStyle(3,{strokeStyle:t})}get barcodeStrokeStyle(){return this._barcodeStrokeStyle}set barcodeLineWidth(t){this._barcodeLineWidth=t,this.dce&&this.dce.updateDrawingStyle(3,{lineWidth:t})}get barcodeLineWidth(){return this._barcodeLineWidth}set barcodeFillStyleBeforeVerification(t){this._barcodeFillStyleBeforeVerification=t,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{fillStyle:t})}get barcodeFillStyleBeforeVerification(){return this._barcodeFillStyleBeforeVerification}set barcodeStrokeStyleBeforeVerification(t){this._barcodeStrokeStyleBeforeVerification=t,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{strokeStyle:t})}get barcodeStrokeStyleBeforeVerification(){return this._barcodeStrokeStyleBeforeVerification}set barcodeLineWidthBeforeVerification(t){this._barcodeLineWidthBeforeVerification=t,this._styleIdBeforeVerification&&this.dce.updateDrawingStyle(this._styleIdBeforeVerification,{lineWidth:t})}get barcodeLineWidthBeforeVerification(){return this._barcodeLineWidthBeforeVerification}set regionMaskFillStyle(t){this.dce.setScanRegionMaskStyle({fillStyle:t})}get regionMaskFillStyle(){return this.dce.regionMaskFillStyle}set regionMaskStrokeStyle(t){this.dce.setScanRegionMaskStyle({strokeStyle:t})}get regionMaskStrokeStyle(){return this.dce.regionMaskStrokeStyle}set regionMaskLineWidth(t){this.dce.setScanRegionMaskStyle({lineWidth:t})}get regionMaskLineWidth(){return this.dce.regionMaskLineWidth}set region(t){this._region=t,this.dce&&(t?t instanceof Array||this.dce.setScanRegion(t):this.dce.setScanRegion(null)),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}set ifSaveOriginalImageInACanvas(t){this._ifSaveOriginalImageInACanvas=t,this.dce.framePixelFormat=t?"rgba":"grey"}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}async createDCEInstance(){this.dce||(x._onLog&&x._onLog("createDCEInstance()"),et.defaultUIElementURL=null,this.dce=await et.createInstance(),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=it,["iPhone","iPad","Android","HarmonyOS"].includes(x.browserInfo.OS)||this.dce.setResolution(1920,1080),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"}),this.barcodeLineWidth=this._barcodeLineWidth,this.dce.on("cameraChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("resolutionChange",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0})),this.dce.on("cameraClose",(()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1})),this.dce.on("singleFrameAcquired",(async t=>{if(!t)return;if(!t.data)return;let e;this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:i,sx:r,sy:s,width:n,height:o,stride:a,pixelFormat:h,timeStamp:l,_sWidth:c,_sHeight:u}=t,d={timeStamp:l};if("grey"===h)e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_GrayScaled,0,d);else if("rgba"===h)e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_ARGB_8888,0,d)}if(await this.clearMapDecodeRecord(),x.recalculateResultLocation(e,r,s,c,u,n,o),this._drawResults(e),this.onFrameRead&&this.isOpen()&&!this._bPauseScan){let t=this._cloneDecodeResults(e);this.onFrameRead(t)}if(this.onUniqueRead&&this.isOpen()&&!this._bPauseScan)for(let t of e)this.onUniqueRead(t.barcodeText,this._cloneDecodeResults(t))})))}set maxCvsSideLength(t){this._maxCvsSideLength=t,this.dce.maxCvsSideLength=t}get maxCvsSideLength(){return this._maxCvsSideLength}static async createInstance(t){let e=new ot;e._instanceID=await ot.createInstanceInWorker(!0),await e.createDCEInstance(),"string"==typeof t&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return await e.dce.setUIElement(ot.defaultUIElementURL),e.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),ot._fireHTTPSWarnning(),e.singleFrameMode||await e.updateRuntimeSettings("single"),e}async decodeCurrentFrame(t){this._assertOpen();let e=null;t&&t.region&&(e=t.region);const i=this.dce._getVideoData(null,{region:e});return this._decode_DCEFrame(i)}async updateRuntimeSettings(t){let e;if("string"==typeof t)if("speed"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=0,e.localizationModes=[2,0,0,0,0,0,0,0],e.barcodeZoneMinDistanceToImageBorders=9}else if("balance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=512,e.deblurLevel=3,e.localizationModes=[2,16,0,0,0,0,0,0],e.barcodeZoneMinDistanceToImageBorders=9,e.timeout=1e5}else if("coverage"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=512,e.deblurLevel=5,e.scaleDownThreshold=1e5,e.localizationModes=[2,16,4,8,0,0,0,0],e.barcodeZoneMinDistanceToImageBorders=9,e.timeout=1e5}else if("single"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region)}else if("dense"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=0,e.deblurLevel=7,e.scaleDownThreshold=1e5,e.localizationModes=[2,8,0,0,0,0,0,0],e.minResultConfidence=0,e.barcodeZoneMinDistanceToImageBorders=9,e.timeout=1e5}else if("distance"==t){let t=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,e=await this.getRuntimeSettings(),e.barcodeFormatIds=t.barcodeFormatIds,e.barcodeFormatIds_2=t.barcodeFormatIds_2,t.region&&(e.region=t.region),e.expectedBarcodesCount=0,e.scaleDownThreshold=1e5,e.localizationModes=[2,8,0,0,0,0,0,0],e.barcodeZoneMinDistanceToImageBorders=9,e.timeout=1e5}else e=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(e=JSON.parse(JSON.stringify(t)),e.region instanceof Array){let i=t.region;[i.regionLeft,i.regionTop,i.regionLeft,i.regionBottom,i.regionMeasuredByPercentage].some((t=>void 0!==t))&&(e.region={regionLeft:i.regionLeft||0,regionTop:i.regionTop||0,regionRight:i.regionRight||0,regionBottom:i.regionBottom||0,regionMeasuredByPercentage:i.regionMeasuredByPercentage||0})}}if(!x._bUseFullFeature){if(0!=(e.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.BF_DATAMATRIX))||0!=e.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=e.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}{let t=e.region;if(this.bFilterRegionInJs?this.userDefinedRegion=JSON.parse(JSON.stringify(t)):this.userDefinedRegion=null,t instanceof Array)if(t.length){for(let e=0;e{let r=x._nextTaskID++;x._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.updateReturn)}catch(t){i(t)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),x._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(e)}})})),"string"==typeof t&&["speed","balance","coverage","dense","distance"].includes(t)&&(await this.setModeArgument("BinarizationModes",0,"EnableFillBinaryVacancy","1"),await this.setModeArgument("BinarizationModes",0,"BlockSizeX","0"),await this.setModeArgument("BinarizationModes",0,"BlockSizeY","0"))}_bindUI(){if(!this.getUIElement())throw new Error("Need to define `UIElement` before opening.");if(this.dce._bindUI(),!this.dce.video)throw this._unbindUI(),Error("Can not find the video container element with class 'dce-video-container'")}_unbindUI(){this.dce._unbindUI()}set onPlayed(t){this.dce.off("played",this._onPlayed),this._onPlayed=t,this.dce.on("played",this._onPlayed)}get onPlayed(){return this._onPlayed}async getAllCameras(){return this.dce.getAllCameras()}async getCurrentCamera(){return this.dce.getSelectedCamera()}async setCurrentCamera(t){const e=await this.dce.selectCamera(t);return this._fireResolutionWarning(),e}getResolution(){return this.dce.getResolution()}async setResolution(t,e){const i=await this.dce.setResolution(t,e);return this._fireResolutionWarning(),i}getVideoSettings(){return this.dce.getVideoSettings()}updateVideoSettings(t){return this.dce.updateVideoSettings(t)}isOpen(){return this.dce&&this.dce.isOpen()}setVideoFit(t){return this.dce&&this.dce.setVideoFit(t)}getVideoFit(){return this.dce&&this.dce.getVideoFit()}set ifShowScanRegionMask(t){this.dce&&(this.dce.ifShowScanRegionMask=t)}get ifShowScanRegionMask(){return this.dce&&this.dce.ifShowScanRegionMask}set ifSaveLastUsedCamera(t){this.dce&&(this.dce.ifSaveLastUsedCamera=t)}get ifSaveLastUsedCamera(){return this.dce&&this.dce.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){this.dce&&(this.dce.ifSkipCameraInspection=t)}get ifSkipCameraInspection(){return this.dce&&this.dce.ifSkipCameraInspection}stop(){this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.dce.stop(),this.dce.ifShowScanRegionLaser=!1,this.dce.hideViewDecorator(),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}pause(){this.dce.pause()}async play(t,e,i){this.dce.ifShowScanRegionLaser=!0;const r=await this.dce.play(t,e,i);return this._fireResolutionWarning(),r}pauseScan(t){this._assertOpen(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),t&&t.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce.ifShowScanRegionLaser=!1,this.dce.stopFetchingLoop()}resumeScan(){this._assertOpen(),this._bPauseScan=!1,this.dce.ifShowScanRegionLaser=!0}getCapabilities(){return this.dce.getCapabilities()}getCameraSettings(){return this.dce.getCameraSettings()}getConstraints(){return this.dce.getConstraints()}async applyConstraints(t){return this.dce.applyConstraints(t)}async turnOnTorch(){return this.dce.turnOnTorch()}async turnOffTorch(){return this.dce.turnOffTorch()}async setColorTemperature(t){return this.dce.setColorTemperature(t)}getColorTemperature(){return this.dce.getColorTemperature()}async setExposureCompensation(t){return this.dce.setExposureCompensation(t)}getExposureCompensation(){return this.dce.getExposureCompensation()}async setZoom(t){return this.dce.setZoom(t)}getZoomSettings(){return this.dce.getZoomSettings()}resetZoom(){return this.dce.resetZoom()}async setFrameRate(t){return this.dce.setFrameRate(t)}getFrameRate(){return this.dce.getFrameRate()}async setFocus(t,e){return this.dce.setFocus(t,e)}getFocus(){return this.dce.getFocus()}getFocusSettings(){return this.dce.getFocusSettings()}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this.dce.stopFetchingLoop(),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(!this.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce.video||this.dce.video.paused||this._bPauseScan)return x._onLog&&x._onLog("Video or scan is paused. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));x._onLog&&x._onLog("======= once read ======="),x._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return x._onLog&&x._onLog("Get invalid frame."),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{t._bUseWebGL||"grey"!==t.pixelFormat||(this.dce.framePixelFormat="rgba");let e=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{data:i,sx:r,sy:s,width:n,height:o,stride:a,pixelFormat:h,timeStamp:l,_sWidth:c,_sHeight:u}=t,d={timeStamp:l};if("grey"===h)e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_GrayScaled,0,d);else if("rgba"===h)e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);e=await this._decodeBuffer_Uint8Array(i,n,o,a,p.IPF_ARGB_8888,0,d)}if(x.recalculateResultLocation(e,r,s,c,u,n,o),0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(e),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration)),this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan&&(this.autoZoom||this.autoFocus||this.autoSuggestTip))if(e.length)this.autoZoomInFrameArray.length=0,this.autoZoomOutFrameCount=0,this.frameArrayInIdealZoom.length=0,this.suggestTipFrameArray.length=0,this.autoZoom&&this.autoFocus&&(this.nextActionInIdealZoom="focus"),this.autoFocusFrameArray.length=0,this.noIntermediateResultsCount=0;else{const t=await this.getIntermediateResults(),e=(t,e,i,r,s,n,o)=>{let a=n/r,h=o/s;t.x1=t.x1/a+e,t.x2=t.x2/a+e,t.x3=t.x3/a+e,t.x4=t.x4/a+e,t.y1=t.y1/h+i,t.y2=t.y2/h+i,t.y3=t.y3/h+i,t.y4=t.y4/h+i},i=t=>{if(!t)return null;const i={};let a,h,l,d,f;{const t=this.video.videoWidth*(1-this.autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+this.autoZoomDetectionArea)/2,i=e,r=t,s=this.video.videoHeight*(1-this.autoZoomDetectionArea)/2,n=s,o=this.video.videoHeight*(1+this.autoZoomDetectionArea)/2;f={x1:t,x2:e,x3:i,x4:r,y1:s,y2:n,y3:o,y4:o}}const g=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let r=!1;const s=t.length;if(s<=2)return!1;for(let n=0;n0!=st(a.y-i)>0&&st(e-(i-o.y)*(o.x-a.x)/(o.y-a.y)-o.x)<0&&(r=!r)}return r}([{x:e.x1,y:e.y1},{x:e.x2,y:e.y2},{x:e.x3,y:e.y3},{x:e.x4,y:e.y4}],t.x,t.y)},r=(t,e)=>!!(nt([t[0],t[1]],[t[2],t[3]],[e.x1,e.y1],[e.x2,e.y2])||nt([t[0],t[1]],[t[2],t[3]],[e.x2,e.y2],[e.x3,e.y3])||nt([t[0],t[1]],[t[2],t[3]],[e.x3,e.y3],[e.x4,e.y4])||nt([t[0],t[1]],[t[2],t[3]],[e.x4,e.y4],[e.x1,e.y1]));return!!(i({x:t.x1,y:t.y1},e)||i({x:t.x2,y:t.y2},e)||i({x:t.x3,y:t.y3},e)||i({x:t.x4,y:t.y4},e))||(!!(i({x:e.x1,y:e.y1},t)||i({x:e.x2,y:e.y2},t)||i({x:e.x3,y:e.y3},t)||i({x:e.x4,y:e.y4},t))||!!(r([e.x1,e.y1,e.x2,e.y2],t)||r([e.x2,e.y2,e.x3,e.y3],t)||r([e.x3,e.y3,e.x4,e.y4],t)||r([e.x4,e.y4,e.x1,e.y1],t)))},_=[];for(let i of t){if(i.resultType!==S.IRT_TYPED_BARCODE_ZONE)continue;const t=i.scaleDownRatio;for(let a of i.results){if(!a)continue;const i={x1:a.x1=a.x1*t,x2:a.x2=a.x2*t,x3:a.x3=a.x3*t,x4:a.x4=a.x4*t,y1:a.y1=a.y1*t,y2:a.y2=a.y2*t,y3:a.y4=a.y3*t,y4:a.y4=a.y4*t};e(i,r,s,c,u,n,o),g(f,i)&&_.push(a)}}const p=(t=>{if(!t||!t.length)return null;const e=t=>{const e=(t.x1+t.x2+t.x3+t.x4)/4,i=(t.y1+t.y2+t.y3+t.y4)/4;return(e-n/2)*(e-n/2)+(i-o/2)*(i-o/2)};let i,r=t.filter((t=>t.barcodeFormat==y.BF_QR_CODE||t.barcodeFormat==y.BF_DATAMATRIX));if(r.length||(r=t.filter((t=>t.barcodeFormat==y.BF_ONED)),r.length||(r=t)),!r.length)return null;i=r[0];let s=e(i);if(1!=r.length)for(let t=1;t1.1*i.confidence?(i=r[t],s=n):r[t].confidence>.9*i.confidence&&n!0===t)).length>=this.suggestTipFrameLimit[1]){this.suggestTipFrameArray.length=0;const t=a.x3-a.x1,e=a.y3-a.y1;a.result.moduleSizee?t>n*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):t>.6*n&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."):t<=e&&(e>o*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):e>.6*o&&Math.max(this.video.videoWidth,this.video.videoHeight)<=1280&&Math.min(this.video.videoWidth,this.video.videoHeight)<=720&&this.dce&&this.dce.suggestTip("low-resolution","Please use a higher resolution."))}if(this.autoZoom){const t=this.autoZoomIdealArea[1];let i=(1-this.autoZoomTargetBorder)/2;const h=a.x1/c,l=(c-a.x3)/c,d=a.y1/u,f=(u-a.y3)/u;if(h>t&&l>t&&d>t&&f>t&&a.result.moduleSize{}))),this.autoZoomInFrameArray.filter((t=>!0===t)).length>=this.autoZoomInFrameLimit[1]){this.autoZoomInFrameArray.length=0;const t=[(.5-i)/(.5-h),(.5-i)/(.5-l),(.5-i)/(.5-d),(.5-i)/(.5-f)].filter((t=>t>0)),e=Math.min(...t,this.autoZoomInIdealModuleSize/a.result.moduleSize),r=this.dce.getZoomSettings().factor;let s=Math.max(Math.pow(r*e,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);s=Math.min(s,e);const n=r*s;await this.setZoom({factor:n}),this.dce.clearFrameBuffer()}}else if(this.autoZoomInFrameArray.length=0,this.frameArrayInIdealZoom.push(!0),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.frameArrayInIdealZoom.filter((t=>!0===t)).length>=this.frameLimitInIdealZoom[1])if(this.frameArrayInIdealZoom.length=0,"focus"===this.nextActionInIdealZoom&&this.autoFocus){e(a,r,s,c,u,n,o);try{await this.setFocus({mode:"manual",area:{centerPoint:{x:(a.x1+a.x3)/2+"px",y:(a.y1+a.y3)/2+"px"},width:a.x3-a.x1+"px",height:a.y3-a.y1+"px"}})}catch(t){}this.dce.clearFrameBuffer(),this.nextActionInIdealZoom="zoomOut"}else{if("zoomOut"!==this.nextActionInIdealZoom&&this.autoFocus)throw new Error("Invalid action.");if(this.enableZoomOutInIdealZoom){i=this.autoZoomIdealArea[1]+this.autoZoomOutStepRate_2;const t=[(.5-i)/(.5-h),(.5-i)/(.5-l),(.5-i)/(.5-d),(.5-i)/(.5-f)].filter((t=>t>0));let e=Math.min(...t)*this.dce.getZoomSettings().factor;await this.setZoom({factor:e}),this.dce.clearFrameBuffer(),this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((t=>{})))}}}else if(this.autoFocus&&(this.autoFocusFrameArray.push(!0),this.autoFocusFrameArray.splice(0,this.autoFocusFrameArray.length-this.autoFocusFrameLimit[0]),this.autoFocusFrameArray.filter((t=>!0===t)).length>=this.autoFocusFrameLimit[1])){this.autoFocusFrameArray.length=0;try{e(a,r,s,c,u,n,o),await this.setFocus({mode:"manual",area:{centerPoint:{x:(a.x1+a.x3)/2+"px",y:(a.y1+a.y3)/2+"px"},width:a.x3-a.x1+"px",height:a.y3-a.y1+"px"}})}catch(t){}this.dce.clearFrameBuffer()}}else if(this.noIntermediateResultsCount++,this.suggestTipFrameArray.push(!1),this.autoZoom){if(this.autoZoomInFrameArray.push(!1),this.autoZoomInFrameArray.splice(0,this.autoZoomInFrameArray.length-this.autoZoomInFrameLimit[0]),this.autoZoomOutFrameCount++,this.frameArrayInIdealZoom.push(!1),this.frameArrayInIdealZoom.splice(0,this.frameArrayInIdealZoom.length-this.frameLimitInIdealZoom[0]),this.autoZoomOutFrameCount>=this.autoZoomOutFrameLimit){this.autoZoomOutFrameCount=0;const t=this.getZoomSettings().factor;if(t>this.autoZoomOutMinValue){const e=Math.max((t-1)*this.autoZoomOutStepRate,this.autoZoomOutMinStep),i=Math.max(t-e,this.autoZoomOutMinValue);await this.setZoom({factor:i}),this.dce.clearFrameBuffer()}}this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((t=>{})))}else this.autoFocus&&(this.autoFocusFrameArray.length=0,this.setFocus({mode:"continuous"}).catch((t=>{})))}return e})().then((t=>{if(x._onLog&&x._onLog(t),this.captureAndDecodeInParallel){let t=this.array_decodeFrameTimeCost,e=this.array_getFrameTimeCost,i=this._indexCurrentDecodingFrame;const r=()=>{let r=0;if(this.region instanceof Array){let s=0,n=0;s=i+1>=this.region.length?0:i+1,n=s+1>=this.region.length?0:s+1,r=t[s]&&t[s].length&&e[n]&&e[n].length?Math.min(...t[s])-Math.max(...e[n]):0}else if(e&&e.length){let i=Math.min(...t),s=Math.max(...e);i&&s&&(r=i-s)}else r=0;return r>0?r:0};(()=>{if(this.region instanceof Array){for(t[i]&&t[i]instanceof Array||(t[i]=[]);t[i].length>=5;)t[i].shift();t[i].push(this._lastInnerDecodeDuration)}else{for(;t.length>=5;)t.shift();t.push(this._lastInnerDecodeDuration)}})(),this._intervalGetVideoFrame=r()+this.intervalTime,x._onLog&&x._onLog("Next fetching frame loop interval: "+this._intervalGetVideoFrame)}if(this.isOpen()&&this.dce.video&&!this.dce.video.paused&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&t.length){let e=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?e=t.some((t=>t.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(e=t.some((t=>0==t.resultState))),e&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&t.length){let e=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?e=t.some((t=>t.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(e=t.some((t=>0==t.resultState))),e)try{navigator.vibrate(this.vibrateDuration)}catch(t){console.warn("Vibration not allowed. User interaction required: "+(t.message||t))}}if(this.onFrameRead){t=t.filter((t=>t.resultState>=0));const e=this._cloneDecodeResults(t);this.onFrameRead(e)}if(this.onUniqueRead){t=t.filter((t=>0==t.resultState));const e=this._cloneDecodeResults(t);for(let t of e)this.onUniqueRead(t.barcodeText,t)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()}))}_getVideoFrame(){if(!this.dce)return null;let t;if(this.captureAndDecodeInParallel){x._onLog&&x._onLog("Get frame in parallel.");let e=this.dce.isFetchingLoopStarted();if(this.dce.loopInterval=this._intervalGetVideoFrame,e||this.dce.startFetchingLoop(),!this.dce.numberOfFramesInBuffer)return this.dce.loopInterval=0,null;t=this.dce.getFrameFromBuffer();const i=t=>{if(!t)return;let e=t.timeSpent,i=this.array_getFrameTimeCost;for(;i.length>=5;)i.shift();i.push(e)};i(t)}else x._onLog&&x._onLog("Get frame in serial."),this.dce.stopFetchingLoop(),t=this.dce.getFrame();return t}async open(){this._bindUI();const t=await this.dce.open();return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),t}async openVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const t=await this.dce.open();return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),t}close(){this.dce.close(),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}async show(){this._bindUI();const t=await this.dce.open(!0);return this._bPauseScan=!1,this.singleFrameMode||(this.dce&&(this.dce.ifShowScanRegionLaser=!0),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),t}async showVideo(){this._bindUI(),this.dce.ifShowScanRegionLaser=!1;const t=await this.dce.open(!0);return this._bPauseScan=!0,this.singleFrameMode||(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0)),this._fireResolutionWarning(),t}hide(){this.dce.close(!0),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId)}showTip(t,e,i,r,s=3e3,n=!0){this.dce&&this.dce.showTip(t,e,i,r,s,n)}hideTip(){this.dce&&this.dce.hideTip()}updateTipMessage(t){this.dce&&this.dce.updateTipMessage(t)}async enableTapToFocus(){this.dce&&this.dce.enableTapToFocus()}disableTapToFocus(){this.dce&&this.dce.disableTapToFocus()}isTapToFocusEnabled(){return this.dce.isTapToFocusEnabled()}transformCoord(t){if(!this.isOpen())throw new Error("Unavailable when the camera is not open.");if(this.singleFrameMode&&!this.dce._cvsSingleFrameMode)throw new Error("No image is selected. ");const e=this.dce._elContainer.getBoundingClientRect();let i,r,s,n,o,a=e.left,h=e.top,l=a+window.scrollX,c=h+window.scrollY;this.singleFrameMode?(i=this.dce._cvsSingleFrameMode.width,r=this.dce._cvsSingleFrameMode.height,s=parseFloat(window.getComputedStyle(this.dce._cvsSingleFrameMode).width),n=parseFloat(window.getComputedStyle(this.dce._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,r=this.video.videoHeight,s=parseFloat(window.getComputedStyle(this.dce._elContainer).width),n=parseFloat(window.getComputedStyle(this.dce._elContainer).height),o=this.getVideoFit());const u=s/n,d=i/r;let f,g,_,p,m=1;if("contain"===o)u=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,n.ctx.currentTime);for(var r=0;r=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,u()),e},codecs:function(e){return(this||n)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||n;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||n,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var r=t.canPlayType("audio/mpeg;").replace(/^no$/,""),o=e._navigator?e._navigator.userAgent:"",i=o.match(/OPR\/([0-6].)/g),a=i&&parseInt(i[0].split("/")[1],10)<33,s=-1!==o.indexOf("Safari")&&-1===o.indexOf("Chrome"),_=o.match(/Version\/(.*?) /),d=s&&_&&parseInt(_[1],10)<15;return e._codecs={mp3:!(a||!r&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!r,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||n;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(n){for(;e._html5AudioPool.length0?s._seek:r._sprite[e][0]/1e3),u=Math.max(0,(r._sprite[e][0]+r._sprite[e][1])/1e3-d),l=1e3*u/Math.abs(s._rate),c=r._sprite[e][0]/1e3,h=(r._sprite[e][0]+r._sprite[e][1])/1e3;s._sprite=e,s._ended=!1;var m=function(){s._paused=!1,s._seek=d,s._start=c,s._stop=h,s._loop=!(!s._loop&&!r._sprite[e][2])};if(!(d>=h)){var A=s._node;if(r._webAudio){var g=function(){r._playLock=!1,m(),r._refreshBuffer(s);var e=s._muted||r._muted?0:s._volume;A.gain.setValueAtTime(e,n.ctx.currentTime),s._playStart=n.ctx.currentTime,void 0===A.bufferSource.start?s._loop?A.bufferSource.noteGrainOn(0,d,86400):A.bufferSource.noteGrainOn(0,d,u):s._loop?A.bufferSource.start(0,d,86400):A.bufferSource.start(0,d,u),l!==1/0&&(r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),l)),t||setTimeout((function(){r._emit("play",s._id),r._loadQueue()}),0)};"running"===n.state&&"interrupted"!==n.ctx.state?g():(r._playLock=!0,r.once("resume",g),r._clearTimer(s._id))}else{var f=function(){A.currentTime=d,A.muted=s._muted||r._muted||n._muted||A.muted,A.volume=s._volume*n.volume(),A.playbackRate=s._rate;try{var o=A.play();if(o&&"undefined"!=typeof Promise&&(o instanceof Promise||"function"==typeof o.then)?(r._playLock=!0,m(),o.then((function(){r._playLock=!1,A._unlocked=!0,t?r._loadQueue():r._emit("play",s._id)})).catch((function(){r._playLock=!1,r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),s._ended=!0,s._paused=!0}))):t||(r._playLock=!1,m(),r._emit("play",s._id)),A.playbackRate=s._rate,A.paused)return void r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||s._loop?r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),l):(r._endTimers[s._id]=function(){r._ended(s),A.removeEventListener("ended",r._endTimers[s._id],!1)},A.addEventListener("ended",r._endTimers[s._id],!1))}catch(e){r._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===A.src&&(A.src=r._src,A.load());var p=window&&window.ejecta||!A.readyState&&n._navigator.isCocoonJS;if(A.readyState>=3||p)f();else{r._playLock=!0,r._state="loading";var E=function(){r._state="loaded",f(),A.removeEventListener(n._canPlayEvent,E,!1)};A.addEventListener(n._canPlayEvent,E,!1),r._clearTimer(s._id)}}return s._id}r._ended(s)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var n=t._getSoundIds(e),r=0;r=0?t=parseInt(i[0],10):e=parseFloat(i[0])}else i.length>=2&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(r=t?o._soundById(t):o._sounds[0])?r._volume:0;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"volume",action:function(){o.volume.apply(o,i)}}),o;void 0===t&&(o._volume=e),t=o._getSoundIds(t);for(var _=0;_0?r/d:r),l=Date.now();e._fadeTo=n,e._interval=setInterval((function(){var o=(Date.now()-l)/r;l=Date.now(),s+=_*o,s=Math.round(100*s)/100,s=_<0?Math.max(n,s):Math.min(n,s),a._webAudio?e._volume=s:a.volume(s,e._id,!0),i&&(a._volume=s),(nt&&s>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit("fade",e._id))}),u)},_stopFade:function(e){var t=this,r=t._soundById(e);return r&&r._interval&&(t._webAudio&&r._node.gain.cancelScheduledValues(n.ctx.currentTime),clearInterval(r._interval),r._interval=null,t.volume(r._fadeTo,e),r._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,n,r=this,o=arguments;if(0===o.length)return r._loop;if(1===o.length){if("boolean"!=typeof o[0])return!!(n=r._soundById(parseInt(o[0],10)))&&n._loop;e=o[0],r._loop=e}else 2===o.length&&(e=o[0],t=parseInt(o[1],10));for(var i=r._getSoundIds(t),a=0;a=0?t=parseInt(i[0],10):e=parseFloat(i[0])}else 2===i.length&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if("number"!=typeof e)return(r=o._soundById(t))?r._rate:o._rate;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"rate",action:function(){o.rate.apply(o,i)}}),o;void 0===t&&(o._rate=e),t=o._getSoundIds(t);for(var _=0;_=0?t=parseInt(o[0],10):r._sounds.length&&(t=r._sounds[0]._id,e=parseFloat(o[0]))}else 2===o.length&&(e=parseFloat(o[0]),t=parseInt(o[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==r._state||r._playLock))return r._queue.push({event:"seek",action:function(){r.seek.apply(r,o)}}),r;var s=r._soundById(t);if(s){if(!("number"==typeof e&&e>=0)){if(r._webAudio){var _=r.playing(t)?n.ctx.currentTime-s._playStart:0,d=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(d+_*Math.abs(s._rate))}return s._node.currentTime}var u=r.playing(t);u&&r.pause(t,!0),s._seek=e,s._ended=!1,r._clearTimer(t),r._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var l=function(){u&&r.play(t,!0),r._emit("seek",t)};if(u&&!r._webAudio){var c=function(){r._playLock?setTimeout(c,0):l()};setTimeout(c,0)}else l()}return r},playing:function(e){var t=this;if("number"==typeof e){var n=t._soundById(e);return!!n&&!n._paused}for(var r=0;r=0&&n._howls.splice(o,1);var a=!0;for(r=0;r=0){a=!1;break}return i&&a&&delete i[e._src],n.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,n,r){var o=this["_on"+e];return"function"==typeof t&&o.push(r?{id:n,fn:t,once:r}:{id:n,fn:t}),this},off:function(e,t,n){var r=this,o=r["_on"+e],i=0;if("number"==typeof t&&(n=t,t=null),t||n)for(i=0;i=0;i--)o[i].id&&o[i].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,n)}.bind(r,o[i].fn),0),o[i].once&&r.off(e,o[i].fn,o[i].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action()}return t},_ended:function(e){var t=this,r=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(n<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),n--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],n=0;n=0;if(!e.bufferSource)return this;if(n._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=n._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(n._navigator&&n._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var o=function(e){this._parent=e,this.init()};o.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++n._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,r=n._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),e._node.gain.setValueAtTime(r,n.ctx.currentTime),e._node.paused=!0,e._node.connect(n.masterGain)):n.noAudio||(e._node=n._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(n._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=r*n.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++n._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(n._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var i={},a=function(e){var t=e._src;if(i[t])return e._duration=i[t].duration,void d(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),r=new Uint8Array(n.length),o=0;o0?(i[t._src]=e,d(t,e)):r()};"undefined"!=typeof Promise&&1===n.ctx.decodeAudioData.length?n.ctx.decodeAudioData(e).then(o).catch(r):n.ctx.decodeAudioData(e,o,r)},d=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},u=function(){if(n.usingWebAudio){try{"undefined"!=typeof AudioContext?n.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?n.ctx=new webkitAudioContext:n.usingWebAudio=!1}catch(e){n.usingWebAudio=!1}n.ctx||(n.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(n._navigator&&n._navigator.platform),t=n._navigator&&n._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),r=t?parseInt(t[1],10):null;if(e&&r&&r<9){var o=/safari/.test(n._navigator&&n._navigator.userAgent.toLowerCase());n._navigator&&!o&&(n.usingWebAudio=!1)}n.usingWebAudio&&(n.masterGain=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),n.masterGain.gain.setValueAtTime(n._muted?0:n._volume,n.ctx.currentTime),n.masterGain.connect(n.ctx.destination)),n._setup()}};!function(e,t,n,r){var o;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var n=t._howls.length-1;n>=0;n--)t._howls[n].stereo(e);return t},e.prototype.pos=function(e,n,r){var o=this;return o.ctx&&o.ctx.listener?(n="number"!=typeof n?o._pos[1]:n,r="number"!=typeof r?o._pos[2]:r,"number"!=typeof e?o._pos:(o._pos=[e,n,r],void 0!==o.ctx.listener.positionX?(o.ctx.listener.positionX.setTargetAtTime(o._pos[0],t.ctx.currentTime,.1),o.ctx.listener.positionY.setTargetAtTime(o._pos[1],t.ctx.currentTime,.1),o.ctx.listener.positionZ.setTargetAtTime(o._pos[2],t.ctx.currentTime,.1)):o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},e.prototype.orientation=function(e,n,r,o,i,a){var s=this;if(!s.ctx||!s.ctx.listener)return s;var _=s._orientation;return n="number"!=typeof n?_[1]:n,r="number"!=typeof r?_[2]:r,o="number"!=typeof o?_[3]:o,i="number"!=typeof i?_[4]:i,a="number"!=typeof a?_[5]:a,"number"!=typeof e?_:(s._orientation=[e,n,r,o,i,a],void 0!==s.ctx.listener.forwardX?(s.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),s.ctx.listener.forwardY.setTargetAtTime(n,t.ctx.currentTime,.1),s.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),s.ctx.listener.upX.setTargetAtTime(o,t.ctx.currentTime,.1),s.ctx.listener.upY.setTargetAtTime(i,t.ctx.currentTime,.1),s.ctx.listener.upZ.setTargetAtTime(a,t.ctx.currentTime,.1)):s.ctx.listener.setOrientation(e,n,r,o,i,a),s)},n.prototype.init=(o=n.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],o.call(this,e)}),n.prototype.stereo=function(e,n){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,n)}}),r;var o=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===n){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var a=r._getSoundIds(n),s=0;s{let e=!1;if(E)try{(await A.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===g.browser&&g.version>66||"Safari"===g.browser&&g.version>13||"OPR"===g.browser&&g.version>43||"Edge"===g.browser&&g.version;const R=(()=>{if(!l&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),T=" is not allowed to change after `createInstance` or `loadWasm` is called.",D=!l&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",S=!l&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",C=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let t=0;te&&"object"==typeof e&&"function"==typeof e.then;class B extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(w(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,w(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const n=await t;e===this._task&&this.resolve(n)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}const b=["iPhone","iPad","Android","HarmonyOS"].includes(g.OS)?2048:4096;class N{constructor(){this._instanceID=void 0,this._ifSaveOriginalImageInACanvas=!1,this.oriCanvas=null,this.oriCanvasData=null,this.canvas=null,this.bFilterRegionInJs=!1,this._region=null,this._timeStartDecode=null,this._timeEnterInnerDBR=null,this._timeGetMessage=null,this.decodeRecords={},this.bDestroyed=!1,this._lastErrorCode=0,this._lastErrorString="",this._lastInnerDecodeDuration=0,this.intervalTime=0,this._intervalGetVideoFrame=0,this.array_getFrameTimeCost=[],this.array_decodeFrameTimeCost=[],this._indexCurrentDecodingFrame=0,this._arrPolygons=[],this._bPauseScan=!1,this._intervalDetectVideoPause=1e3,this._soundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",this.beepSound=new r({src:["data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=b,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+T);n._license=t})(N,e)}static get productKeys(){return this._license}static set productKeys(e){N.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){N.license=e}static get organizationID(){return this._license}static set organizationID(e){N.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+T);n._sessionPassword=t})(N,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:f,worker:p,getUserMedia:E,camera:await I(),browser:g.browser,version:g.version,OS:g.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");N._engineResourcePath=(e=>{if(null==e&&(e="./"),!l){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+T);n._licenseServer=C(t)})(N,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+T);n._deviceFriendlyName=t||""})(N,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");N.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&(("colorMode"in e||"pixelFormat"in e)&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=N._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",N.engineResourcePath)}static set defaultUIElementURL(e){N._defaultUIElementURL=e}static _fireHTTPSWarnning(){N.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{N.onWarning&&N.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new r({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;N._onLog&&N._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const n=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{n?n===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else n||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let t=await this._decode_DCEFrame(e,{bCopyData:!1}),n=null;if(t&&t.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;n=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),N.recalculateResultLocation(n,r,o,s,_,i,a)}if(this._drawResults(n,t),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(N._onLog&&N._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!N.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:n,sp:r,rmk:o}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,n,r=t._license||"",o=JSON.parse(JSON.stringify(t._licenseServer)),i=t._sessionPassword,a=0;if(r.startsWith("t")||r.startsWith("f"))a=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))a=1;else{a=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t;try{let e=r.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===o.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),o=C(e)}!i&&t.sessionPassword&&(i=t.sessionPassword),e=t.remark}("200001"===r||r.startsWith("200001-"))&&(o&&o.length||(r="")),r||(a=1)}if(a&&(globalThis.crypto||(n="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(n="Require https to use online key in this browser.")),n){if(1!==a)throw new Error(n);a=0,console.warn(n),t._lastErrorCode=-1,t._lastErrorString=n}return 1===a&&(r="",console.warn("Applying for a public trial license ...")),{lt:a,l:r,ls:o,sp:i,rmk:e}}throw new Error("Can't preprocess license again"+T)})(N);this._pLoad.task=async(i,a)=>{let s=N.engineResourcePath+N._workerName;N.engineResourcePath.startsWith(location.origin)||(s=await fetch(s).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),N._dbrWorker=new Worker(s),N._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},N._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":N._onLog&&N._onLog(n.message);break;case"load":{n.message&&(n.message=n.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0,n.message||(n.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),n.success?(N._dbrWorker.onerror=null,N._version=n.version+"(JS "+N._jsVersion+"."+N._jsEditVersion+")",N._onLog&&N._onLog("load dbr worker success"),n.message&&console.warn(n.message)):(t=new Error(n.message),t.stack=n.stack+"\n"+t.stack,t.ltsErrorCode=n.ltsErrorCode,r||111==n.ltsErrorCode&&-1!=n.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&N.showDialog(n.success?"warn":"error",n.message),n.success?i():a(t);break}case"task":{let e=n.id,t=n.body;try{N._taskCallbackMap.get(e)(t),N._taskCallbackMap.delete(e)}catch(t){throw N._taskCallbackMap.delete(e),t}break}default:N._onLog&&N._onLog(t)}},N._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:N.engineResourcePath,bUseFullFeature:N._bUseFullFeature,bd:N._bWasmDebug,v:N._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:g,fn:N.deviceFriendlyName,ls:n,sp:r,rmk:o})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,n)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let o=await r.text();if(!o.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let i=document.createElement("div");i.innerHTML=o;let a=[];for(let e=0;e{if(e==t.target){s.remove();for(let e of a)e.remove()}}));else if(!d&&e.classList.contains("dls-license-icon-close"))d=e,e.addEventListener("click",(()=>{s.remove();for(let e of a)e.remove()}));else if(!u&&e.classList.contains("dls-license-icon-error"))u=e,"error"!=t&&e.remove();else if(!l&&e.classList.contains("dls-license-icon-warn"))l=e,"warn"!=t&&e.remove();else if(!c&&e.classList.contains("dls-license-msg-content")){c=e;let t=n;for(;t;){let n=t.indexOf("["),r=t.indexOf("]",n),o=t.indexOf("(",r),i=t.indexOf(")",o);if(-1==n||-1==r||-1==o||-1==i){e.appendChild(new Text(t));break}n>0&&e.appendChild(new Text(t.substring(0,n)));let a=document.createElement("a"),s=t.substring(n+1,r);a.innerText=s;let _=t.substring(o+1,i);a.setAttribute("href",_),a.setAttribute("target","_blank"),e.appendChild(a),t=t.substring(i+1)}}document.body.appendChild(s)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await N.loadWasm(),await new Promise(((t,n)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),N._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new N;return e._instanceID=await N.createInstanceInWorker(),N._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){N._onLog&&N._onLog("decode(source: any)"),N._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):N.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):N.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,n,r,o,i,a){return await new Promise(((s,_)=>{let d=N._nextTaskID++;N._taskCallbackMap.set(d,(e=>{if(e.success){let t,n=N._onLog?Date.now():0;N._onLog&&N._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return _(e)}if(N._onLog){let e=Date.now();N._onLog("DBR getting message from worker timestamp: "+n),N._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),N._onLog("From DBR entering worker to returning message from worker costs: "+(n-this._timeEnterInnerDBR)),N._onLog("Handling results from DBR worker costs: "+(e-n)),N._onLog("Total decoding image costs: "+(e-this._timeStartDecode))}return s(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,_(t)}})),this._timeEnterInnerDBR=Date.now(),N._onLog&&N._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),N._dbrWorker.postMessage({type:"decodeBuffer",id:d,instanceID:this._instanceID,body:{buffer:e,width:t,height:n,stride:r,format:o,orientation:i,config:a}},[e.buffer]),N._onLog&&a&&a.timeStamp&&N._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-a.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,r,o,i,a){N._onLog&&N._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const s=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,n)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(s),t,n,r,o,i,a)}async decodeBuffer(e,t,n,r,o,i,a){let s;return N._onLog&&N._onLog("decodeBuffer(buffer,width,height,stride,format)"),N._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?s=await this._decodeBuffer_Uint8Array(e,t,n,r,o,i,a):e instanceof ArrayBuffer?s=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,n,r,o,i,a):e instanceof Blob&&(s=await this._decodeBuffer_Blob(e,t,n,r,o,i,a)),s}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,n)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return n(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),N._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success){let t=JSON.parse(n.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"getRuntimeSettings",id:n,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let n;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=3,n.expectedBarcodesCount=0,n.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=5,n.expectedBarcodesCount=512,n.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=9,n.expectedBarcodesCount=0,n.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=3,n.expectedBarcodesCount=0,n.localizationModes=[2,8,0,0,0,0,0,0]}else n=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(n=JSON.parse(JSON.stringify(t)),n.region instanceof Array){let e=n.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(n.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!N._bUseFullFeature){if(0!=(n.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=n.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=n.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=n.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,n.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(n.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,t)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(n=>{if(n.success){try{this._handleRetJsonString(n.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(n)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=b,await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"resetRuntimeSettings",id:n,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=b,await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!N._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!N._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,n)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){n(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),N._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){N._onLog&&N._onLog("_decode_Blob(blob: Blob)");let n=null,r=null;if("undefined"!=typeof createImageBitmap)try{n=await createImageBitmap(e)}catch(e){}n||(r=await function(e){return new Promise(((t,n)=>{let r=URL.createObjectURL(e),o=new Image;o.dbrObjUrl=r,o.src=r,o.onload=()=>{t(o)},o.onerror=e=>{n(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let o=await this._decode_Image(n||r,t);return n&&n.close(),o}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){N._onLog&&N._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let n,r,o=e instanceof HTMLImageElement?e.naturalWidth:e.width,i=e instanceof HTMLImageElement?e.naturalHeight:e.height,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d",{willReadFrequently:!0}));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(s,t)}async _decode_Canvas(t,n){if(N._onLog&&N._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let r=(t.ctx2d||t.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(r,t.width,t.height,4*t.width,e.EnumImagePixelFormat.IPF_ABGR_8888,0,n)}async _decode_Video(e,t){if(N._onLog&&N._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let n,r,o=e.videoWidth,i=e.videoHeight,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d",{willReadFrequently:!0}));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),await this._decode_Canvas(s,t)}async _decode_DCEFrame(t,n){if(N._onLog&&N._onLog("_decode_DCEFrame(dceFrame)"),!N.isDCEFrame(t))return[];let r=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:o,height:i,colorMode:a,pixelFormat:s,stride:_,timeStamp:d}=t;let u;u=n&&n.bCopyData?new Uint8Array(t.data):t.data;let l=null;if(n?(l=JSON.parse(JSON.stringify(n)),l.timeStamp=d):l={timeStamp:d},s&&_)if("grey"===s)r=await this._decodeBuffer_Uint8Array(u,o,i,_,e.EnumImagePixelFormat.IPF_GrayScaled,0,l);else if("rgba"===s)r=await this._decodeBuffer_Uint8Array(u,o,i,_,e.EnumImagePixelFormat.IPF_ABGR_8888,0,l);else{if("bgra"!==s)throw new Error(`Pixel format '${s}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(u,o,i,_,e.EnumImagePixelFormat.IPF_ARGB_8888,0,l)}else if("grey"===a)r=await this._decodeBuffer_Uint8Array(u,o,i,o,e.EnumImagePixelFormat.IPF_GrayScaled,0,l);else if("rgba"===a)r=await this._decodeBuffer_Uint8Array(u,o,i,4*o,e.EnumImagePixelFormat.IPF_ABGR_8888,0,l);else{if("bgra"!==a)throw new Error(`Color mode '${a}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(u,o,i,4*o,e.EnumImagePixelFormat.IPF_ARGB_8888,0,l)}return r}async _decode_DSImage(t,n){if(N._onLog&&N._onLog("_decode_DSImage(dsImage)"),!N.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(n,t)}}async _decode_FilePath(e,t){throw N._onLog&&N._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,n,r,o,i,a){if(e.length>0)for(let s of e){let e=s.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*i,e.x2*=.01*i,e.x3*=.01*i,e.x4*=.01*i,e.y1*=.01*a,e.y2*=.01*a,e.y3*=.01*a,e.y4*=.01*a);let _=i/r,d=a/o;e.x1=e.x1/_+t,e.x2=e.x2/_+t,e.x3=e.x3/_+t,e.x4=e.x4/_+t,e.y1=e.y1/d+n,e.y2=e.y2/d+n,e.y3=e.y3/d+n,e.y4=e.y4/d+n,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/o,e.y2*=100/o,e.y3*=100/o,e.y4*=100/o)}}static BarcodeReaderException(t,n){let r,o=e.EnumErrorCode.DBR_UNKNOWN;return"number"==typeof t?(o=t,r=new Error(n)):r=new Error(t),r.code=o,r}_handleRetJsonString(t){let n=e.EnumErrorCode;if(t.textResults){for(let e=0;e{let n=t.indexOf(":");e[t.substring(0,n)]=t.substring(n+1)})),n.exception=e}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!N._setWarnnedEx.has(t.description)&&(N._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==n.DBR_SUCCESS)return t.data;throw N.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,n,r){return await new Promise(((o,i)=>{let a=N._nextTaskID++;N._taskCallbackMap.set(a,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return i(e)}return o()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),N._dbrWorker.postMessage({type:"setModeArgument",id:a,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n,argumentValue:r}})}))}async getModeArgument(e,t,n){return await new Promise(((r,o)=>{let i=N._nextTaskID++;N._taskCallbackMap.set(i,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return o(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),N._dbrWorker.postMessage({type:"getModeArgument",id:i,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),n=[];for(let r of t)if(r.dataType==e.EnumIMResultDataType.IMRDT_IMAGE)for(let t of r.results){const r=t.bytes;let o;switch(N._onLog&&N._onLog(" "+r.length+" "+r.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case e.EnumImagePixelFormat.IPF_ABGR_8888:o=new Uint8ClampedArray(r);break;case e.EnumImagePixelFormat.IPF_RGB_888:{const e=r.length/3;o=new Uint8ClampedArray(4*e);for(let t=0;t=n)break;o[a]=o[a+1]=o[a+2]=(128&e)/128*255,o[a+3]=255,e<<=1}}break}default:console.warn("unknow intermediate image",t)}if(!o)continue;let i=new ImageData(o,t.width,t.height),a=document.createElement("canvas");a.width=t.width,a.height=t.height,a.getContext("2d").putImageData(i,0,0),n.push(a)}return n}async getScanSettings(){return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success){let t=n.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t.autoZoom=this.autoZoom,t.autoFocus=this.autoFocus,t.autoSuggestTip=this.autoSuggestTip,e(t)}{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),N._dbrWorker.postMessage({type:"getScanSettings",id:n,instanceID:this._instanceID})}))}async updateScanSettings(t){if(!t)return;const n=JSON.parse(JSON.stringify(t));if(n.autoZoom||n.autoFocus||n.autoSuggestTip){if(!N._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const t=await this.getRuntimeSettings();t.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(t)}return n.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(n.intervalTime,0),delete n.intervalTime),n.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=n.whenToPlaySoundforSuccessfulRead,delete n.whenToPlaySoundforSuccessfulRead),n.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=n.soundOnSuccessfullRead,delete n.soundOnSuccessfullRead),n.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=n.whenToVibrateforSuccessfulRead,delete n.whenToVibrateforSuccessfulRead),n.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=n.vibrateDuration,delete n.vibrateDuration),n.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=n.captureAndDecodeInParallel,delete n.captureAndDecodeInParallel),n.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=n.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=n.autoZoom,delete n.autoZoom),n.hasOwnProperty("autoFocus")&&(this.autoFocus=n.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete n.autoFocus),n.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=n.autoSuggestTip,delete n.autoFocus),await new Promise(((e,t)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),N._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:n}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let n of e)t.push(this._cloneDecodeResults(n));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return N._onLog&&N._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));N._onLog&&N._onLog("======= once read ======="),N._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!N.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return N._onLog&&N._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n=[];if(e){n=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(n&&n.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;t=n.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),N.recalculateResultLocation(t,r,o,s,_,i,a)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t,n),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else t&&(n=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return n})().then((e=>{if(N._onLog&&N._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const n=()=>{let n=0;if(t&&t.length){let r=Math.min(...e),o=Math.max(...t);r&&o&&(n=r-o)}else n=0;return n>0?n:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=n()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),N._onLog&&N._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(N._onLog&&N._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)};t(e)}else N._onLog&&N._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e,t){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const n=this._dbrDrawingLayer;e||(e=[]);let r=this._arrPolygons;for(let o=0;o{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(t),t}stopScanning(e){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[e]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(e){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(N._onLog&&N._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let e=N._nextTaskID++;N._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),N._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}var P,F,V,x,k,U,G,H,K,W,Z,Y,Q,J,X,j,q,z,$,ee,te,ne,re,oe,ie,ae;N._jsVersion="9.6.10",N._jsEditVersion="20230213",N._version=`loading...(JS ${N._jsVersion}.${N._jsEditVersion})`,N._license=D,N._sessionPassword=S,N.browserInfo=g,N._workerName=`dbr-${N._jsVersion}.browser.worker.js`,N._engineResourcePath=R,N._licenseServer=[],N._deviceFriendlyName="",N._isShowRelDecodeTimeInResults=!1,N._bWasmDebug=!1,N._bNeverShowDialog=!1,N.__bUseFullFeature=!0,N._nextTaskID=0,N._taskCallbackMap=new Map,N._pLoad=new B,N._lastErrorCode=0,N._lastErrorString="",N._setWarnnedEx=new Set,N._defaultUIElementURL="@engineResourcePath/dbr.ui.html",e.EnumBarcodeColourMode=void 0,(P=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[P.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",P[P.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",P[P.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",P[P.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",P[P.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",P[P.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",P[P.BICM_SKIP=0]="BICM_SKIP",P[P.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(F=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[F.BCM_AUTO=1]="BCM_AUTO",F[F.BCM_GENERAL=2]="BCM_GENERAL",F[F.BCM_SKIP=0]="BCM_SKIP",F[F.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(V=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[V.BF2_NULL=0]="BF2_NULL",V[V.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",V[V.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",V[V.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",V[V.BF2_POSTNET=2097152]="BF2_POSTNET",V[V.BF2_PLANET=4194304]="BF2_PLANET",V[V.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",V[V.BF2_RM4SCC=16777216]="BF2_RM4SCC",V[V.BF2_DOTCODE=2]="BF2_DOTCODE",V[V.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",V[V.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",V[V.BF2_PHARMACODE=12]="BF2_PHARMACODE",V[V.BF2_ALL=4294967295]="BF2_ALL",e.EnumBinarizationMode=void 0,(x=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[x.BM_AUTO=1]="BM_AUTO",x[x.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",x[x.BM_SKIP=0]="BM_SKIP",x[x.BM_THRESHOLD=4]="BM_THRESHOLD",x[x.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(k=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[k.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(U=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[U.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(G=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[G.CCM_AUTO=1]="CCM_AUTO",G[G.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",G[G.CCM_SKIP=0]="CCM_SKIP",G[G.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(H=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[H.CICM_GENERAL=1]="CICM_GENERAL",H[H.CICM_SKIP=0]="CICM_SKIP",H[H.CICM_REV=2147483648]="CICM_REV",e.EnumConflictMode=void 0,(K=e.EnumConflictMode||(e.EnumConflictMode={}))[K.CM_IGNORE=1]="CM_IGNORE",K[K.CM_OVERWRITE=2]="CM_OVERWRITE",e.EnumDeblurMode=void 0,(W=e.EnumDeblurMode||(e.EnumDeblurMode={}))[W.DM_SKIP=0]="DM_SKIP",W[W.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",W[W.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",W[W.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",W[W.DM_SMOOTHING=8]="DM_SMOOTHING",W[W.DM_MORPHING=16]="DM_MORPHING",W[W.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",W[W.DM_SHARPENING=64]="DM_SHARPENING",W[W.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",W[W.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(Z=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[Z.DRM_AUTO=1]="DRM_AUTO",Z[Z.DRM_GENERAL=2]="DRM_GENERAL",Z[Z.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",Z[Z.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",Z[Z.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",Z[Z.DRM_SKIP=0]="DRM_SKIP",Z[Z.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(Y=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[Y.DPMCRM_AUTO=1]="DPMCRM_AUTO",Y[Y.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",Y[Y.DPMCRM_SKIP=0]="DPMCRM_SKIP",Y[Y.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(Q=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[Q.GTM_INVERTED=1]="GTM_INVERTED",Q[Q.GTM_ORIGINAL=2]="GTM_ORIGINAL",Q[Q.GTM_SKIP=0]="GTM_SKIP",Q[Q.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(J=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[J.IPM_AUTO=1]="IPM_AUTO",J[J.IPM_GENERAL=2]="IPM_GENERAL",J[J.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",J[J.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",J[J.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",J[J.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",J[J.IPM_SKIP=0]="IPM_SKIP",J[J.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(X=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[X.IRSM_MEMORY=1]="IRSM_MEMORY",X[X.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",X[X.IRSM_BOTH=4]="IRSM_BOTH",e.EnumLocalizationMode=void 0,(j=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[j.LM_SKIP=0]="LM_SKIP",j[j.LM_AUTO=1]="LM_AUTO",j[j.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",j[j.LM_LINES=8]="LM_LINES",j[j.LM_STATISTICS=4]="LM_STATISTICS",j[j.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",j[j.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",j[j.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",j[j.LM_CENTRE=128]="LM_CENTRE",j[j.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",j[j.LM_REV=2147483648]="LM_REV",e.EnumPDFReadingMode=void 0,(q=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[q.PDFRM_RASTER=1]="PDFRM_RASTER",q[q.PDFRM_AUTO=2]="PDFRM_AUTO",q[q.PDFRM_VECTOR=4]="PDFRM_VECTOR",q[q.PDFRM_REV=2147483648]="PDFRM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,(z=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[z.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",z[z.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",z[z.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",z[z.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,($=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[$.RPM_AUTO=1]="RPM_AUTO",$[$.RPM_GENERAL=2]="RPM_GENERAL",$[$.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",$[$.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",$[$.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",$[$.RPM_SKIP=0]="RPM_SKIP",$[$.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(ee=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[ee.RCT_PIXEL=1]="RCT_PIXEL",ee[ee.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,(te=e.EnumResultType||(e.EnumResultType={}))[te.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",te[te.RT_RAW_TEXT=1]="RT_RAW_TEXT",te[te.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",te[te.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(ne=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[ne.SUM_AUTO=1]="SUM_AUTO",ne[ne.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",ne[ne.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",ne[ne.SUM_SKIP=0]="SUM_SKIP",ne[ne.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(re=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[re.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",re[re.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",re[re.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",re[re.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",re[re.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",re[re.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(oe=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[oe.TFM_AUTO=1]="TFM_AUTO",oe[oe.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",oe[oe.TFM_SKIP=0]="TFM_SKIP",oe[oe.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(ie=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[ie.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",ie[ie.TROM_POSITION=2]="TROM_POSITION",ie[ie.TROM_FORMAT=4]="TROM_FORMAT",ie[ie.TROM_SKIP=0]="TROM_SKIP",ie[ie.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(ae=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[ae.TDM_AUTO=1]="TDM_AUTO",ae[ae.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",ae[ae.TDM_SKIP=0]="TDM_SKIP",ae[ae.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=N,Object.defineProperty(e,"__esModule",{value:!0})})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.DBR={}))}(this,(function(e){"use strict";var t=function(){this.init()};t.prototype={init:function(){var e=this||n;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var t=this||n;if(e=parseFloat(e),t.ctx||u(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,n.ctx.currentTime);for(var r=0;r=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,u()),e},codecs:function(e){return(this||n)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||n;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||n,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var r=t.canPlayType("audio/mpeg;").replace(/^no$/,""),o=e._navigator?e._navigator.userAgent:"",i=o.match(/OPR\/([0-6].)/g),a=i&&parseInt(i[0].split("/")[1],10)<33,s=-1!==o.indexOf("Safari")&&-1===o.indexOf("Chrome"),_=o.match(/Version\/(.*?) /),d=s&&_&&parseInt(_[1],10)<15;return e._codecs={mp3:!(a||!r&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!r,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(t.canPlayType('audio/wav; codecs="1"')||t.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(t.canPlayType("audio/x-m4b;")||t.canPlayType("audio/m4b;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(d||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||n;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var t=function(n){for(;e._html5AudioPool.length0?s._seek:r._sprite[e][0]/1e3),u=Math.max(0,(r._sprite[e][0]+r._sprite[e][1])/1e3-d),l=1e3*u/Math.abs(s._rate),c=r._sprite[e][0]/1e3,h=(r._sprite[e][0]+r._sprite[e][1])/1e3;s._sprite=e,s._ended=!1;var m=function(){s._paused=!1,s._seek=d,s._start=c,s._stop=h,s._loop=!(!s._loop&&!r._sprite[e][2])};if(!(d>=h)){var A=s._node;if(r._webAudio){var g=function(){r._playLock=!1,m(),r._refreshBuffer(s);var e=s._muted||r._muted?0:s._volume;A.gain.setValueAtTime(e,n.ctx.currentTime),s._playStart=n.ctx.currentTime,void 0===A.bufferSource.start?s._loop?A.bufferSource.noteGrainOn(0,d,86400):A.bufferSource.noteGrainOn(0,d,u):s._loop?A.bufferSource.start(0,d,86400):A.bufferSource.start(0,d,u),l!==1/0&&(r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),l)),t||setTimeout((function(){r._emit("play",s._id),r._loadQueue()}),0)};"running"===n.state&&"interrupted"!==n.ctx.state?g():(r._playLock=!0,r.once("resume",g),r._clearTimer(s._id))}else{var f=function(){A.currentTime=d,A.muted=s._muted||r._muted||n._muted||A.muted,A.volume=s._volume*n.volume(),A.playbackRate=s._rate;try{var o=A.play();if(o&&"undefined"!=typeof Promise&&(o instanceof Promise||"function"==typeof o.then)?(r._playLock=!0,m(),o.then((function(){r._playLock=!1,A._unlocked=!0,t?r._loadQueue():r._emit("play",s._id)})).catch((function(){r._playLock=!1,r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),s._ended=!0,s._paused=!0}))):t||(r._playLock=!1,m(),r._emit("play",s._id)),A.playbackRate=s._rate,A.paused)return void r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||s._loop?r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),l):(r._endTimers[s._id]=function(){r._ended(s),A.removeEventListener("ended",r._endTimers[s._id],!1)},A.addEventListener("ended",r._endTimers[s._id],!1))}catch(e){r._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===A.src&&(A.src=r._src,A.load());var p=window&&window.ejecta||!A.readyState&&n._navigator.isCocoonJS;if(A.readyState>=3||p)f();else{r._playLock=!0,r._state="loading";var E=function(){r._state="loaded",f(),A.removeEventListener(n._canPlayEvent,E,!1)};A.addEventListener(n._canPlayEvent,E,!1),r._clearTimer(s._id)}}return s._id}r._ended(s)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var n=t._getSoundIds(e),r=0;r=0?t=parseInt(i[0],10):e=parseFloat(i[0])}else i.length>=2&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(r=t?o._soundById(t):o._sounds[0])?r._volume:0;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"volume",action:function(){o.volume.apply(o,i)}}),o;void 0===t&&(o._volume=e),t=o._getSoundIds(t);for(var _=0;_0?r/d:r),l=Date.now();e._fadeTo=n,e._interval=setInterval((function(){var o=(Date.now()-l)/r;l=Date.now(),s+=_*o,s=Math.round(100*s)/100,s=_<0?Math.max(n,s):Math.min(n,s),a._webAudio?e._volume=s:a.volume(s,e._id,!0),i&&(a._volume=s),(nt&&s>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit("fade",e._id))}),u)},_stopFade:function(e){var t=this,r=t._soundById(e);return r&&r._interval&&(t._webAudio&&r._node.gain.cancelScheduledValues(n.ctx.currentTime),clearInterval(r._interval),r._interval=null,t.volume(r._fadeTo,e),r._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,t,n,r=this,o=arguments;if(0===o.length)return r._loop;if(1===o.length){if("boolean"!=typeof o[0])return!!(n=r._soundById(parseInt(o[0],10)))&&n._loop;e=o[0],r._loop=e}else 2===o.length&&(e=o[0],t=parseInt(o[1],10));for(var i=r._getSoundIds(t),a=0;a=0?t=parseInt(i[0],10):e=parseFloat(i[0])}else 2===i.length&&(e=parseFloat(i[0]),t=parseInt(i[1],10));if("number"!=typeof e)return(r=o._soundById(t))?r._rate:o._rate;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"rate",action:function(){o.rate.apply(o,i)}}),o;void 0===t&&(o._rate=e),t=o._getSoundIds(t);for(var _=0;_=0?t=parseInt(o[0],10):r._sounds.length&&(t=r._sounds[0]._id,e=parseFloat(o[0]))}else 2===o.length&&(e=parseFloat(o[0]),t=parseInt(o[1],10));if(void 0===t)return 0;if("number"==typeof e&&("loaded"!==r._state||r._playLock))return r._queue.push({event:"seek",action:function(){r.seek.apply(r,o)}}),r;var s=r._soundById(t);if(s){if(!("number"==typeof e&&e>=0)){if(r._webAudio){var _=r.playing(t)?n.ctx.currentTime-s._playStart:0,d=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(d+_*Math.abs(s._rate))}return s._node.currentTime}var u=r.playing(t);u&&r.pause(t,!0),s._seek=e,s._ended=!1,r._clearTimer(t),r._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var l=function(){u&&r.play(t,!0),r._emit("seek",t)};if(u&&!r._webAudio){var c=function(){r._playLock?setTimeout(c,0):l()};setTimeout(c,0)}else l()}return r},playing:function(e){var t=this;if("number"==typeof e){var n=t._soundById(e);return!!n&&!n._paused}for(var r=0;r=0&&n._howls.splice(o,1);var a=!0;for(r=0;r=0){a=!1;break}return i&&a&&delete i[e._src],n.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,n,r){var o=this["_on"+e];return"function"==typeof t&&o.push(r?{id:n,fn:t,once:r}:{id:n,fn:t}),this},off:function(e,t,n){var r=this,o=r["_on"+e],i=0;if("number"==typeof t&&(n=t,t=null),t||n)for(i=0;i=0;i--)o[i].id&&o[i].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,n)}.bind(r,o[i].fn),0),o[i].once&&r.off(e,o[i].fn,o[i].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action()}return t},_ended:function(e){var t=this,r=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(n<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),n--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],n=0;n=0;if(!e.bufferSource)return this;if(n._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=n._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(n._navigator&&n._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var o=function(e){this._parent=e,this.init()};o.prototype={init:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++n._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,r=n._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),e._node.gain.setValueAtTime(r,n.ctx.currentTime),e._node.paused=!0,e._node.connect(n.masterGain)):n.noAudio||(e._node=n._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(n._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=r*n.volume(),e._node.load()),e},reset:function(){var e=this,t=e._parent;return e._muted=t._muted,e._loop=t._loop,e._volume=t._volume,e._rate=t._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++n._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,t=e._parent;t._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(t._sprite).length&&(t._sprite={__default:[0,1e3*t._duration]}),"loaded"!==t._state&&(t._state="loaded",t._emit("load"),t._loadQueue()),e._node.removeEventListener(n._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var i={},a=function(e){var t=e._src;if(i[t])return e._duration=i[t].duration,void d(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),r=new Uint8Array(n.length),o=0;o0?(i[t._src]=e,d(t,e)):r()};"undefined"!=typeof Promise&&1===n.ctx.decodeAudioData.length?n.ctx.decodeAudioData(e).then(o).catch(r):n.ctx.decodeAudioData(e,o,r)},d=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},u=function(){if(n.usingWebAudio){try{"undefined"!=typeof AudioContext?n.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?n.ctx=new webkitAudioContext:n.usingWebAudio=!1}catch(e){n.usingWebAudio=!1}n.ctx||(n.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(n._navigator&&n._navigator.platform),t=n._navigator&&n._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),r=t?parseInt(t[1],10):null;if(e&&r&&r<9){var o=/safari/.test(n._navigator&&n._navigator.userAgent.toLowerCase());n._navigator&&!o&&(n.usingWebAudio=!1)}n.usingWebAudio&&(n.masterGain=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),n.masterGain.gain.setValueAtTime(n._muted?0:n._volume,n.ctx.currentTime),n.masterGain.connect(n.ctx.destination)),n._setup()}};!function(e,t,n,r){var o;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var n=t._howls.length-1;n>=0;n--)t._howls[n].stereo(e);return t},e.prototype.pos=function(e,n,r){var o=this;return o.ctx&&o.ctx.listener?(n="number"!=typeof n?o._pos[1]:n,r="number"!=typeof r?o._pos[2]:r,"number"!=typeof e?o._pos:(o._pos=[e,n,r],void 0!==o.ctx.listener.positionX?(o.ctx.listener.positionX.setTargetAtTime(o._pos[0],t.ctx.currentTime,.1),o.ctx.listener.positionY.setTargetAtTime(o._pos[1],t.ctx.currentTime,.1),o.ctx.listener.positionZ.setTargetAtTime(o._pos[2],t.ctx.currentTime,.1)):o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},e.prototype.orientation=function(e,n,r,o,i,a){var s=this;if(!s.ctx||!s.ctx.listener)return s;var _=s._orientation;return n="number"!=typeof n?_[1]:n,r="number"!=typeof r?_[2]:r,o="number"!=typeof o?_[3]:o,i="number"!=typeof i?_[4]:i,a="number"!=typeof a?_[5]:a,"number"!=typeof e?_:(s._orientation=[e,n,r,o,i,a],void 0!==s.ctx.listener.forwardX?(s.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),s.ctx.listener.forwardY.setTargetAtTime(n,t.ctx.currentTime,.1),s.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),s.ctx.listener.upX.setTargetAtTime(o,t.ctx.currentTime,.1),s.ctx.listener.upY.setTargetAtTime(i,t.ctx.currentTime,.1),s.ctx.listener.upZ.setTargetAtTime(a,t.ctx.currentTime,.1)):s.ctx.listener.setOrientation(e,n,r,o,i,a),s)},n.prototype.init=(o=n.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],o.call(this,e)}),n.prototype.stereo=function(e,n){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,n)}}),r;var o=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===n){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var a=r._getSoundIds(n),s=0;s{let e=!1;if(E)try{(await A.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===g.browser&&g.version>66||"Safari"===g.browser&&g.version>13||"OPR"===g.browser&&g.version>43||"Edge"===g.browser&&g.version;const R=(()=>{if(!l&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),T=" is not allowed to change after `createInstance` or `loadWasm` is called.",D=!l&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",S=!l&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",C=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let t=0;te&&"object"==typeof e&&"function"==typeof e.then;class B extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(w(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,w(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const n=await t;e===this._task&&this.resolve(n)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}const b=["iPhone","iPad","Android","HarmonyOS"].includes(g.OS)?2048:4096;class N{constructor(){this._instanceID=void 0,this._ifSaveOriginalImageInACanvas=!1,this.oriCanvas=null,this.oriCanvasData=null,this.canvas=null,this.bFilterRegionInJs=!1,this._region=null,this._timeStartDecode=null,this._timeEnterInnerDBR=null,this._timeGetMessage=null,this.decodeRecords={},this.bDestroyed=!1,this._lastErrorCode=0,this._lastErrorString="",this._lastInnerDecodeDuration=0,this.intervalTime=0,this._intervalGetVideoFrame=0,this.array_getFrameTimeCost=[],this.array_decodeFrameTimeCost=[],this._indexCurrentDecodingFrame=0,this._arrPolygons=[],this._bPauseScan=!1,this._intervalDetectVideoPause=1e3,this._soundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",this.beepSound=new r({src:["data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=b,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+T);n._license=t})(N,e)}static get productKeys(){return this._license}static set productKeys(e){N.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){N.license=e}static get organizationID(){return this._license}static set organizationID(e){N.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+T);n._sessionPassword=t})(N,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:f,worker:p,getUserMedia:E,camera:await I(),browser:g.browser,version:g.version,OS:g.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");N._engineResourcePath=(e=>{if(null==e&&(e="./"),!l){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+T);n._licenseServer=C(t)})(N,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+T);n._deviceFriendlyName=t||""})(N,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");N.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&(("colorMode"in e||"pixelFormat"in e)&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=N._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",N.engineResourcePath)}static set defaultUIElementURL(e){N._defaultUIElementURL=e}static _fireHTTPSWarnning(){N.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{N.onWarning&&N.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new r({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;N._onLog&&N._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const n=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{n?n===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else n||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let t=await this._decode_DCEFrame(e,{bCopyData:!1}),n=null;if(t&&t.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;n=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),N.recalculateResultLocation(n,r,o,s,_,i,a)}if(this._drawResults(n,t),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(N._onLog&&N._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!N.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:n,sp:r,rmk:o}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,n,r=t._license||"",o=JSON.parse(JSON.stringify(t._licenseServer)),i=t._sessionPassword,a=0;if(r.startsWith("t")||r.startsWith("f"))a=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))a=1;else{a=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t;try{let e=r.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===o.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),o=C(e)}!i&&t.sessionPassword&&(i=t.sessionPassword),e=t.remark}("200001"===r||r.startsWith("200001-"))&&(o&&o.length||(r="")),r||(a=1)}if(a&&(globalThis.crypto||(n="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(n="Require https to use online key in this browser.")),n){if(1!==a)throw new Error(n);a=0,console.warn(n),t._lastErrorCode=-1,t._lastErrorString=n}return 1===a&&(r="",console.warn("Applying for a public trial license ...")),{lt:a,l:r,ls:o,sp:i,rmk:e}}throw new Error("Can't preprocess license again"+T)})(N);this._pLoad.task=async(i,a)=>{let s=N.engineResourcePath+N._workerName;N.engineResourcePath.startsWith(location.origin)||(s=await fetch(s).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),N._dbrWorker=new Worker(s),N._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},N._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":N._onLog&&N._onLog(n.message);break;case"load":{n.message&&(n.message=n.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0,n.message||(n.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),n.success?(N._dbrWorker.onerror=null,N._version=n.version+"(JS "+N._jsVersion+"."+N._jsEditVersion+")",N._onLog&&N._onLog("load dbr worker success"),n.message&&console.warn(n.message)):(t=new Error(n.message),t.stack=n.stack+"\n"+t.stack,t.ltsErrorCode=n.ltsErrorCode,r||111==n.ltsErrorCode&&-1!=n.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&N.showDialog(n.success?"warn":"error",n.message),n.success?i():a(t);break}case"task":{let e=n.id,t=n.body;try{N._taskCallbackMap.get(e)(t),N._taskCallbackMap.delete(e)}catch(t){throw N._taskCallbackMap.delete(e),t}break}default:N._onLog&&N._onLog(t)}},N._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:N.engineResourcePath,bUseFullFeature:N._bUseFullFeature,bd:N._bWasmDebug,v:N._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:g,cv:N.authCacheVersion,fn:N.deviceFriendlyName,ls:n,sp:r,rmk:o})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,n)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let o=await r.text();if(!o.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let i=document.createElement("div");i.innerHTML=o;let a=[];for(let e=0;e{if(e==t.target){s.remove();for(let e of a)e.remove()}}));else if(!d&&e.classList.contains("dls-license-icon-close"))d=e,e.addEventListener("click",(()=>{s.remove();for(let e of a)e.remove()}));else if(!u&&e.classList.contains("dls-license-icon-error"))u=e,"error"!=t&&e.remove();else if(!l&&e.classList.contains("dls-license-icon-warn"))l=e,"warn"!=t&&e.remove();else if(!c&&e.classList.contains("dls-license-msg-content")){c=e;let t=n;for(;t;){let n=t.indexOf("["),r=t.indexOf("]",n),o=t.indexOf("(",r),i=t.indexOf(")",o);if(-1==n||-1==r||-1==o||-1==i){e.appendChild(new Text(t));break}n>0&&e.appendChild(new Text(t.substring(0,n)));let a=document.createElement("a"),s=t.substring(n+1,r);a.innerText=s;let _=t.substring(o+1,i);a.setAttribute("href",_),a.setAttribute("target","_blank"),e.appendChild(a),t=t.substring(i+1)}}document.body.appendChild(s)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await N.loadWasm(),await new Promise(((t,n)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),N._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new N;return e._instanceID=await N.createInstanceInWorker(),N._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){N._onLog&&N._onLog("decode(source: any)"),N._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):N.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):N.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,n,r,o,i,a){return await new Promise(((s,_)=>{let d=N._nextTaskID++;N._taskCallbackMap.set(d,(e=>{if(e.success){let t,n=N._onLog?Date.now():0;N._onLog&&N._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return _(e)}if(N._onLog){let e=Date.now();N._onLog("DBR getting message from worker timestamp: "+n),N._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),N._onLog("From DBR entering worker to returning message from worker costs: "+(n-this._timeEnterInnerDBR)),N._onLog("Handling results from DBR worker costs: "+(e-n)),N._onLog("Total decoding image costs: "+(e-this._timeStartDecode))}return s(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,_(t)}})),this._timeEnterInnerDBR=Date.now(),N._onLog&&N._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),N._dbrWorker.postMessage({type:"decodeBuffer",id:d,instanceID:this._instanceID,body:{buffer:e,width:t,height:n,stride:r,format:o,orientation:i,config:a}},[e.buffer]),N._onLog&&a&&a.timeStamp&&N._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-a.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,r,o,i,a){N._onLog&&N._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const s=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,n)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(s),t,n,r,o,i,a)}async decodeBuffer(e,t,n,r,o,i,a){let s;return N._onLog&&N._onLog("decodeBuffer(buffer,width,height,stride,format)"),N._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?s=await this._decodeBuffer_Uint8Array(e,t,n,r,o,i,a):e instanceof ArrayBuffer?s=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,n,r,o,i,a):e instanceof Blob&&(s=await this._decodeBuffer_Blob(e,t,n,r,o,i,a)),s}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,n)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return n(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),N._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success){let t=JSON.parse(n.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"getRuntimeSettings",id:n,instanceID:this._instanceID})}))}async updateRuntimeSettings(t){let n;if("string"==typeof t)if("speed"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=3,n.expectedBarcodesCount=0,n.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=5,n.expectedBarcodesCount=512,n.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region}else if("dense"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=9,n.expectedBarcodesCount=0,n.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==t){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,n=await this.getRuntimeSettings(),n.barcodeFormatIds=e.barcodeFormatIds,n.barcodeFormatIds_2=e.barcodeFormatIds_2,n.region=e.region,n.deblurLevel=3,n.expectedBarcodesCount=0,n.localizationModes=[2,8,0,0,0,0,0,0]}else n=JSON.parse(t);else{if("object"!=typeof t)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(n=JSON.parse(JSON.stringify(t)),n.region instanceof Array){let e=n.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(n.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!N._bUseFullFeature){if(0!=(n.barcodeFormatIds&~(e.EnumBarcodeFormat.BF_ONED|e.EnumBarcodeFormat.BF_QR_CODE|e.EnumBarcodeFormat.BF_PDF417|e.EnumBarcodeFormat.BF_DATAMATRIX))||0!=n.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=n.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=n.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,n.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(n.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,t)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(n=>{if(n.success){try{this._handleRetJsonString(n.updateReturn)}catch(e){t(e)}return e()}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(n)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=b,await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"resetRuntimeSettings",id:n,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=b,await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!N._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!N._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,n)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){n(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),N._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){N._onLog&&N._onLog("_decode_Blob(blob: Blob)");let n=null,r=null;if("undefined"!=typeof createImageBitmap)try{n=await createImageBitmap(e)}catch(e){}n||(r=await function(e){return new Promise(((t,n)=>{let r=URL.createObjectURL(e),o=new Image;o.dbrObjUrl=r,o.src=r,o.onload=()=>{t(o)},o.onerror=e=>{n(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let o=await this._decode_Image(n||r,t);return n&&n.close(),o}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){N._onLog&&N._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let n,r,o=e instanceof HTMLImageElement?e.naturalWidth:e.width,i=e instanceof HTMLImageElement?e.naturalHeight:e.height,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d",{willReadFrequently:!0}));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(s,t)}async _decode_Canvas(t,n){if(N._onLog&&N._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if(0===t.width||0===t.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=t,this.oriCanvasData=null);let r=(t.ctx2d||t.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,t.width,t.height).data;return await this._decodeBuffer_Uint8Array(r,t.width,t.height,4*t.width,e.EnumImagePixelFormat.IPF_ABGR_8888,0,n)}async _decode_Video(e,t){if(N._onLog&&N._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let n,r,o=e.videoWidth,i=e.videoHeight,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d",{willReadFrequently:!0}));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),await this._decode_Canvas(s,t)}async _decode_DCEFrame(t,n){if(N._onLog&&N._onLog("_decode_DCEFrame(dceFrame)"),!N.isDCEFrame(t))return[];let r=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,colorMode:t.colorMode,pixelFormat:t.pixelFormat,data:new Uint8Array(t.data),toCanvas:t.toCanvas});const{width:o,height:i,colorMode:a,pixelFormat:s,stride:_,timeStamp:d}=t;let u;u=n&&n.bCopyData?new Uint8Array(t.data):t.data;let l=null;if(n?(l=JSON.parse(JSON.stringify(n)),l.timeStamp=d):l={timeStamp:d},s&&_)if("grey"===s)r=await this._decodeBuffer_Uint8Array(u,o,i,_,e.EnumImagePixelFormat.IPF_GrayScaled,0,l);else if("rgba"===s)r=await this._decodeBuffer_Uint8Array(u,o,i,_,e.EnumImagePixelFormat.IPF_ABGR_8888,0,l);else{if("bgra"!==s)throw new Error(`Pixel format '${s}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(u,o,i,_,e.EnumImagePixelFormat.IPF_ARGB_8888,0,l)}else if("grey"===a)r=await this._decodeBuffer_Uint8Array(u,o,i,o,e.EnumImagePixelFormat.IPF_GrayScaled,0,l);else if("rgba"===a)r=await this._decodeBuffer_Uint8Array(u,o,i,4*o,e.EnumImagePixelFormat.IPF_ABGR_8888,0,l);else{if("bgra"!==a)throw new Error(`Color mode '${a}' is not supported to decode.`);r=await this._decodeBuffer_Uint8Array(u,o,i,4*o,e.EnumImagePixelFormat.IPF_ARGB_8888,0,l)}return r}async _decode_DSImage(t,n){if(N._onLog&&N._onLog("_decode_DSImage(dsImage)"),!N.isDSImage(t))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:t.width,height:t.height,pixelFormat:t.pixelFormat.toLowerCase(),data:new Uint8Array(t.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(n,t)}}async _decode_FilePath(e,t){throw N._onLog&&N._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,n,r,o,i,a){if(e.length>0)for(let s of e){let e=s.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*i,e.x2*=.01*i,e.x3*=.01*i,e.x4*=.01*i,e.y1*=.01*a,e.y2*=.01*a,e.y3*=.01*a,e.y4*=.01*a);let _=i/r,d=a/o;e.x1=e.x1/_+t,e.x2=e.x2/_+t,e.x3=e.x3/_+t,e.x4=e.x4/_+t,e.y1=e.y1/d+n,e.y2=e.y2/d+n,e.y3=e.y3/d+n,e.y4=e.y4/d+n,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/o,e.y2*=100/o,e.y3*=100/o,e.y4*=100/o)}}static BarcodeReaderException(t,n){let r,o=e.EnumErrorCode.DBR_UNKNOWN;return"number"==typeof t?(o=t,r=new Error(n)):r=new Error(t),r.code=o,r}_handleRetJsonString(t){let n=e.EnumErrorCode;if(t.textResults){for(let e=0;e{let n=t.indexOf(":");e[t.substring(0,n)]=t.substring(n+1)})),n.exception=e}}return t.decodeRecords?this.decodeRecords=t.decodeRecords:this.decodeRecords={},this._lastErrorCode=t.exception,this._lastErrorString=t.description,t.exception&&!N._setWarnnedEx.has(t.description)&&(N._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==n.DBR_SUCCESS)return t.data;throw N.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,n,r){return await new Promise(((o,i)=>{let a=N._nextTaskID++;N._taskCallbackMap.set(a,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return i(e)}return o()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),N._dbrWorker.postMessage({type:"setModeArgument",id:a,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n,argumentValue:r}})}))}async getModeArgument(e,t,n){return await new Promise(((r,o)=>{let i=N._nextTaskID++;N._taskCallbackMap.set(i,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return o(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),N._dbrWorker.postMessage({type:"getModeArgument",id:i,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),N._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),n=[];for(let r of t)if(r.dataType==e.EnumIMResultDataType.IMRDT_IMAGE)for(let t of r.results){const r=t.bytes;let o;switch(N._onLog&&N._onLog(" "+r.length+" "+r.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case e.EnumImagePixelFormat.IPF_ABGR_8888:o=new Uint8ClampedArray(r);break;case e.EnumImagePixelFormat.IPF_RGB_888:{const e=r.length/3;o=new Uint8ClampedArray(4*e);for(let t=0;t=n)break;o[a]=o[a+1]=o[a+2]=(128&e)/128*255,o[a+3]=255,e<<=1}}break}default:console.warn("unknow intermediate image",t)}if(!o)continue;let i=new ImageData(o,t.width,t.height),a=document.createElement("canvas");a.width=t.width,a.height=t.height,a.getContext("2d").putImageData(i,0,0),n.push(a)}return n}async getScanSettings(){return await new Promise(((e,t)=>{let n=N._nextTaskID++;N._taskCallbackMap.set(n,(n=>{if(n.success){let t=n.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t.autoZoom=this.autoZoom,t.autoFocus=this.autoFocus,t.autoSuggestTip=this.autoSuggestTip,e(t)}{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),N._dbrWorker.postMessage({type:"getScanSettings",id:n,instanceID:this._instanceID})}))}async updateScanSettings(t){if(!t)return;const n=JSON.parse(JSON.stringify(t));if(n.autoZoom||n.autoFocus||n.autoSuggestTip){if(!N._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const t=await this.getRuntimeSettings();t.intermediateResultTypes|=e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(t)}return n.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(n.intervalTime,0),delete n.intervalTime),n.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=n.whenToPlaySoundforSuccessfulRead,delete n.whenToPlaySoundforSuccessfulRead),n.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=n.soundOnSuccessfullRead,delete n.soundOnSuccessfullRead),n.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=n.whenToVibrateforSuccessfulRead,delete n.whenToVibrateforSuccessfulRead),n.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=n.vibrateDuration,delete n.vibrateDuration),n.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=n.captureAndDecodeInParallel,delete n.captureAndDecodeInParallel),n.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=n.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=n.autoZoom,delete n.autoZoom),n.hasOwnProperty("autoFocus")&&(this.autoFocus=n.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete n.autoFocus),n.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=n.autoSuggestTip,delete n.autoFocus),await new Promise(((e,t)=>{let r=N._nextTaskID++;N._taskCallbackMap.set(r,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),N._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:n}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let n of e)t.push(this._cloneDecodeResults(n));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return N._onLog&&N._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));N._onLog&&N._onLog("======= once read ======="),N._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!N.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return N._onLog&&N._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n=[];if(e){n=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(n&&n.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;t=n.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),N.recalculateResultLocation(t,r,o,s,_,i,a)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t,n),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else t&&(n=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return n})().then((e=>{if(N._onLog&&N._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const n=()=>{let n=0;if(t&&t.length){let r=Math.min(...e),o=Math.max(...t);r&&o&&(n=r-o)}else n=0;return n>0?n:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=n()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),N._onLog&&N._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(N._onLog&&N._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)};t(e)}else N._onLog&&N._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e,t){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const n=this._dbrDrawingLayer;e||(e=[]);let r=this._arrPolygons;for(let o=0;o{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(t),t}stopScanning(e){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[e]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(e){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(N._onLog&&N._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let e=N._nextTaskID++;N._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),N._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}var P,F,V,x,k,U,G,H,K,W,Z,Y,Q,J,X,j,q,z,$,ee,te,ne,re,oe,ie,ae;N._jsVersion="9.6.11",N._jsEditVersion="20230310",N._version=`loading...(JS ${N._jsVersion}.${N._jsEditVersion})`,N._license=D,N._sessionPassword=S,N.browserInfo=g,N._workerName=`dbr-${N._jsVersion}.browser.worker.js`,N._engineResourcePath=R,N._licenseServer=[],N._deviceFriendlyName="",N._isShowRelDecodeTimeInResults=!1,N._bWasmDebug=!1,N._bNeverShowDialog=!1,N.__bUseFullFeature=!0,N._nextTaskID=0,N._taskCallbackMap=new Map,N._pLoad=new B,N._lastErrorCode=0,N._lastErrorString="",N._setWarnnedEx=new Set,N._defaultUIElementURL="@engineResourcePath/dbr.ui.html",e.EnumBarcodeColourMode=void 0,(P=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[P.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",P[P.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",P[P.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",P[P.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",P[P.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",P[P.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",P[P.BICM_SKIP=0]="BICM_SKIP",P[P.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(F=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[F.BCM_AUTO=1]="BCM_AUTO",F[F.BCM_GENERAL=2]="BCM_GENERAL",F[F.BCM_SKIP=0]="BCM_SKIP",F[F.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(V=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[V.BF2_NULL=0]="BF2_NULL",V[V.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",V[V.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",V[V.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",V[V.BF2_POSTNET=2097152]="BF2_POSTNET",V[V.BF2_PLANET=4194304]="BF2_PLANET",V[V.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",V[V.BF2_RM4SCC=16777216]="BF2_RM4SCC",V[V.BF2_DOTCODE=2]="BF2_DOTCODE",V[V.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",V[V.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",V[V.BF2_PHARMACODE=12]="BF2_PHARMACODE",V[V.BF2_ALL=4294967295]="BF2_ALL",e.EnumBinarizationMode=void 0,(x=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[x.BM_AUTO=1]="BM_AUTO",x[x.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",x[x.BM_SKIP=0]="BM_SKIP",x[x.BM_THRESHOLD=4]="BM_THRESHOLD",x[x.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(k=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[k.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(U=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[U.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(G=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[G.CCM_AUTO=1]="CCM_AUTO",G[G.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",G[G.CCM_SKIP=0]="CCM_SKIP",G[G.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(H=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[H.CICM_GENERAL=1]="CICM_GENERAL",H[H.CICM_SKIP=0]="CICM_SKIP",H[H.CICM_REV=2147483648]="CICM_REV",e.EnumConflictMode=void 0,(K=e.EnumConflictMode||(e.EnumConflictMode={}))[K.CM_IGNORE=1]="CM_IGNORE",K[K.CM_OVERWRITE=2]="CM_OVERWRITE",e.EnumDeblurMode=void 0,(W=e.EnumDeblurMode||(e.EnumDeblurMode={}))[W.DM_SKIP=0]="DM_SKIP",W[W.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",W[W.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",W[W.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",W[W.DM_SMOOTHING=8]="DM_SMOOTHING",W[W.DM_MORPHING=16]="DM_MORPHING",W[W.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",W[W.DM_SHARPENING=64]="DM_SHARPENING",W[W.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",W[W.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(Z=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[Z.DRM_AUTO=1]="DRM_AUTO",Z[Z.DRM_GENERAL=2]="DRM_GENERAL",Z[Z.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",Z[Z.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",Z[Z.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",Z[Z.DRM_SKIP=0]="DRM_SKIP",Z[Z.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(Y=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[Y.DPMCRM_AUTO=1]="DPMCRM_AUTO",Y[Y.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",Y[Y.DPMCRM_SKIP=0]="DPMCRM_SKIP",Y[Y.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(Q=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[Q.GTM_INVERTED=1]="GTM_INVERTED",Q[Q.GTM_ORIGINAL=2]="GTM_ORIGINAL",Q[Q.GTM_SKIP=0]="GTM_SKIP",Q[Q.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(J=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[J.IPM_AUTO=1]="IPM_AUTO",J[J.IPM_GENERAL=2]="IPM_GENERAL",J[J.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",J[J.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",J[J.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",J[J.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",J[J.IPM_SKIP=0]="IPM_SKIP",J[J.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(X=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[X.IRSM_MEMORY=1]="IRSM_MEMORY",X[X.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",X[X.IRSM_BOTH=4]="IRSM_BOTH",e.EnumLocalizationMode=void 0,(j=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[j.LM_SKIP=0]="LM_SKIP",j[j.LM_AUTO=1]="LM_AUTO",j[j.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",j[j.LM_LINES=8]="LM_LINES",j[j.LM_STATISTICS=4]="LM_STATISTICS",j[j.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",j[j.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",j[j.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",j[j.LM_CENTRE=128]="LM_CENTRE",j[j.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",j[j.LM_REV=2147483648]="LM_REV",e.EnumPDFReadingMode=void 0,(q=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[q.PDFRM_RASTER=1]="PDFRM_RASTER",q[q.PDFRM_AUTO=2]="PDFRM_AUTO",q[q.PDFRM_VECTOR=4]="PDFRM_VECTOR",q[q.PDFRM_REV=2147483648]="PDFRM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,(z=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[z.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",z[z.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",z[z.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",z[z.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,($=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[$.RPM_AUTO=1]="RPM_AUTO",$[$.RPM_GENERAL=2]="RPM_GENERAL",$[$.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",$[$.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",$[$.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",$[$.RPM_SKIP=0]="RPM_SKIP",$[$.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(ee=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[ee.RCT_PIXEL=1]="RCT_PIXEL",ee[ee.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,(te=e.EnumResultType||(e.EnumResultType={}))[te.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",te[te.RT_RAW_TEXT=1]="RT_RAW_TEXT",te[te.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",te[te.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(ne=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[ne.SUM_AUTO=1]="SUM_AUTO",ne[ne.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",ne[ne.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",ne[ne.SUM_SKIP=0]="SUM_SKIP",ne[ne.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(re=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[re.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",re[re.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",re[re.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",re[re.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",re[re.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",re[re.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(oe=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[oe.TFM_AUTO=1]="TFM_AUTO",oe[oe.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",oe[oe.TFM_SKIP=0]="TFM_SKIP",oe[oe.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(ie=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[ie.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",ie[ie.TROM_POSITION=2]="TROM_POSITION",ie[ie.TROM_FORMAT=4]="TROM_FORMAT",ie[ie.TROM_SKIP=0]="TROM_SKIP",ie[ie.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(ae=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[ae.TDM_AUTO=1]="TDM_AUTO",ae[ae.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",ae[ae.TDM_SKIP=0]="TDM_SKIP",ae[ae.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=N,Object.defineProperty(e,"__esModule",{value:!0})})); diff --git a/dist/dbr.pure.mjs b/dist/dbr.pure.mjs index 5c5cfec..dc92457 100644 --- a/dist/dbr.pure.mjs +++ b/dist/dbr.pure.mjs @@ -4,8 +4,8 @@ * @website http://www.dynamsoft.com * @copyright Copyright 2023, Dynamsoft Corporation * @author Dynamsoft - * @version 9.6.10 (js 20230213) + * @version 9.6.11 (js 20230310) * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ */ -var e=function(){this.init()};e.prototype={init:function(){var e=this||t;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var n=this||t;if(e=parseFloat(e),n.ctx||d(),void 0!==e&&e>=0&&e<=1){if(n._volume=e,n._muted)return n;n.usingWebAudio&&n.masterGain.gain.setValueAtTime(e,t.ctx.currentTime);for(var r=0;r=0;n--)e._howls[n].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,d()),e},codecs:function(e){return(this||t)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||t;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||t,n=null;try{n="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!n||"function"!=typeof n.canPlayType)return e;var r=n.canPlayType("audio/mpeg;").replace(/^no$/,""),o=e._navigator?e._navigator.userAgent:"",i=o.match(/OPR\/([0-6].)/g),a=i&&parseInt(i[0].split("/")[1],10)<33,s=-1!==o.indexOf("Safari")&&-1===o.indexOf("Chrome"),_=o.match(/Version\/(.*?) /),d=s&&_&&parseInt(_[1],10)<15;return e._codecs={mp3:!(a||!r&&!n.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!r,opus:!!n.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(n.canPlayType('audio/wav; codecs="1"')||n.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!n.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!n.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(n.canPlayType("audio/x-m4a;")||n.canPlayType("audio/m4a;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(n.canPlayType("audio/x-m4b;")||n.canPlayType("audio/m4b;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(n.canPlayType("audio/x-mp4;")||n.canPlayType("audio/mp4;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(d||!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(d||!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!n.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(n.canPlayType("audio/x-flac;")||n.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||t;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var n=function(t){for(;e._html5AudioPool.length0?s._seek:r._sprite[e][0]/1e3),c=Math.max(0,(r._sprite[e][0]+r._sprite[e][1])/1e3-d),u=1e3*c/Math.abs(s._rate),l=r._sprite[e][0]/1e3,h=(r._sprite[e][0]+r._sprite[e][1])/1e3;s._sprite=e,s._ended=!1;var A=function(){s._paused=!1,s._seek=d,s._start=l,s._stop=h,s._loop=!(!s._loop&&!r._sprite[e][2])};if(!(d>=h)){var f=s._node;if(r._webAudio){var g=function(){r._playLock=!1,A(),r._refreshBuffer(s);var e=s._muted||r._muted?0:s._volume;f.gain.setValueAtTime(e,t.ctx.currentTime),s._playStart=t.ctx.currentTime,void 0===f.bufferSource.start?s._loop?f.bufferSource.noteGrainOn(0,d,86400):f.bufferSource.noteGrainOn(0,d,c):s._loop?f.bufferSource.start(0,d,86400):f.bufferSource.start(0,d,c),u!==1/0&&(r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),u)),n||setTimeout((function(){r._emit("play",s._id),r._loadQueue()}),0)};"running"===t.state&&"interrupted"!==t.ctx.state?g():(r._playLock=!0,r.once("resume",g),r._clearTimer(s._id))}else{var m=function(){f.currentTime=d,f.muted=s._muted||r._muted||t._muted||f.muted,f.volume=s._volume*t.volume(),f.playbackRate=s._rate;try{var o=f.play();if(o&&"undefined"!=typeof Promise&&(o instanceof Promise||"function"==typeof o.then)?(r._playLock=!0,A(),o.then((function(){r._playLock=!1,f._unlocked=!0,n?r._loadQueue():r._emit("play",s._id)})).catch((function(){r._playLock=!1,r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),s._ended=!0,s._paused=!0}))):n||(r._playLock=!1,A(),r._emit("play",s._id)),f.playbackRate=s._rate,f.paused)return void r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||s._loop?r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),u):(r._endTimers[s._id]=function(){r._ended(s),f.removeEventListener("ended",r._endTimers[s._id],!1)},f.addEventListener("ended",r._endTimers[s._id],!1))}catch(e){r._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===f.src&&(f.src=r._src,f.load());var p=window&&window.ejecta||!f.readyState&&t._navigator.isCocoonJS;if(f.readyState>=3||p)m();else{r._playLock=!0,r._state="loading";var I=function(){r._state="loaded",m(),f.removeEventListener(t._canPlayEvent,I,!1)};f.addEventListener(t._canPlayEvent,I,!1),r._clearTimer(s._id)}}return s._id}r._ended(s)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var n=t._getSoundIds(e),r=0;r=0?n=parseInt(i[0],10):e=parseFloat(i[0])}else i.length>=2&&(e=parseFloat(i[0]),n=parseInt(i[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(r=n?o._soundById(n):o._sounds[0])?r._volume:0;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"volume",action:function(){o.volume.apply(o,i)}}),o;void 0===n&&(o._volume=e),n=o._getSoundIds(n);for(var _=0;_0?r/d:r),u=Date.now();e._fadeTo=n,e._interval=setInterval((function(){var o=(Date.now()-u)/r;u=Date.now(),s+=_*o,s=Math.round(100*s)/100,s=_<0?Math.max(n,s):Math.min(n,s),a._webAudio?e._volume=s:a.volume(s,e._id,!0),i&&(a._volume=s),(nt&&s>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit("fade",e._id))}),c)},_stopFade:function(e){var n=this,r=n._soundById(e);return r&&r._interval&&(n._webAudio&&r._node.gain.cancelScheduledValues(t.ctx.currentTime),clearInterval(r._interval),r._interval=null,n.volume(r._fadeTo,e),r._fadeTo=null,n._emit("fade",e)),n},loop:function(){var e,t,n,r=this,o=arguments;if(0===o.length)return r._loop;if(1===o.length){if("boolean"!=typeof o[0])return!!(n=r._soundById(parseInt(o[0],10)))&&n._loop;e=o[0],r._loop=e}else 2===o.length&&(e=o[0],t=parseInt(o[1],10));for(var i=r._getSoundIds(t),a=0;a=0?n=parseInt(i[0],10):e=parseFloat(i[0])}else 2===i.length&&(e=parseFloat(i[0]),n=parseInt(i[1],10));if("number"!=typeof e)return(r=o._soundById(n))?r._rate:o._rate;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"rate",action:function(){o.rate.apply(o,i)}}),o;void 0===n&&(o._rate=e),n=o._getSoundIds(n);for(var _=0;_=0?n=parseInt(o[0],10):r._sounds.length&&(n=r._sounds[0]._id,e=parseFloat(o[0]))}else 2===o.length&&(e=parseFloat(o[0]),n=parseInt(o[1],10));if(void 0===n)return 0;if("number"==typeof e&&("loaded"!==r._state||r._playLock))return r._queue.push({event:"seek",action:function(){r.seek.apply(r,o)}}),r;var s=r._soundById(n);if(s){if(!("number"==typeof e&&e>=0)){if(r._webAudio){var _=r.playing(n)?t.ctx.currentTime-s._playStart:0,d=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(d+_*Math.abs(s._rate))}return s._node.currentTime}var c=r.playing(n);c&&r.pause(n,!0),s._seek=e,s._ended=!1,r._clearTimer(n),r._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var u=function(){c&&r.play(n,!0),r._emit("seek",n)};if(c&&!r._webAudio){var l=function(){r._playLock?setTimeout(l,0):u()};setTimeout(l,0)}else u()}return r},playing:function(e){var t=this;if("number"==typeof e){var n=t._soundById(e);return!!n&&!n._paused}for(var r=0;r=0&&t._howls.splice(i,1);var a=!0;for(r=0;r=0){a=!1;break}return o&&a&&delete o[e._src],t.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,n,r){var o=this["_on"+e];return"function"==typeof t&&o.push(r?{id:n,fn:t,once:r}:{id:n,fn:t}),this},off:function(e,t,n){var r=this,o=r["_on"+e],i=0;if("number"==typeof t&&(n=t,t=null),t||n)for(i=0;i=0;i--)o[i].id&&o[i].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,n)}.bind(r,o[i].fn),0),o[i].once&&r.off(e,o[i].fn,o[i].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action()}return t},_ended:function(e){var n=this,r=e._sprite;if(!n._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(n<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),n--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],n=0;n=0;if(!e.bufferSource)return this;if(t._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),n))try{e.bufferSource.buffer=t._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(t._navigator&&t._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var r=function(e){this._parent=e,this.init()};r.prototype={init:function(){var e=this,n=e._parent;return e._muted=n._muted,e._loop=n._loop,e._volume=n._volume,e._rate=n._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++t._counter,n._sounds.push(e),e.create(),e},create:function(){var e=this,n=e._parent,r=t._muted||e._muted||e._parent._muted?0:e._volume;return n._webAudio?(e._node=void 0===t.ctx.createGain?t.ctx.createGainNode():t.ctx.createGain(),e._node.gain.setValueAtTime(r,t.ctx.currentTime),e._node.paused=!0,e._node.connect(t.masterGain)):t.noAudio||(e._node=t._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(t._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=n._src,e._node.preload=!0===n._preload?"auto":n._preload,e._node.volume=r*t.volume(),e._node.load()),e},reset:function(){var e=this,n=e._parent;return e._muted=n._muted,e._loop=n._loop,e._volume=n._volume,e._rate=n._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++t._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,n=e._parent;n._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(n._sprite).length&&(n._sprite={__default:[0,1e3*n._duration]}),"loaded"!==n._state&&(n._state="loaded",n._emit("load"),n._loadQueue()),e._node.removeEventListener(t._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var o={},i=function(e){var t=e._src;if(o[t])return e._duration=o[t].duration,void _(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),r=new Uint8Array(n.length),i=0;i0?(o[n._src]=e,_(n,e)):r()};"undefined"!=typeof Promise&&1===t.ctx.decodeAudioData.length?t.ctx.decodeAudioData(e).then(i).catch(r):t.ctx.decodeAudioData(e,i,r)},_=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},d=function(){if(t.usingWebAudio){try{"undefined"!=typeof AudioContext?t.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?t.ctx=new webkitAudioContext:t.usingWebAudio=!1}catch(e){t.usingWebAudio=!1}t.ctx||(t.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(t._navigator&&t._navigator.platform),n=t._navigator&&t._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),r=n?parseInt(n[1],10):null;if(e&&r&&r<9){var o=/safari/.test(t._navigator&&t._navigator.userAgent.toLowerCase());t._navigator&&!o&&(t.usingWebAudio=!1)}t.usingWebAudio&&(t.masterGain=void 0===t.ctx.createGain?t.ctx.createGainNode():t.ctx.createGain(),t.masterGain.gain.setValueAtTime(t._muted?0:t._volume,t.ctx.currentTime),t.masterGain.connect(t.ctx.destination)),t._setup()}};!function(e,t,n,r){var o;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var n=t._howls.length-1;n>=0;n--)t._howls[n].stereo(e);return t},e.prototype.pos=function(e,n,r){var o=this;return o.ctx&&o.ctx.listener?(n="number"!=typeof n?o._pos[1]:n,r="number"!=typeof r?o._pos[2]:r,"number"!=typeof e?o._pos:(o._pos=[e,n,r],void 0!==o.ctx.listener.positionX?(o.ctx.listener.positionX.setTargetAtTime(o._pos[0],t.ctx.currentTime,.1),o.ctx.listener.positionY.setTargetAtTime(o._pos[1],t.ctx.currentTime,.1),o.ctx.listener.positionZ.setTargetAtTime(o._pos[2],t.ctx.currentTime,.1)):o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},e.prototype.orientation=function(e,n,r,o,i,a){var s=this;if(!s.ctx||!s.ctx.listener)return s;var _=s._orientation;return n="number"!=typeof n?_[1]:n,r="number"!=typeof r?_[2]:r,o="number"!=typeof o?_[3]:o,i="number"!=typeof i?_[4]:i,a="number"!=typeof a?_[5]:a,"number"!=typeof e?_:(s._orientation=[e,n,r,o,i,a],void 0!==s.ctx.listener.forwardX?(s.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),s.ctx.listener.forwardY.setTargetAtTime(n,t.ctx.currentTime,.1),s.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),s.ctx.listener.upX.setTargetAtTime(o,t.ctx.currentTime,.1),s.ctx.listener.upY.setTargetAtTime(i,t.ctx.currentTime,.1),s.ctx.listener.upZ.setTargetAtTime(a,t.ctx.currentTime,.1)):s.ctx.listener.setOrientation(e,n,r,o,i,a),s)},n.prototype.init=(o=n.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],o.call(this,e)}),n.prototype.stereo=function(e,n){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,n)}}),r;var o=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===n){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var a=r._getSoundIds(n),s=0;s{let e=!1;if(p)try{(await A.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===f.browser&&f.version>66||"Safari"===f.browser&&f.version>13||"OPR"===f.browser&&f.version>43||"Edge"===f.browser&&f.version;const R=(()=>{if(!c&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),E=" is not allowed to change after `createInstance` or `loadWasm` is called.",T=!c&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",D=!c&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",S=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let t=0;te&&"object"==typeof e&&"function"==typeof e.then;class w extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(v(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,v(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const n=await t;e===this._task&&this.resolve(n)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}const N=["iPhone","iPad","Android","HarmonyOS"].includes(f.OS)?2048:4096;class b{constructor(){this._instanceID=void 0,this._ifSaveOriginalImageInACanvas=!1,this.oriCanvas=null,this.oriCanvasData=null,this.canvas=null,this.bFilterRegionInJs=!1,this._region=null,this._timeStartDecode=null,this._timeEnterInnerDBR=null,this._timeGetMessage=null,this.decodeRecords={},this.bDestroyed=!1,this._lastErrorCode=0,this._lastErrorString="",this._lastInnerDecodeDuration=0,this.intervalTime=0,this._intervalGetVideoFrame=0,this.array_getFrameTimeCost=[],this.array_decodeFrameTimeCost=[],this._indexCurrentDecodingFrame=0,this._arrPolygons=[],this._bPauseScan=!1,this._intervalDetectVideoPause=1e3,this._soundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",this.beepSound=new n({src:["data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=N,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+E);n._license=t})(b,e)}static get productKeys(){return this._license}static set productKeys(e){b.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){b.license=e}static get organizationID(){return this._license}static set organizationID(e){b.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+E);n._sessionPassword=t})(b,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:g,worker:m,getUserMedia:p,camera:await I(),browser:f.browser,version:f.version,OS:f.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");b._engineResourcePath=(e=>{if(null==e&&(e="./"),!c){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+E);n._licenseServer=S(t)})(b,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+E);n._deviceFriendlyName=t||""})(b,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");b.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&(("colorMode"in e||"pixelFormat"in e)&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=b._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",b.engineResourcePath)}static set defaultUIElementURL(e){b._defaultUIElementURL=e}static _fireHTTPSWarnning(){b.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{b.onWarning&&b.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new n({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;b._onLog&&b._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const n=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{n?n===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else n||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let t=await this._decode_DCEFrame(e,{bCopyData:!1}),n=null;if(t&&t.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;n=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),b.recalculateResultLocation(n,r,o,s,_,i,a)}if(this._drawResults(n,t),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(b._onLog&&b._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!b.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:n,sp:r,rmk:o}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,n,r=t._license||"",o=JSON.parse(JSON.stringify(t._licenseServer)),i=t._sessionPassword,a=0;if(r.startsWith("t")||r.startsWith("f"))a=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))a=1;else{a=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t;try{let e=r.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===o.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),o=S(e)}!i&&t.sessionPassword&&(i=t.sessionPassword),e=t.remark}("200001"===r||r.startsWith("200001-"))&&(o&&o.length||(r="")),r||(a=1)}if(a&&(globalThis.crypto||(n="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(n="Require https to use online key in this browser.")),n){if(1!==a)throw new Error(n);a=0,console.warn(n),t._lastErrorCode=-1,t._lastErrorString=n}return 1===a&&(r="",console.warn("Applying for a public trial license ...")),{lt:a,l:r,ls:o,sp:i,rmk:e}}throw new Error("Can't preprocess license again"+E)})(b);this._pLoad.task=async(i,a)=>{let s=b.engineResourcePath+b._workerName;b.engineResourcePath.startsWith(location.origin)||(s=await fetch(s).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),b._dbrWorker=new Worker(s),b._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},b._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":b._onLog&&b._onLog(n.message);break;case"load":{n.message&&(n.message=n.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0,n.message||(n.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),n.success?(b._dbrWorker.onerror=null,b._version=n.version+"(JS "+b._jsVersion+"."+b._jsEditVersion+")",b._onLog&&b._onLog("load dbr worker success"),n.message&&console.warn(n.message)):(t=new Error(n.message),t.stack=n.stack+"\n"+t.stack,t.ltsErrorCode=n.ltsErrorCode,r||111==n.ltsErrorCode&&-1!=n.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&b.showDialog(n.success?"warn":"error",n.message),n.success?i():a(t);break}case"task":{let e=n.id,t=n.body;try{b._taskCallbackMap.get(e)(t),b._taskCallbackMap.delete(e)}catch(t){throw b._taskCallbackMap.delete(e),t}break}default:b._onLog&&b._onLog(t)}},b._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:b.engineResourcePath,bUseFullFeature:b._bUseFullFeature,bd:b._bWasmDebug,v:b._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:f,fn:b.deviceFriendlyName,ls:n,sp:r,rmk:o})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,n)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let o=await r.text();if(!o.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let i=document.createElement("div");i.innerHTML=o;let a=[];for(let e=0;e{if(e==t.target){s.remove();for(let e of a)e.remove()}}));else if(!d&&e.classList.contains("dls-license-icon-close"))d=e,e.addEventListener("click",(()=>{s.remove();for(let e of a)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!l&&e.classList.contains("dls-license-msg-content")){l=e;let t=n;for(;t;){let n=t.indexOf("["),r=t.indexOf("]",n),o=t.indexOf("(",r),i=t.indexOf(")",o);if(-1==n||-1==r||-1==o||-1==i){e.appendChild(new Text(t));break}n>0&&e.appendChild(new Text(t.substring(0,n)));let a=document.createElement("a"),s=t.substring(n+1,r);a.innerText=s;let _=t.substring(o+1,i);a.setAttribute("href",_),a.setAttribute("target","_blank"),e.appendChild(a),t=t.substring(i+1)}}document.body.appendChild(s)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await b.loadWasm(),await new Promise(((t,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),b._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new b;return e._instanceID=await b.createInstanceInWorker(),b._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){b._onLog&&b._onLog("decode(source: any)"),b._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):b.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):b.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,n,r,o,i,a){return await new Promise(((s,_)=>{let d=b._nextTaskID++;b._taskCallbackMap.set(d,(e=>{if(e.success){let t,n=b._onLog?Date.now():0;b._onLog&&b._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return _(e)}if(b._onLog){let e=Date.now();b._onLog("DBR getting message from worker timestamp: "+n),b._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),b._onLog("From DBR entering worker to returning message from worker costs: "+(n-this._timeEnterInnerDBR)),b._onLog("Handling results from DBR worker costs: "+(e-n)),b._onLog("Total decoding image costs: "+(e-this._timeStartDecode))}return s(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,_(t)}})),this._timeEnterInnerDBR=Date.now(),b._onLog&&b._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),b._dbrWorker.postMessage({type:"decodeBuffer",id:d,instanceID:this._instanceID,body:{buffer:e,width:t,height:n,stride:r,format:o,orientation:i,config:a}},[e.buffer]),b._onLog&&a&&a.timeStamp&&b._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-a.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,r,o,i,a){b._onLog&&b._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const s=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,n)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(s),t,n,r,o,i,a)}async decodeBuffer(e,t,n,r,o,i,a){let s;return b._onLog&&b._onLog("decodeBuffer(buffer,width,height,stride,format)"),b._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?s=await this._decodeBuffer_Uint8Array(e,t,n,r,o,i,a):e instanceof ArrayBuffer?s=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,n,r,o,i,a):e instanceof Blob&&(s=await this._decodeBuffer_Blob(e,t,n,r,o,i,a)),s}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return n(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),b._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success){let t=JSON.parse(n.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"getRuntimeSettings",id:n,instanceID:this._instanceID})}))}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=5,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region}else if("dense"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=9,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!b._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(L.BF_ONED|L.BF_QR_CODE|L.BF_PDF417|L.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=t.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,t.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(t.intermediateResultTypes|=M.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){n(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),b._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=N,await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"resetRuntimeSettings",id:n,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=N,await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!b._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!b._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){n(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),b._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){b._onLog&&b._onLog("_decode_Blob(blob: Blob)");let n=null,r=null;if("undefined"!=typeof createImageBitmap)try{n=await createImageBitmap(e)}catch(e){}n||(r=await function(e){return new Promise(((t,n)=>{let r=URL.createObjectURL(e),o=new Image;o.dbrObjUrl=r,o.src=r,o.onload=()=>{t(o)},o.onerror=e=>{n(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let o=await this._decode_Image(n||r,t);return n&&n.close(),o}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){b._onLog&&b._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let n,r,o=e instanceof HTMLImageElement?e.naturalWidth:e.width,i=e instanceof HTMLImageElement?e.naturalHeight:e.height,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d",{willReadFrequently:!0}));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(s,t)}async _decode_Canvas(e,t){if(b._onLog&&b._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if(0===e.width||0===e.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=e,this.oriCanvasData=null);let n=(e.ctx2d||e.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,e.width,e.height).data;return await this._decodeBuffer_Uint8Array(n,e.width,e.height,4*e.width,C.IPF_ABGR_8888,0,t)}async _decode_Video(e,t){if(b._onLog&&b._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let n,r,o=e.videoWidth,i=e.videoHeight,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d",{willReadFrequently:!0}));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),await this._decode_Canvas(s,t)}async _decode_DCEFrame(e,t){if(b._onLog&&b._onLog("_decode_DCEFrame(dceFrame)"),!b.isDCEFrame(e))return[];let n=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,pixelFormat:e.pixelFormat,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{width:r,height:o,colorMode:i,pixelFormat:a,stride:s,timeStamp:_}=e;let d;d=t&&t.bCopyData?new Uint8Array(e.data):e.data;let c=null;if(t?(c=JSON.parse(JSON.stringify(t)),c.timeStamp=_):c={timeStamp:_},a&&s)if("grey"===a)n=await this._decodeBuffer_Uint8Array(d,r,o,s,C.IPF_GrayScaled,0,c);else if("rgba"===a)n=await this._decodeBuffer_Uint8Array(d,r,o,s,C.IPF_ABGR_8888,0,c);else{if("bgra"!==a)throw new Error(`Pixel format '${a}' is not supported to decode.`);n=await this._decodeBuffer_Uint8Array(d,r,o,s,C.IPF_ARGB_8888,0,c)}else if("grey"===i)n=await this._decodeBuffer_Uint8Array(d,r,o,r,C.IPF_GrayScaled,0,c);else if("rgba"===i)n=await this._decodeBuffer_Uint8Array(d,r,o,4*r,C.IPF_ABGR_8888,0,c);else{if("bgra"!==i)throw new Error(`Color mode '${i}' is not supported to decode.`);n=await this._decodeBuffer_Uint8Array(d,r,o,4*r,C.IPF_ARGB_8888,0,c)}return n}async _decode_DSImage(e,t){if(b._onLog&&b._onLog("_decode_DSImage(dsImage)"),!b.isDSImage(e))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat.toLowerCase(),data:new Uint8Array(e.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(n,t)}}async _decode_FilePath(e,t){throw b._onLog&&b._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,n,r,o,i,a){if(e.length>0)for(let s of e){let e=s.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*i,e.x2*=.01*i,e.x3*=.01*i,e.x4*=.01*i,e.y1*=.01*a,e.y2*=.01*a,e.y3*=.01*a,e.y4*=.01*a);let _=i/r,d=a/o;e.x1=e.x1/_+t,e.x2=e.x2/_+t,e.x3=e.x3/_+t,e.x4=e.x4/_+t,e.y1=e.y1/d+n,e.y2=e.y2/d+n,e.y3=e.y3/d+n,e.y4=e.y4/d+n,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/o,e.y2*=100/o,e.y3*=100/o,e.y4*=100/o)}}static BarcodeReaderException(e,t){let n,r=y.DBR_UNKNOWN;return"number"==typeof e?(r=e,n=new Error(t)):n=new Error(e),n.code=r,n}_handleRetJsonString(e){let t=y;if(e.textResults){for(let t=0;t{let n=t.indexOf(":");e[t.substring(0,n)]=t.substring(n+1)})),n.exception=e}}return e.decodeRecords?this.decodeRecords=e.decodeRecords:this.decodeRecords={},this._lastErrorCode=e.exception,this._lastErrorString=e.description,e.exception&&!b._setWarnnedEx.has(e.description)&&(b._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw b.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,n,r){return await new Promise(((o,i)=>{let a=b._nextTaskID++;b._taskCallbackMap.set(a,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return i(e)}return o()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),b._dbrWorker.postMessage({type:"setModeArgument",id:a,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n,argumentValue:r}})}))}async getModeArgument(e,t,n){return await new Promise(((r,o)=>{let i=b._nextTaskID++;b._taskCallbackMap.set(i,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return o(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),b._dbrWorker.postMessage({type:"getModeArgument",id:i,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let n of e)if(n.dataType==O.IMRDT_IMAGE)for(let e of n.results){const n=e.bytes;let r;switch(b._onLog&&b._onLog(" "+n.length+" "+n.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case C.IPF_ABGR_8888:r=new Uint8ClampedArray(n);break;case C.IPF_RGB_888:{const e=n.length/3;r=new Uint8ClampedArray(4*e);for(let t=0;t=o)break;r[a]=r[a+1]=r[a+2]=(128&t)/128*255,r[a+3]=255,t<<=1}}break}default:console.warn("unknow intermediate image",e)}if(!r)continue;let o=new ImageData(r,e.width,e.height),i=document.createElement("canvas");i.width=e.width,i.height=e.height,i.getContext("2d").putImageData(o,0,0),t.push(i)}return t}async getScanSettings(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success){let t=n.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t.autoZoom=this.autoZoom,t.autoFocus=this.autoFocus,t.autoSuggestTip=this.autoSuggestTip,e(t)}{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),b._dbrWorker.postMessage({type:"getScanSettings",id:n,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));if(t.autoZoom||t.autoFocus||t.autoSuggestTip){if(!b._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const e=await this.getRuntimeSettings();e.intermediateResultTypes|=M.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(e)}return t.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(t.intervalTime,0),delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),t.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=t.captureAndDecodeInParallel,delete t.captureAndDecodeInParallel),t.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=t.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=t.autoZoom,delete t.autoZoom),t.hasOwnProperty("autoFocus")&&(this.autoFocus=t.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete t.autoFocus),t.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=t.autoSuggestTip,delete t.autoFocus),await new Promise(((e,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,n(e)}})),b._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let n of e)t.push(this._cloneDecodeResults(n));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return b._onLog&&b._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));b._onLog&&b._onLog("======= once read ======="),b._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!b.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return b._onLog&&b._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n=[];if(e){n=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(n&&n.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;t=n.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),b.recalculateResultLocation(t,r,o,s,_,i,a)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t,n),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else t&&(n=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return n})().then((e=>{if(b._onLog&&b._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const n=()=>{let n=0;if(t&&t.length){let r=Math.min(...e),o=Math.max(...t);r&&o&&(n=r-o)}else n=0;return n>0?n:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=n()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),b._onLog&&b._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(b._onLog&&b._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)};t(e)}else b._onLog&&b._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e,t){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const n=this._dbrDrawingLayer;e||(e=[]);let r=this._arrPolygons;for(let o=0;o{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(t),t}stopScanning(e){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[e]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(e){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(b._onLog&&b._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let e=b._nextTaskID++;b._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),b._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}var B,P,F,V,x,k,U,G,H,K,W,Z,Y,Q,J,X,j,q,$,z,ee,te,ne,re,oe,ie;b._jsVersion="9.6.10",b._jsEditVersion="20230213",b._version=`loading...(JS ${b._jsVersion}.${b._jsEditVersion})`,b._license=T,b._sessionPassword=D,b.browserInfo=f,b._workerName=`dbr-${b._jsVersion}.browser.worker.js`,b._engineResourcePath=R,b._licenseServer=[],b._deviceFriendlyName="",b._isShowRelDecodeTimeInResults=!1,b._bWasmDebug=!1,b._bNeverShowDialog=!1,b.__bUseFullFeature=!0,b._nextTaskID=0,b._taskCallbackMap=new Map,b._pLoad=new w,b._lastErrorCode=0,b._lastErrorString="",b._setWarnnedEx=new Set,b._defaultUIElementURL="@engineResourcePath/dbr.ui.html",function(e){e[e.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",e[e.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",e[e.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",e[e.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",e[e.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",e[e.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",e[e.BICM_SKIP=0]="BICM_SKIP",e[e.BICM_REV=2147483648]="BICM_REV"}(B||(B={})),function(e){e[e.BCM_AUTO=1]="BCM_AUTO",e[e.BCM_GENERAL=2]="BCM_GENERAL",e[e.BCM_SKIP=0]="BCM_SKIP",e[e.BCM_REV=2147483648]="BCM_REV"}(P||(P={})),function(e){e[e.BF2_NULL=0]="BF2_NULL",e[e.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",e[e.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",e[e.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",e[e.BF2_POSTNET=2097152]="BF2_POSTNET",e[e.BF2_PLANET=4194304]="BF2_PLANET",e[e.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",e[e.BF2_RM4SCC=16777216]="BF2_RM4SCC",e[e.BF2_DOTCODE=2]="BF2_DOTCODE",e[e.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",e[e.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",e[e.BF2_PHARMACODE=12]="BF2_PHARMACODE",e[e.BF2_ALL=4294967295]="BF2_ALL"}(F||(F={})),function(e){e[e.BM_AUTO=1]="BM_AUTO",e[e.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",e[e.BM_SKIP=0]="BM_SKIP",e[e.BM_THRESHOLD=4]="BM_THRESHOLD",e[e.BM_REV=2147483648]="BM_REV"}(V||(V={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(x||(x={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(k||(k={})),function(e){e[e.CCM_AUTO=1]="CCM_AUTO",e[e.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",e[e.CCM_SKIP=0]="CCM_SKIP",e[e.CCM_REV=2147483648]="CCM_REV"}(U||(U={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(G||(G={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(H||(H={})),function(e){e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(K||(K={})),function(e){e[e.DRM_AUTO=1]="DRM_AUTO",e[e.DRM_GENERAL=2]="DRM_GENERAL",e[e.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",e[e.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",e[e.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",e[e.DRM_SKIP=0]="DRM_SKIP",e[e.DRM_REV=2147483648]="DRM_REV"}(W||(W={})),function(e){e[e.DPMCRM_AUTO=1]="DPMCRM_AUTO",e[e.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",e[e.DPMCRM_SKIP=0]="DPMCRM_SKIP",e[e.DPMCRM_REV=2147483648]="DPMCRM_REV"}(Z||(Z={})),function(e){e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_REV=2147483648]="GTM_REV"}(Y||(Y={})),function(e){e[e.IPM_AUTO=1]="IPM_AUTO",e[e.IPM_GENERAL=2]="IPM_GENERAL",e[e.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",e[e.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",e[e.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",e[e.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",e[e.IPM_SKIP=0]="IPM_SKIP",e[e.IPM_REV=2147483648]="IPM_REV"}(Q||(Q={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(J||(J={})),function(e){e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_REV=2147483648]="LM_REV"}(X||(X={})),function(e){e[e.PDFRM_RASTER=1]="PDFRM_RASTER",e[e.PDFRM_AUTO=2]="PDFRM_AUTO",e[e.PDFRM_VECTOR=4]="PDFRM_VECTOR",e[e.PDFRM_REV=2147483648]="PDFRM_REV"}(j||(j={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(q||(q={})),function(e){e[e.RPM_AUTO=1]="RPM_AUTO",e[e.RPM_GENERAL=2]="RPM_GENERAL",e[e.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",e[e.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",e[e.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",e[e.RPM_SKIP=0]="RPM_SKIP",e[e.RPM_REV=2147483648]="RPM_REV"}($||($={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(z||(z={})),function(e){e[e.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",e[e.RT_RAW_TEXT=1]="RT_RAW_TEXT",e[e.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",e[e.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(ee||(ee={})),function(e){e[e.SUM_AUTO=1]="SUM_AUTO",e[e.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",e[e.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",e[e.SUM_SKIP=0]="SUM_SKIP",e[e.SUM_REV=2147483648]="SUM_REV"}(te||(te={})),function(e){e[e.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",e[e.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",e[e.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",e[e.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",e[e.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",e[e.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(ne||(ne={})),function(e){e[e.TFM_AUTO=1]="TFM_AUTO",e[e.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",e[e.TFM_SKIP=0]="TFM_SKIP",e[e.TFM_REV=2147483648]="TFM_REV"}(re||(re={})),function(e){e[e.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",e[e.TROM_POSITION=2]="TROM_POSITION",e[e.TROM_FORMAT=4]="TROM_FORMAT",e[e.TROM_SKIP=0]="TROM_SKIP",e[e.TROM_REV=2147483648]="TROM_REV"}(oe||(oe={})),function(e){e[e.TDM_AUTO=1]="TDM_AUTO",e[e.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",e[e.TDM_SKIP=0]="TDM_SKIP",e[e.TDM_REV=2147483648]="TDM_REV"}(ie||(ie={}));export{b as BarcodeReader,B as EnumBarcodeColourMode,P as EnumBarcodeComplementMode,L as EnumBarcodeFormat,F as EnumBarcodeFormat_2,V as EnumBinarizationMode,x as EnumClarityCalculationMethod,k as EnumClarityFilterMode,U as EnumColourClusteringMode,G as EnumColourConversionMode,H as EnumConflictMode,Z as EnumDPMCodeReadingMode,K as EnumDeblurMode,W as EnumDeformationResistingMode,y as EnumErrorCode,Y as EnumGrayscaleTransformationMode,O as EnumIMResultDataType,C as EnumImagePixelFormat,Q as EnumImagePreprocessingMode,J as EnumIntermediateResultSavingMode,M as EnumIntermediateResultType,X as EnumLocalizationMode,j as EnumPDFReadingMode,q as EnumQRCodeErrorCorrectionLevel,$ as EnumRegionPredetectionMode,z as EnumResultCoordinateType,ee as EnumResultType,te as EnumScaleUpMode,ne as EnumTerminatePhase,re as EnumTextFilterMode,oe as EnumTextResultOrderMode,ie as EnumTextureDetectionMode}; +var e=function(){this.init()};e.prototype={init:function(){var e=this||t;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var n=this||t;if(e=parseFloat(e),n.ctx||d(),void 0!==e&&e>=0&&e<=1){if(n._volume=e,n._muted)return n;n.usingWebAudio&&n.masterGain.gain.setValueAtTime(e,t.ctx.currentTime);for(var r=0;r=0;n--)e._howls[n].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,d()),e},codecs:function(e){return(this||t)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||t;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||t,n=null;try{n="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!n||"function"!=typeof n.canPlayType)return e;var r=n.canPlayType("audio/mpeg;").replace(/^no$/,""),o=e._navigator?e._navigator.userAgent:"",i=o.match(/OPR\/([0-6].)/g),a=i&&parseInt(i[0].split("/")[1],10)<33,s=-1!==o.indexOf("Safari")&&-1===o.indexOf("Chrome"),_=o.match(/Version\/(.*?) /),d=s&&_&&parseInt(_[1],10)<15;return e._codecs={mp3:!(a||!r&&!n.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!r,opus:!!n.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(n.canPlayType('audio/wav; codecs="1"')||n.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!n.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!n.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(n.canPlayType("audio/x-m4a;")||n.canPlayType("audio/m4a;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(n.canPlayType("audio/x-m4b;")||n.canPlayType("audio/m4b;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(n.canPlayType("audio/x-mp4;")||n.canPlayType("audio/mp4;")||n.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(d||!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(d||!n.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!n.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(n.canPlayType("audio/x-flac;")||n.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||t;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var n=function(t){for(;e._html5AudioPool.length0?s._seek:r._sprite[e][0]/1e3),c=Math.max(0,(r._sprite[e][0]+r._sprite[e][1])/1e3-d),u=1e3*c/Math.abs(s._rate),l=r._sprite[e][0]/1e3,h=(r._sprite[e][0]+r._sprite[e][1])/1e3;s._sprite=e,s._ended=!1;var A=function(){s._paused=!1,s._seek=d,s._start=l,s._stop=h,s._loop=!(!s._loop&&!r._sprite[e][2])};if(!(d>=h)){var f=s._node;if(r._webAudio){var g=function(){r._playLock=!1,A(),r._refreshBuffer(s);var e=s._muted||r._muted?0:s._volume;f.gain.setValueAtTime(e,t.ctx.currentTime),s._playStart=t.ctx.currentTime,void 0===f.bufferSource.start?s._loop?f.bufferSource.noteGrainOn(0,d,86400):f.bufferSource.noteGrainOn(0,d,c):s._loop?f.bufferSource.start(0,d,86400):f.bufferSource.start(0,d,c),u!==1/0&&(r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),u)),n||setTimeout((function(){r._emit("play",s._id),r._loadQueue()}),0)};"running"===t.state&&"interrupted"!==t.ctx.state?g():(r._playLock=!0,r.once("resume",g),r._clearTimer(s._id))}else{var m=function(){f.currentTime=d,f.muted=s._muted||r._muted||t._muted||f.muted,f.volume=s._volume*t.volume(),f.playbackRate=s._rate;try{var o=f.play();if(o&&"undefined"!=typeof Promise&&(o instanceof Promise||"function"==typeof o.then)?(r._playLock=!0,A(),o.then((function(){r._playLock=!1,f._unlocked=!0,n?r._loadQueue():r._emit("play",s._id)})).catch((function(){r._playLock=!1,r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),s._ended=!0,s._paused=!0}))):n||(r._playLock=!1,A(),r._emit("play",s._id)),f.playbackRate=s._rate,f.paused)return void r._emit("playerror",s._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||s._loop?r._endTimers[s._id]=setTimeout(r._ended.bind(r,s),u):(r._endTimers[s._id]=function(){r._ended(s),f.removeEventListener("ended",r._endTimers[s._id],!1)},f.addEventListener("ended",r._endTimers[s._id],!1))}catch(e){r._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===f.src&&(f.src=r._src,f.load());var p=window&&window.ejecta||!f.readyState&&t._navigator.isCocoonJS;if(f.readyState>=3||p)m();else{r._playLock=!0,r._state="loading";var I=function(){r._state="loaded",m(),f.removeEventListener(t._canPlayEvent,I,!1)};f.addEventListener(t._canPlayEvent,I,!1),r._clearTimer(s._id)}}return s._id}r._ended(s)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var n=t._getSoundIds(e),r=0;r=0?n=parseInt(i[0],10):e=parseFloat(i[0])}else i.length>=2&&(e=parseFloat(i[0]),n=parseInt(i[1],10));if(!(void 0!==e&&e>=0&&e<=1))return(r=n?o._soundById(n):o._sounds[0])?r._volume:0;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"volume",action:function(){o.volume.apply(o,i)}}),o;void 0===n&&(o._volume=e),n=o._getSoundIds(n);for(var _=0;_0?r/d:r),u=Date.now();e._fadeTo=n,e._interval=setInterval((function(){var o=(Date.now()-u)/r;u=Date.now(),s+=_*o,s=Math.round(100*s)/100,s=_<0?Math.max(n,s):Math.min(n,s),a._webAudio?e._volume=s:a.volume(s,e._id,!0),i&&(a._volume=s),(nt&&s>=n)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(n,e._id),a._emit("fade",e._id))}),c)},_stopFade:function(e){var n=this,r=n._soundById(e);return r&&r._interval&&(n._webAudio&&r._node.gain.cancelScheduledValues(t.ctx.currentTime),clearInterval(r._interval),r._interval=null,n.volume(r._fadeTo,e),r._fadeTo=null,n._emit("fade",e)),n},loop:function(){var e,t,n,r=this,o=arguments;if(0===o.length)return r._loop;if(1===o.length){if("boolean"!=typeof o[0])return!!(n=r._soundById(parseInt(o[0],10)))&&n._loop;e=o[0],r._loop=e}else 2===o.length&&(e=o[0],t=parseInt(o[1],10));for(var i=r._getSoundIds(t),a=0;a=0?n=parseInt(i[0],10):e=parseFloat(i[0])}else 2===i.length&&(e=parseFloat(i[0]),n=parseInt(i[1],10));if("number"!=typeof e)return(r=o._soundById(n))?r._rate:o._rate;if("loaded"!==o._state||o._playLock)return o._queue.push({event:"rate",action:function(){o.rate.apply(o,i)}}),o;void 0===n&&(o._rate=e),n=o._getSoundIds(n);for(var _=0;_=0?n=parseInt(o[0],10):r._sounds.length&&(n=r._sounds[0]._id,e=parseFloat(o[0]))}else 2===o.length&&(e=parseFloat(o[0]),n=parseInt(o[1],10));if(void 0===n)return 0;if("number"==typeof e&&("loaded"!==r._state||r._playLock))return r._queue.push({event:"seek",action:function(){r.seek.apply(r,o)}}),r;var s=r._soundById(n);if(s){if(!("number"==typeof e&&e>=0)){if(r._webAudio){var _=r.playing(n)?t.ctx.currentTime-s._playStart:0,d=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(d+_*Math.abs(s._rate))}return s._node.currentTime}var c=r.playing(n);c&&r.pause(n,!0),s._seek=e,s._ended=!1,r._clearTimer(n),r._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var u=function(){c&&r.play(n,!0),r._emit("seek",n)};if(c&&!r._webAudio){var l=function(){r._playLock?setTimeout(l,0):u()};setTimeout(l,0)}else u()}return r},playing:function(e){var t=this;if("number"==typeof e){var n=t._soundById(e);return!!n&&!n._paused}for(var r=0;r=0&&t._howls.splice(i,1);var a=!0;for(r=0;r=0){a=!1;break}return o&&a&&delete o[e._src],t.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,n,r){var o=this["_on"+e];return"function"==typeof t&&o.push(r?{id:n,fn:t,once:r}:{id:n,fn:t}),this},off:function(e,t,n){var r=this,o=r["_on"+e],i=0;if("number"==typeof t&&(n=t,t=null),t||n)for(i=0;i=0;i--)o[i].id&&o[i].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,n)}.bind(r,o[i].fn),0),o[i].once&&r.off(e,o[i].fn,o[i].id));return r._loadQueue(e),r},_loadQueue:function(e){var t=this;if(t._queue.length>0){var n=t._queue[0];n.event===e&&(t._queue.shift(),t._loadQueue()),e||n.action()}return t},_ended:function(e){var n=this,r=e._sprite;if(!n._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;r--){if(n<=t)return;e._sounds[r]._ended&&(e._webAudio&&e._sounds[r]._node&&e._sounds[r]._node.disconnect(0),e._sounds.splice(r,1),n--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],n=0;n=0;if(!e.bufferSource)return this;if(t._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),n))try{e.bufferSource.buffer=t._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(t._navigator&&t._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var r=function(e){this._parent=e,this.init()};r.prototype={init:function(){var e=this,n=e._parent;return e._muted=n._muted,e._loop=n._loop,e._volume=n._volume,e._rate=n._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++t._counter,n._sounds.push(e),e.create(),e},create:function(){var e=this,n=e._parent,r=t._muted||e._muted||e._parent._muted?0:e._volume;return n._webAudio?(e._node=void 0===t.ctx.createGain?t.ctx.createGainNode():t.ctx.createGain(),e._node.gain.setValueAtTime(r,t.ctx.currentTime),e._node.paused=!0,e._node.connect(t.masterGain)):t.noAudio||(e._node=t._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(t._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=n._src,e._node.preload=!0===n._preload?"auto":n._preload,e._node.volume=r*t.volume(),e._node.load()),e},reset:function(){var e=this,n=e._parent;return e._muted=n._muted,e._loop=n._loop,e._volume=n._volume,e._rate=n._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++t._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,n=e._parent;n._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(n._sprite).length&&(n._sprite={__default:[0,1e3*n._duration]}),"loaded"!==n._state&&(n._state="loaded",n._emit("load"),n._loadQueue()),e._node.removeEventListener(t._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var o={},i=function(e){var t=e._src;if(o[t])return e._duration=o[t].duration,void _(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),r=new Uint8Array(n.length),i=0;i0?(o[n._src]=e,_(n,e)):r()};"undefined"!=typeof Promise&&1===t.ctx.decodeAudioData.length?t.ctx.decodeAudioData(e).then(i).catch(r):t.ctx.decodeAudioData(e,i,r)},_=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},d=function(){if(t.usingWebAudio){try{"undefined"!=typeof AudioContext?t.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?t.ctx=new webkitAudioContext:t.usingWebAudio=!1}catch(e){t.usingWebAudio=!1}t.ctx||(t.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(t._navigator&&t._navigator.platform),n=t._navigator&&t._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),r=n?parseInt(n[1],10):null;if(e&&r&&r<9){var o=/safari/.test(t._navigator&&t._navigator.userAgent.toLowerCase());t._navigator&&!o&&(t.usingWebAudio=!1)}t.usingWebAudio&&(t.masterGain=void 0===t.ctx.createGain?t.ctx.createGainNode():t.ctx.createGain(),t.masterGain.gain.setValueAtTime(t._muted?0:t._volume,t.ctx.currentTime),t.masterGain.connect(t.ctx.destination)),t._setup()}};!function(e,t,n,r){var o;e.prototype._pos=[0,0,0],e.prototype._orientation=[0,0,-1,0,1,0],e.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var n=t._howls.length-1;n>=0;n--)t._howls[n].stereo(e);return t},e.prototype.pos=function(e,n,r){var o=this;return o.ctx&&o.ctx.listener?(n="number"!=typeof n?o._pos[1]:n,r="number"!=typeof r?o._pos[2]:r,"number"!=typeof e?o._pos:(o._pos=[e,n,r],void 0!==o.ctx.listener.positionX?(o.ctx.listener.positionX.setTargetAtTime(o._pos[0],t.ctx.currentTime,.1),o.ctx.listener.positionY.setTargetAtTime(o._pos[1],t.ctx.currentTime,.1),o.ctx.listener.positionZ.setTargetAtTime(o._pos[2],t.ctx.currentTime,.1)):o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},e.prototype.orientation=function(e,n,r,o,i,a){var s=this;if(!s.ctx||!s.ctx.listener)return s;var _=s._orientation;return n="number"!=typeof n?_[1]:n,r="number"!=typeof r?_[2]:r,o="number"!=typeof o?_[3]:o,i="number"!=typeof i?_[4]:i,a="number"!=typeof a?_[5]:a,"number"!=typeof e?_:(s._orientation=[e,n,r,o,i,a],void 0!==s.ctx.listener.forwardX?(s.ctx.listener.forwardX.setTargetAtTime(e,t.ctx.currentTime,.1),s.ctx.listener.forwardY.setTargetAtTime(n,t.ctx.currentTime,.1),s.ctx.listener.forwardZ.setTargetAtTime(r,t.ctx.currentTime,.1),s.ctx.listener.upX.setTargetAtTime(o,t.ctx.currentTime,.1),s.ctx.listener.upY.setTargetAtTime(i,t.ctx.currentTime,.1),s.ctx.listener.upZ.setTargetAtTime(a,t.ctx.currentTime,.1)):s.ctx.listener.setOrientation(e,n,r,o,i,a),s)},n.prototype.init=(o=n.prototype.init,function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],o.call(this,e)}),n.prototype.stereo=function(e,n){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(e,n)}}),r;var o=void 0===t.ctx.createStereoPanner?"spatial":"stereo";if(void 0===n){if("number"!=typeof e)return r._stereo;r._stereo=e,r._pos=[e,0,0]}for(var a=r._getSoundIds(n),s=0;s{let e=!1;if(p)try{(await A.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===f.browser&&f.version>66||"Safari"===f.browser&&f.version>13||"OPR"===f.browser&&f.version>43||"Edge"===f.browser&&f.version;const R=(()=>{if(!c&&document.currentScript){let e=document.currentScript.src,t=e.indexOf("?");if(-1!=t)e=e.substring(0,t);else{let t=e.indexOf("#");-1!=t&&(e=e.substring(0,t))}return e.substring(0,e.lastIndexOf("/")+1)}return"./"})(),E=" is not allowed to change after `createInstance` or `loadWasm` is called.",T=!c&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",D=!c&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",S=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let t=0;te&&"object"==typeof e&&"function"==typeof e.then;class w extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(v(e)?this.task=e:(this._s="fulfilled",t(e)))},this.reject=e=>{this.isPending&&(this._s="rejected",n(e))},this.task=e}get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(e){let t;this._task=e,v(e)?t=e:"function"==typeof e&&(t=new Promise(e)),t&&(async()=>{try{const n=await t;e===this._task&&this.resolve(n)}catch(t){e===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}}const N=["iPhone","iPad","Android","HarmonyOS"].includes(f.OS)?2048:4096;class b{constructor(){this._instanceID=void 0,this._ifSaveOriginalImageInACanvas=!1,this.oriCanvas=null,this.oriCanvasData=null,this.canvas=null,this.bFilterRegionInJs=!1,this._region=null,this._timeStartDecode=null,this._timeEnterInnerDBR=null,this._timeGetMessage=null,this.decodeRecords={},this.bDestroyed=!1,this._lastErrorCode=0,this._lastErrorString="",this._lastInnerDecodeDuration=0,this.intervalTime=0,this._intervalGetVideoFrame=0,this.array_getFrameTimeCost=[],this.array_decodeFrameTimeCost=[],this._indexCurrentDecodingFrame=0,this._arrPolygons=[],this._bPauseScan=!1,this._intervalDetectVideoPause=1e3,this._soundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",this.beepSound=new n({src:["data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV"],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}}),this.bPlaySoundOnSuccessfulRead=!1,this.bVibrateOnSuccessfulRead=!1,this.vibrateDuration=300,this.captureAndDecodeInParallel=!0,this.autoSuggestTip=!1,this.suggestTipFrameArray=[],this.suggestTipFrameLimit=[5,3],this.noIntermediateResultsCount=0,this.noIntermediateResultsTipLimit=100,this.tinyBarcodeTipModuleSizeLimit=3,this.hugeBarcodeTipLimit=.9,this.autoZoomInFrameArray=[],this.autoZoomInFrameLimit=[5,3],this.autoZoomInStepRate=1/3,this.autoZoomInMaxStep=1.5,this.autoZoomInMaxTimes=5,this.autoZoomInMinStep=Math.pow(10,1/this.autoZoomInMaxTimes),this.autoZoomInIdealModuleSize=6,this.autoZoomOutFrameCount=0,this.autoZoomOutFrameLimit=3,this.autoZoomOutStepRate=1/3,this.autoZoomOutMinValue=1,this.autoZoomOutMinStep=2,this.autoZoomOutStepRate_2=.05,this.autoZoomOutMinValue_2=2,this.frameArrayInIdealZoom=[],this.frameLimitInIdealZoom=[5,3],this.enableZoomOutInIdealZoom=!1,this.nextActionInIdealZoom="focus",this.autoFocusFrameArray=[],this.autoFocusFrameLimit=[5,3],this.autoZoomIdealArea=[0,.05],this.autoZoomTargetBorder=.9,this.autoZoomDetectionArea=.5,this.autoZoom=!1,this.autoFocus=!1,this._resultHighlightingDuration=-1,this._dce=null,this._imgSource=null,this._maxCvsSideLength=N,this._promiseStartScan=null}static get version(){return this._version}static get license(){return this._license}static set license(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+E);n._license=t})(b,e)}static get productKeys(){return this._license}static set productKeys(e){b.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){b.license=e}static get organizationID(){return this._license}static set organizationID(e){b.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+E);n._sessionPassword=t})(b,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:g,worker:m,getUserMedia:p,camera:await I(),browser:f.browser,version:f.version,OS:f.OS}))()}static get engineResourcePath(){return this._engineResourcePath}static set engineResourcePath(e){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");b._engineResourcePath=(e=>{if(null==e&&(e="./"),!c){let t=document.createElement("a");t.href=e,e=t.href}return e.endsWith("/")||(e+="/"),e})(e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+E);n._licenseServer=S(t)})(b,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+E);n._deviceFriendlyName=t||""})(b,e)}static get _bUseFullFeature(){return this.__bUseFullFeature}static set _bUseFullFeature(e){if(!this._pLoad.isEmpty)throw new Error("`_bUseFullFeature` is not allowed to change after `createInstance` or `loadWasm` is called.");b.__bUseFullFeature=e}static isImageSource(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"getImage"in e}static isDSImage(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("width"in e&&("height"in e&&"pixelFormat"in e)))}static isDCEFrame(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("data"in e&&("region"in e&&("sx"in e&&("sy"in e&&("width"in e&&("height"in e&&(("colorMode"in e||"pixelFormat"in e)&&("timeSpent"in e&&("timeStamp"in e&&("isCropped"in e&&("toCanvas"in e&&("_sWidth"in e&&("_sHeight"in e&&"_bUseWebGL"in e)))))))))))))}get ifSaveOriginalImageInACanvas(){return this._ifSaveOriginalImageInACanvas}set ifSaveOriginalImageInACanvas(e){this._ifSaveOriginalImageInACanvas=e}getOriginalImageInACanvas(){return!this.oriCanvas&&this.oriCanvasData?this.oriCanvasData.toCanvas():this.oriCanvas}set region(e){this._region=e,this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0}get region(){return this._region}static isWasmLoaded(){return this._pLoad.isFulfilled}isContextDestroyed(){return this.bDestroyed}static get lastErrorCode(){return this._lastErrorCode}static get lastErrorString(){return this._lastErrorString}get lastErrorCode(){return this._lastErrorCode}get lastErrorString(){return this._lastErrorString}static get defaultUIElementURL(){var e;return null===(e=b._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",b.engineResourcePath)}static set defaultUIElementURL(e){b._defaultUIElementURL=e}static _fireHTTPSWarnning(){b.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{b.onWarning&&b.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}get soundSource(){return this._soundSource}set soundSource(e){this._soundSource=e,this.beepSound=new n({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}get whenToPlaySoundforSuccessfulRead(){return!0===this.bPlaySoundOnSuccessfulRead?"frame":this.bPlaySoundOnSuccessfulRead?this.bPlaySoundOnSuccessfulRead:"never"}set whenToPlaySoundforSuccessfulRead(e){this.bPlaySoundOnSuccessfulRead="never"!==e&&e}get whenToVibrateforSuccessfulRead(){return!0===this.bVibrateOnSuccessfulRead?"frame":this.bVibrateOnSuccessfulRead?this.bVibrateOnSuccessfulRead:"never"}set whenToVibrateforSuccessfulRead(e){this.bVibrateOnSuccessfulRead="never"!==e&&e}set dce(e){this._dce=e}get dce(){return!this._dce||this._dce.isDisposed||this._dce.disposed?null:this._dce}set maxCvsSideLength(e){this._maxCvsSideLength=e,this._dceControler&&this._dceControler.setDisiredValue(this,"maxCvsSideLength",e)}get maxCvsSideLength(){return this._maxCvsSideLength}async _registerDCEControler(){if(!this.dce)return;b._onLog&&b._onLog("_registerDCEControler()");const e=this.dce;this._dceControler=e._createControler();const t=this._dceControler;t.register(this),t.setDisiredValue(this,"refreshInterval",200),t.setDisiredValue(this,"maxCvsSideLength",this._maxCvsSideLength),this._styleIdBeforeVerification=this.dce.createDrawingStyle({fillStyle:"rgba(248,252,0,0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill"});try{ResizeObserver}catch(e){"ReferenceError"===e.name&&window&&(window.ResizeObserver=void 0)}const n=e.getUIElement(),r=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===r._defaultUIElementURL)try{n?n===t._innerSetUI&&(await e.setUIElement(`${r.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${r.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(r.defaultUIElementURL)}else n||await e.setUIElement(r.defaultUIElementURL);this.callbackCameraChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackResolutionChange=()=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0},this.callbackCameraClose=()=>{this.stopScanning(!0),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._bPauseScan=!1},this.callbackSingleFrameAcquired=async e=>{this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null);let t=await this._decode_DCEFrame(e,{bCopyData:!1}),n=null;if(t&&t.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;n=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),b.recalculateResultLocation(n,r,o,s,_,i,a)}if(this._drawResults(n,t),await this.clearMapDecodeRecord(),this.onImageRead&&this.dce.isOpen()&&!this._bPauseScan){let e=this._cloneDecodeResults(t);this.onImageRead(e)}if(this.onUniqueRead&&this.dce.isOpen()&&!this._bPauseScan)for(let e of t)this.onUniqueRead(e.barcodeText,this._cloneDecodeResults(e))},e.on("cameraChange",this.callbackCameraChange),e.on("resolutionChange",this.callbackResolutionChange),e.on("cameraClose",this.callbackCameraClose),e.on("singleFrameAcquired",this.callbackSingleFrameAcquired)}_logoutDCEControler(){this.dce&&this._dceControler&&(b._onLog&&b._onLog("_logoutDCEControler()"),this._dceControler.logout(this),this.dce.off("cameraChange",this.callbackCameraChange),this.dce.off("resolutionChange",this.callbackResolutionChange),this.dce.off("cameraClose",this.callbackCameraClose),this.dce.off("singleFrameAcquired",this.callbackSingleFrameAcquired),this._dceControler=null,this.dce=null)}async setImageSource(e,t){if(null==e)return this._imgSource=null,this._logoutDCEControler(),void(this._drawingItemNamespace=null);if(e&&e.isCameraEnhancer)this.dce=e,await this._registerDCEControler(),this._imgSource=null;else{if(!b.isImageSource(e))throw new Error("Invalid value.");this._logoutDCEControler(),this._imgSource=e}t&&t.resultsHighlightBaseShapes&&(this._drawingItemNamespace=t.resultsHighlightBaseShapes)}static async loadWasm(){if(this._pLoad.isEmpty){let{lt:e,l:t,ls:n,sp:r,rmk:o}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,n,r=t._license||"",o=JSON.parse(JSON.stringify(t._licenseServer)),i=t._sessionPassword,a=0;if(r.startsWith("t")||r.startsWith("f"))a=0;else if(0===r.length||r.startsWith("P")||r.startsWith("L")||r.startsWith("Y")||r.startsWith("A"))a=1;else{a=2;const t=r.indexOf(":");if(-1!=t&&(r=r.substring(t+1)),r.startsWith("DLS2")){let t;try{let e=r.substring(4);e=atob(e),t=JSON.parse(e)}catch(e){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(r=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof r&&(r=JSON.stringify(r)),0===o.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),o=S(e)}!i&&t.sessionPassword&&(i=t.sessionPassword),e=t.remark}("200001"===r||r.startsWith("200001-"))&&(o&&o.length||(r="")),r||(a=1)}if(a&&(globalThis.crypto||(n="Please upgrade your browser to support online key."),globalThis.crypto.subtle||(n="Require https to use online key in this browser.")),n){if(1!==a)throw new Error(n);a=0,console.warn(n),t._lastErrorCode=-1,t._lastErrorString=n}return 1===a&&(r="",console.warn("Applying for a public trial license ...")),{lt:a,l:r,ls:o,sp:i,rmk:e}}throw new Error("Can't preprocess license again"+E)})(b);this._pLoad.task=async(i,a)=>{let s=b.engineResourcePath+b._workerName;b.engineResourcePath.startsWith(location.origin)||(s=await fetch(s).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),b._dbrWorker=new Worker(s),b._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},b._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":b._onLog&&b._onLog(n.message);break;case"load":{n.message&&(n.message=n.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,r=!1;1===e&&(r=!0,n.message||(n.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),n.success?(b._dbrWorker.onerror=null,b._version=n.version+"(JS "+b._jsVersion+"."+b._jsEditVersion+")",b._onLog&&b._onLog("load dbr worker success"),n.message&&console.warn(n.message)):(t=new Error(n.message),t.stack=n.stack+"\n"+t.stack,t.ltsErrorCode=n.ltsErrorCode,r||111==n.ltsErrorCode&&-1!=n.message.toLowerCase().indexOf("trial license")&&(r=!0)),r&&b.showDialog(n.success?"warn":"error",n.message),n.success?i():a(t);break}case"task":{let e=n.id,t=n.body;try{b._taskCallbackMap.get(e)(t),b._taskCallbackMap.delete(e)}catch(t){throw b._taskCallbackMap.delete(e),t}break}default:b._onLog&&b._onLog(t)}},b._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:b.engineResourcePath,bUseFullFeature:b._bUseFullFeature,bd:b._bWasmDebug,v:b._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:f,cv:b.authCacheVersion,fn:b.deviceFriendlyName,ls:n,sp:r,rmk:o})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,n)=>{if(!e._bNeverShowDialog)try{let r=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!r.ok)throw Error("Get license dialog fail. Network Error: "+r.statusText);let o=await r.text();if(!o.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let i=document.createElement("div");i.innerHTML=o;let a=[];for(let e=0;e{if(e==t.target){s.remove();for(let e of a)e.remove()}}));else if(!d&&e.classList.contains("dls-license-icon-close"))d=e,e.addEventListener("click",(()=>{s.remove();for(let e of a)e.remove()}));else if(!c&&e.classList.contains("dls-license-icon-error"))c=e,"error"!=t&&e.remove();else if(!u&&e.classList.contains("dls-license-icon-warn"))u=e,"warn"!=t&&e.remove();else if(!l&&e.classList.contains("dls-license-msg-content")){l=e;let t=n;for(;t;){let n=t.indexOf("["),r=t.indexOf("]",n),o=t.indexOf("(",r),i=t.indexOf(")",o);if(-1==n||-1==r||-1==o||-1==i){e.appendChild(new Text(t));break}n>0&&e.appendChild(new Text(t.substring(0,n)));let a=document.createElement("a"),s=t.substring(n+1,r);a.innerText=s;let _=t.substring(o+1,i);a.setAttribute("href",_),a.setAttribute("target","_blank"),e.appendChild(a),t=t.substring(i+1)}}document.body.appendChild(s)}catch(t){e._onLog&&e._onLog(t.message||t)}})(this,e,t)}static async createInstanceInWorker(e=!1){return await b.loadWasm(),await new Promise(((t,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success)return t(e.instanceID);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),b._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){let e=new b;return e._instanceID=await b.createInstanceInWorker(),b._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){b._onLog&&b._onLog("decode(source: any)"),b._onLog&&(this._timeStartDecode=Date.now());{let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),e instanceof Blob?await this._decode_Blob(e,t):e instanceof ArrayBuffer?await this._decode_ArrayBuffer(e,t):e instanceof Uint8Array||e instanceof Uint8ClampedArray?await this._decode_Uint8Array(e,t):e instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?await this._decode_Image(e,t):e instanceof HTMLCanvasElement?await this._decode_Canvas(e,t):e instanceof HTMLVideoElement?await this._decode_Video(e,t):"string"==typeof e?"data:image/"==e.substring(0,11)?await this._decode_Base64(e,t):await this._decode_Url(e,t):b.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):b.isDSImage(e)?(t.bCopyData=!0,await this._decode_DSImage(e,t)):await Promise.reject(TypeError("'_decode(source, config)': Type of 'source' should be 'Blob', 'ArrayBuffer', 'Uint8Array', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement', 'String(base64 with image mime)' or 'String(url)'."))}}async decodeBase64String(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Base64(e,t)}async decodeUrl(e){let t={};return!this.region||this.region instanceof Array||(t.region=JSON.parse(JSON.stringify(this.region))),this._decode_Url(e,t)}async _decodeBuffer_Uint8Array(e,t,n,r,o,i,a){return await new Promise(((s,_)=>{let d=b._nextTaskID++;b._taskCallbackMap.set(d,(e=>{if(e.success){let t,n=b._onLog?Date.now():0;b._onLog&&b._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return _(e)}if(b._onLog){let e=Date.now();b._onLog("DBR getting message from worker timestamp: "+n),b._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),b._onLog("From DBR entering worker to returning message from worker costs: "+(n-this._timeEnterInnerDBR)),b._onLog("Handling results from DBR worker costs: "+(e-n)),b._onLog("Total decoding image costs: "+(e-this._timeStartDecode))}return s(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,_(t)}})),this._timeEnterInnerDBR=Date.now(),b._onLog&&b._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),b._dbrWorker.postMessage({type:"decodeBuffer",id:d,instanceID:this._instanceID,body:{buffer:e,width:t,height:n,stride:r,format:o,orientation:i,config:a}},[e.buffer]),b._onLog&&a&&a.timeStamp&&b._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-a.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,r,o,i,a){b._onLog&&b._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const s=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,n)=>{let r=new FileReader;r.readAsArrayBuffer(e),r.onload=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(s),t,n,r,o,i,a)}async decodeBuffer(e,t,n,r,o,i,a){let s;return b._onLog&&b._onLog("decodeBuffer(buffer,width,height,stride,format)"),b._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?s=await this._decodeBuffer_Uint8Array(e,t,n,r,o,i,a):e instanceof ArrayBuffer?s=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,n,r,o,i,a):e instanceof Blob&&(s=await this._decodeBuffer_Blob(e,t,n,r,o,i,a)),s}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success){let r;this._lastInnerDecodeDuration=e.duration;try{r=this._handleRetJsonString(e.decodeReturn)}catch(e){return n(e)}return t(r)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),b._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success){let t=JSON.parse(n.results);return null!=this.userDefinedRegion&&(t.region=JSON.parse(JSON.stringify(this.userDefinedRegion))),e(t)}{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"getRuntimeSettings",id:n,instanceID:this._instanceID})}))}async updateRuntimeSettings(e){let t;if("string"==typeof e)if("speed"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,0,0,0,0,0,0,0]}else if("balance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=5,t.expectedBarcodesCount=512,t.localizationModes=[2,16,0,0,0,0,0,0]}else if("coverage"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region}else if("dense"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=9,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else if("distance"==e){let e=await this.getRuntimeSettings();await this.resetRuntimeSettings(),this.maxCvsSideLength=4096,t=await this.getRuntimeSettings(),t.barcodeFormatIds=e.barcodeFormatIds,t.barcodeFormatIds_2=e.barcodeFormatIds_2,t.region=e.region,t.deblurLevel=3,t.expectedBarcodesCount=0,t.localizationModes=[2,8,0,0,0,0,0,0]}else t=JSON.parse(e);else{if("object"!=typeof e)throw TypeError("'UpdateRuntimeSettings(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");if(t=JSON.parse(JSON.stringify(e)),t.region instanceof Array){let e=t.region;[e.regionLeft,e.regionTop,e.regionLeft,e.regionBottom,e.regionMeasuredByPercentage].some((e=>void 0!==e))&&(t.region={regionLeft:e.regionLeft||0,regionTop:e.regionTop||0,regionRight:e.regionRight||0,regionBottom:e.regionBottom||0,regionMeasuredByPercentage:e.regionMeasuredByPercentage||0})}}if(!b._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(L.BF_ONED|L.BF_QR_CODE|L.BF_PDF417|L.BF_DATAMATRIX))||0!=t.barcodeFormatIds_2)throw Error("Some of the specified barcode formats are not supported in the compact version. Please try the full-featured version.");if(0!=t.intermediateResultTypes)throw Error("Intermediate results is not supported in the compact version. Please try the full-featured version.")}if(this.bFilterRegionInJs){let e=t.region;if(e instanceof Array)throw Error("The `region` of type `Array` is only allowed in `BarcodeScanner`.");this.userDefinedRegion=JSON.parse(JSON.stringify(e)),(e.regionLeft||e.regionTop||e.regionRight||e.regionBottom||e.regionMeasuredByPercentage)&&(e.regionLeft||e.regionTop||100!=e.regionRight||100!=e.regionBottom||!e.regionMeasuredByPercentage)?this.region=e:this.region=null,t.region={regionLeft:0,regionTop:0,regionRight:0,regionBottom:0,regionMeasuredByPercentage:0}}else this.userDefinedRegion=null,this.region=null;return(this.autoZoom||this.autoFocus)&&(t.intermediateResultTypes|=M.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(t=>{if(t.success){try{this._handleRetJsonString(t.updateReturn)}catch(e){n(e)}return e()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),b._dbrWorker.postMessage({type:"updateRuntimeSettings",id:r,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=N,await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"resetRuntimeSettings",id:n,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=N,await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!b._bUseFullFeature)throw Error("outputRuntimeSettingsToString() is not supported in the compact version. Please try the full-featured version.");return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!b._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof e)e=e;else{if("object"!=typeof e)throw TypeError("'initRuntimeSettingstWithString(settings)': Type of 'settings' should be 'string' or 'PlainObject'.");e=JSON.stringify(e)}return await new Promise(((t,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(e=>{if(e.success){try{this._handleRetJsonString(e.initReturn)}catch(e){n(e)}return t()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}})),b._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){b._onLog&&b._onLog("_decode_Blob(blob: Blob)");let n=null,r=null;if("undefined"!=typeof createImageBitmap)try{n=await createImageBitmap(e)}catch(e){}n||(r=await function(e){return new Promise(((t,n)=>{let r=URL.createObjectURL(e),o=new Image;o.dbrObjUrl=r,o.src=r,o.onload=()=>{t(o)},o.onerror=e=>{n(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let o=await this._decode_Image(n||r,t);return n&&n.close(),o}async _decode_ArrayBuffer(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Uint8Array(e,t){return await this._decode_Blob(new Blob([e]),t)}async _decode_Image(e,t){b._onLog&&b._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),t=t||{};let n,r,o=e instanceof HTMLImageElement?e.naturalWidth:e.width,i=e instanceof HTMLImageElement?e.naturalHeight:e.height,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d",{willReadFrequently:!0}));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl),await this._decode_Canvas(s,t)}async _decode_Canvas(e,t){if(b._onLog&&b._onLog("_decode_Canvas(canvas:HTMLCanvasElement)"),e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";if(0===e.width||0===e.height)throw Error("The width or height of the 'canvas' is 0.");this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=e,this.oriCanvasData=null);let n=(e.ctx2d||e.getContext("2d",{willReadFrequently:!0})).getImageData(0,0,e.width,e.height).data;return await this._decodeBuffer_Uint8Array(n,e.width,e.height,4*e.width,C.IPF_ABGR_8888,0,t)}async _decode_Video(e,t){if(b._onLog&&b._onLog("_decode_Video(video)"),!(e instanceof HTMLVideoElement))throw TypeError("'_decode_Video(video [, config] )': Type of 'video' should be 'HTMLVideoElement'.");if(e.crossOrigin&&"anonymous"!=e.crossOrigin)throw"cors";t=t||{};let n,r,o=e.videoWidth,i=e.videoHeight,a=Math.max(o,i);if(a>this._maxCvsSideLength){let e=this._maxCvsSideLength/a;n=Math.round(o*e),r=Math.round(i*e)}else n=o,r=i;this.canvas||(this.canvas=document.createElement("canvas"));const s=this.canvas;s.width===n&&s.height===r||(s.width=n,s.height=r),s.ctx2d||(s.ctx2d=s.getContext("2d",{willReadFrequently:!0}));return s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),await this._decode_Canvas(s,t)}async _decode_DCEFrame(e,t){if(b._onLog&&b._onLog("_decode_DCEFrame(dceFrame)"),!b.isDCEFrame(e))return[];let n=[];this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,colorMode:e.colorMode,pixelFormat:e.pixelFormat,data:new Uint8Array(e.data),toCanvas:e.toCanvas});const{width:r,height:o,colorMode:i,pixelFormat:a,stride:s,timeStamp:_}=e;let d;d=t&&t.bCopyData?new Uint8Array(e.data):e.data;let c=null;if(t?(c=JSON.parse(JSON.stringify(t)),c.timeStamp=_):c={timeStamp:_},a&&s)if("grey"===a)n=await this._decodeBuffer_Uint8Array(d,r,o,s,C.IPF_GrayScaled,0,c);else if("rgba"===a)n=await this._decodeBuffer_Uint8Array(d,r,o,s,C.IPF_ABGR_8888,0,c);else{if("bgra"!==a)throw new Error(`Pixel format '${a}' is not supported to decode.`);n=await this._decodeBuffer_Uint8Array(d,r,o,s,C.IPF_ARGB_8888,0,c)}else if("grey"===i)n=await this._decodeBuffer_Uint8Array(d,r,o,r,C.IPF_GrayScaled,0,c);else if("rgba"===i)n=await this._decodeBuffer_Uint8Array(d,r,o,4*r,C.IPF_ABGR_8888,0,c);else{if("bgra"!==i)throw new Error(`Color mode '${i}' is not supported to decode.`);n=await this._decodeBuffer_Uint8Array(d,r,o,4*r,C.IPF_ARGB_8888,0,c)}return n}async _decode_DSImage(e,t){if(b._onLog&&b._onLog("_decode_DSImage(dsImage)"),!b.isDSImage(e))return null;this.ifSaveOriginalImageInACanvas&&(this.oriCanvas=null,this.oriCanvasData={width:e.width,height:e.height,pixelFormat:e.pixelFormat.toLowerCase(),data:new Uint8Array(e.data),toCanvas:function(){const e=document.createElement("canvas");let t;switch(e.width=this.width,e.height=this.height,this.pixelFormat){case"grey":t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{let r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="blob",r.send(),r.onloadend=async()=>{t(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}}));return await this._decode_Blob(n,t)}}async _decode_FilePath(e,t){throw b._onLog&&b._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(e,t,n,r,o,i,a){if(e.length>0)for(let s of e){let e=s.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*i,e.x2*=.01*i,e.x3*=.01*i,e.x4*=.01*i,e.y1*=.01*a,e.y2*=.01*a,e.y3*=.01*a,e.y4*=.01*a);let _=i/r,d=a/o;e.x1=e.x1/_+t,e.x2=e.x2/_+t,e.x3=e.x3/_+t,e.x4=e.x4/_+t,e.y1=e.y1/d+n,e.y2=e.y2/d+n,e.y3=e.y3/d+n,e.y4=e.y4/d+n,2==e.resultCoordinateType&&(e.x1*=100/r,e.x2*=100/r,e.x3*=100/r,e.x4*=100/r,e.y1*=100/o,e.y2*=100/o,e.y3*=100/o,e.y4*=100/o)}}static BarcodeReaderException(e,t){let n,r=y.DBR_UNKNOWN;return"number"==typeof e?(r=e,n=new Error(t)):n=new Error(e),n.code=r,n}_handleRetJsonString(e){let t=y;if(e.textResults){for(let t=0;t{let n=t.indexOf(":");e[t.substring(0,n)]=t.substring(n+1)})),n.exception=e}}return e.decodeRecords?this.decodeRecords=e.decodeRecords:this.decodeRecords={},this._lastErrorCode=e.exception,this._lastErrorString=e.description,e.exception&&!b._setWarnnedEx.has(e.description)&&(b._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw b.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,n,r){return await new Promise(((o,i)=>{let a=b._nextTaskID++;b._taskCallbackMap.set(a,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return i(e)}return o()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),b._dbrWorker.postMessage({type:"setModeArgument",id:a,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n,argumentValue:r}})}))}async getModeArgument(e,t,n){return await new Promise(((r,o)=>{let i=b._nextTaskID++;b._taskCallbackMap.set(i,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return o(e)}return r(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}})),b._dbrWorker.postMessage({type:"getModeArgument",id:i,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:n}})}))}async getIntermediateResults(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success)return e(n.results);{let e=new Error(n.message);return e.stack=n.stack+"\n"+e.stack,t(e)}})),b._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let n of e)if(n.dataType==O.IMRDT_IMAGE)for(let e of n.results){const n=e.bytes;let r;switch(b._onLog&&b._onLog(" "+n.length+" "+n.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case C.IPF_ABGR_8888:r=new Uint8ClampedArray(n);break;case C.IPF_RGB_888:{const e=n.length/3;r=new Uint8ClampedArray(4*e);for(let t=0;t=o)break;r[a]=r[a+1]=r[a+2]=(128&t)/128*255,r[a+3]=255,t<<=1}}break}default:console.warn("unknow intermediate image",e)}if(!r)continue;let o=new ImageData(r,e.width,e.height),i=document.createElement("canvas");i.width=e.width,i.height=e.height,i.getContext("2d").putImageData(o,0,0),t.push(i)}return t}async getScanSettings(){return await new Promise(((e,t)=>{let n=b._nextTaskID++;b._taskCallbackMap.set(n,(n=>{if(n.success){let t=n.results;return t.intervalTime=this.intervalTime,t.whenToPlaySoundforSuccessfulRead=this.whenToPlaySoundforSuccessfulRead,t.soundOnSuccessfullRead=this.soundSource,t.whenToVibrateforSuccessfulRead=this.whenToVibrateforSuccessfulRead,t.vibrateDuration=this.vibrateDuration,t.captureAndDecodeInParallel=this.captureAndDecodeInParallel,t.autoZoom=this.autoZoom,t.autoFocus=this.autoFocus,t.autoSuggestTip=this.autoSuggestTip,e(t)}{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),b._dbrWorker.postMessage({type:"getScanSettings",id:n,instanceID:this._instanceID})}))}async updateScanSettings(e){if(!e)return;const t=JSON.parse(JSON.stringify(e));if(t.autoZoom||t.autoFocus||t.autoSuggestTip){if(!b._bUseFullFeature)throw new Error("'autoZoom', 'autoFocus' and 'autoSuggestTip' are not supported in the compact version. Please try the full-featured version.");const e=await this.getRuntimeSettings();e.intermediateResultTypes|=M.IRT_TYPED_BARCODE_ZONE,await this.updateRuntimeSettings(e)}return t.hasOwnProperty("intervalTime")&&(this.intervalTime=Math.max(t.intervalTime,0),delete t.intervalTime),t.hasOwnProperty("whenToPlaySoundforSuccessfulRead")&&(this.whenToPlaySoundforSuccessfulRead=t.whenToPlaySoundforSuccessfulRead,delete t.whenToPlaySoundforSuccessfulRead),t.hasOwnProperty("soundOnSuccessfullRead")&&(this.soundSource=t.soundOnSuccessfullRead,delete t.soundOnSuccessfullRead),t.hasOwnProperty("whenToVibrateforSuccessfulRead")&&(this.whenToVibrateforSuccessfulRead=t.whenToVibrateforSuccessfulRead,delete t.whenToVibrateforSuccessfulRead),t.hasOwnProperty("vibrateDuration")&&(this.vibrateDuration=t.vibrateDuration,delete t.vibrateDuration),t.hasOwnProperty("captureAndDecodeInParallel")&&(this.captureAndDecodeInParallel=t.captureAndDecodeInParallel,delete t.captureAndDecodeInParallel),t.hasOwnProperty("autoZoom")&&(this.autoZoom&&this.autoZoom!=t.autoZoom&&this.dce&&this.dce.setZoom({factor:1}).catch((()=>{})),this.autoZoom=t.autoZoom,delete t.autoZoom),t.hasOwnProperty("autoFocus")&&(this.autoFocus=t.autoFocus,this.dce&&this.dce.setFocus({mode:"continuous"}).catch((()=>{})),delete t.autoFocus),t.hasOwnProperty("autoSuggestTip")&&(this.autoSuggestTip=t.autoSuggestTip,delete t.autoFocus),await new Promise(((e,n)=>{let r=b._nextTaskID++;b._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,n(e)}})),b._dbrWorker.postMessage({type:"updateScanSettings",id:r,instanceID:this._instanceID,body:{settings:t}})}))}_cloneDecodeResults(e){if(e instanceof Array){let t=[];for(let n of e)t.push(this._cloneDecodeResults(n));return t}{let t=e;return JSON.parse(JSON.stringify(t,((e,t)=>"oriVideoCanvas"==e||"searchRegionCanvas"==e?void 0:t)))}}async _loopReadVideo(){if(this.bDestroyed)return this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),void this._drawResults(null);if(this.dce&&!this.dce.isOpen())return this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),void await this.clearMapDecodeRecord();if(!this.dce&&!this._imgSource||this._bPauseScan)return b._onLog&&b._onLog("Scan is paused, or imageSource is not set. Ask in 1s."),await this.clearMapDecodeRecord(),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this._intervalDetectVideoPause));b._onLog&&b._onLog("======= once read ======="),b._onLog&&(this._timeStartDecode=Date.now());let e=null,t=null;if(this.dce)e=this._getVideoFrame();else if(this._imgSource&&(t=await this._imgSource.getImage(),!b.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return b._onLog&&b._onLog("Get invalid frame."),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),void(this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),0));(async()=>{let n=[];if(e){n=await this._decode_DCEFrame(e,{bScanner:!0,bCopyData:!1});let t=null;if(n&&n.length){const{sx:r,sy:o,width:i,height:a,_sWidth:s,_sHeight:_}=e;t=n.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),b.recalculateResultLocation(t,r,o,s,_,i,a)}0==this._resultHighlightingDuration?this._drawResults(null):this._drawResults(t,n),this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._resultHighlightingDuration>0&&(this._clearResultsCanvasTimeoutId=setTimeout((()=>{this.bDestroyed||this._drawResults(null)}),this._resultHighlightingDuration))}else t&&(n=await this._decode_DSImage(t,{bScanner:!0,bCopyData:!1}));return n})().then((e=>{if(b._onLog&&b._onLog(e),this.dce&&this.captureAndDecodeInParallel){let e=this.array_decodeFrameTimeCost,t=this.array_getFrameTimeCost;const n=()=>{let n=0;if(t&&t.length){let r=Math.min(...e),o=Math.max(...t);r&&o&&(n=r-o)}else n=0;return n>0?n:0};(()=>{for(;e.length>=5;)e.shift();e.push(this._lastInnerDecodeDuration)})(),this._intervalGetVideoFrame=n()+this.intervalTime}if((this.dce&&this.dce.isOpen()||this._imgSource)&&!this._bPauseScan){if(this.bPlaySoundOnSuccessfulRead&&e.length){let t=!1;!0===this.bPlaySoundOnSuccessfulRead||"frame"===this.bPlaySoundOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bPlaySoundOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t&&(this.beepSound.stop(),this.beepSound.play())}if(navigator.vibrate&&this.bVibrateOnSuccessfulRead&&e.length){let t=!1;if(!0===this.bVibrateOnSuccessfulRead||"frame"===this.bVibrateOnSuccessfulRead?t=e.some((e=>e.resultState>=0)):"unique"===this.bVibrateOnSuccessfulRead&&(t=e.some((e=>0==e.resultState))),t)try{navigator.vibrate(this.vibrateDuration)}catch(e){console.warn("Vibration not allowed. User interaction required: "+(e.message||e))}}if(this.onImageRead){e=e.filter((e=>e.resultState>=0));const t=this._cloneDecodeResults(e);this.onImageRead(t)}if(this.onUniqueRead){e=e.filter((e=>0==e.resultState));const t=this._cloneDecodeResults(e);for(let e of t)this.onUniqueRead(e.barcodeText,e)}}this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.intervalTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo()}),this.intervalTime):this._loopReadVideo()})).catch((e=>{this.dce&&this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),b._onLog&&b._onLog(e.message||e),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),Math.max(this.intervalTime,1e3)),"platform error"==e.message||console.warn(e.message)}))}_getVideoFrame(){if(!this.dce)return null;let e;if(this.captureAndDecodeInParallel){if(b._onLog&&b._onLog("Get frame in parallel."),this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",this._intervalGetVideoFrame),!this.dce.numberOfFramesInBuffer)return this._dceControler&&this._dceControler.setDisiredValue(this,"loopInterval",0),null;e=this.dce.getFrameFromBuffer();const t=e=>{if(!e)return;let t=e.timeSpent,n=this.array_getFrameTimeCost;for(;n.length>=5;)n.shift();n.push(t)};t(e)}else b._onLog&&b._onLog("Get frame in serial."),this._dceControler&&this._dceControler.setDisiredAction(this,"stopFetchingLoop"),e=this.dce.getFrame();return e}_drawResults(e,t){if(!this.dce||this.dce.disposed||this._bPauseScan||!this._drawingItemNamespace||!this._drawingItemNamespace.DT_Polygon)return;if(!this._dbrDrawingLayer){if(!this.dce.isOpen())return;if(!(this.dce.singleFrameMode||this.dce.video&&this.dce._videoTrack))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const n=this._dbrDrawingLayer;e||(e=[]);let r=this._arrPolygons;for(let o=0;o{this.dce&&(this.dce.startFetchingLoop(),this._dceControler&&this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"})),this._loopReadVideo()}),0)),this._promiseStartScan.resolve(t),t}stopScanning(e){this.dce&&(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),this._drawResults(null),this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"close",[e]))),this._bPauseScan=!0,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this.array_decodeFrameTimeCost.length=0,this.array_getFrameTimeCost.length=0,this._intervalGetVideoFrame=0,this._promiseStartScan=null}pauseScanning(e){if(this._clearResultsCanvasTimeoutId&&clearTimeout(this._clearResultsCanvasTimeoutId),e&&e.keepResultsHighlighted||this._drawResults(null),this._bPauseScan=!0,this.dce){if(this.dce.singleFrameMode)throw new Error("'pauseScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this._dceControler&&(this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!1),this.dce.ifShowScanRegionLaser||this.dce.hideScanRegionLaser(),this._dceControler.setDisiredAction(this,"stopFetchingLoop"))}}resumeScanning(){if(this._bPauseScan=!1,this.dce){if(this.dce.singleFrameMode)throw new Error("'resumeScanning()' is unavailable when property 'singleFrameMode' of the 'CameraEnhancer' instance is true.");this.dce.startFetchingLoop(),this._dceControler&&(this._dceControler.clearUserDisiredAction({user:this,actionName:"stopFetchingLoop"}),this._dceControler.clearUserDisiredValue({property:"ifShowScanRegionLaser"}),this._dceControler.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(b._onLog&&b._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,!this.dce&&this._promiseStartScan||this.stopScanning(),this.setImageSource(null);let e=b._nextTaskID++;b._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),b._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}var B,P,F,V,x,k,U,G,H,K,W,Z,Y,Q,J,X,j,q,$,z,ee,te,ne,re,oe,ie;b._jsVersion="9.6.11",b._jsEditVersion="20230310",b._version=`loading...(JS ${b._jsVersion}.${b._jsEditVersion})`,b._license=T,b._sessionPassword=D,b.browserInfo=f,b._workerName=`dbr-${b._jsVersion}.browser.worker.js`,b._engineResourcePath=R,b._licenseServer=[],b._deviceFriendlyName="",b._isShowRelDecodeTimeInResults=!1,b._bWasmDebug=!1,b._bNeverShowDialog=!1,b.__bUseFullFeature=!0,b._nextTaskID=0,b._taskCallbackMap=new Map,b._pLoad=new w,b._lastErrorCode=0,b._lastErrorString="",b._setWarnnedEx=new Set,b._defaultUIElementURL="@engineResourcePath/dbr.ui.html",function(e){e[e.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",e[e.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",e[e.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",e[e.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",e[e.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",e[e.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",e[e.BICM_SKIP=0]="BICM_SKIP",e[e.BICM_REV=2147483648]="BICM_REV"}(B||(B={})),function(e){e[e.BCM_AUTO=1]="BCM_AUTO",e[e.BCM_GENERAL=2]="BCM_GENERAL",e[e.BCM_SKIP=0]="BCM_SKIP",e[e.BCM_REV=2147483648]="BCM_REV"}(P||(P={})),function(e){e[e.BF2_NULL=0]="BF2_NULL",e[e.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",e[e.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",e[e.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",e[e.BF2_POSTNET=2097152]="BF2_POSTNET",e[e.BF2_PLANET=4194304]="BF2_PLANET",e[e.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",e[e.BF2_RM4SCC=16777216]="BF2_RM4SCC",e[e.BF2_DOTCODE=2]="BF2_DOTCODE",e[e.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",e[e.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",e[e.BF2_PHARMACODE=12]="BF2_PHARMACODE",e[e.BF2_ALL=4294967295]="BF2_ALL"}(F||(F={})),function(e){e[e.BM_AUTO=1]="BM_AUTO",e[e.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",e[e.BM_SKIP=0]="BM_SKIP",e[e.BM_THRESHOLD=4]="BM_THRESHOLD",e[e.BM_REV=2147483648]="BM_REV"}(V||(V={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(x||(x={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(k||(k={})),function(e){e[e.CCM_AUTO=1]="CCM_AUTO",e[e.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",e[e.CCM_SKIP=0]="CCM_SKIP",e[e.CCM_REV=2147483648]="CCM_REV"}(U||(U={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(G||(G={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(H||(H={})),function(e){e[e.DM_SKIP=0]="DM_SKIP",e[e.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",e[e.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",e[e.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",e[e.DM_SMOOTHING=8]="DM_SMOOTHING",e[e.DM_MORPHING=16]="DM_MORPHING",e[e.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",e[e.DM_SHARPENING=64]="DM_SHARPENING",e[e.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",e[e.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING"}(K||(K={})),function(e){e[e.DRM_AUTO=1]="DRM_AUTO",e[e.DRM_GENERAL=2]="DRM_GENERAL",e[e.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",e[e.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",e[e.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",e[e.DRM_SKIP=0]="DRM_SKIP",e[e.DRM_REV=2147483648]="DRM_REV"}(W||(W={})),function(e){e[e.DPMCRM_AUTO=1]="DPMCRM_AUTO",e[e.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",e[e.DPMCRM_SKIP=0]="DPMCRM_SKIP",e[e.DPMCRM_REV=2147483648]="DPMCRM_REV"}(Z||(Z={})),function(e){e[e.GTM_INVERTED=1]="GTM_INVERTED",e[e.GTM_ORIGINAL=2]="GTM_ORIGINAL",e[e.GTM_SKIP=0]="GTM_SKIP",e[e.GTM_REV=2147483648]="GTM_REV"}(Y||(Y={})),function(e){e[e.IPM_AUTO=1]="IPM_AUTO",e[e.IPM_GENERAL=2]="IPM_GENERAL",e[e.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",e[e.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",e[e.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",e[e.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",e[e.IPM_SKIP=0]="IPM_SKIP",e[e.IPM_REV=2147483648]="IPM_REV"}(Q||(Q={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(J||(J={})),function(e){e[e.LM_SKIP=0]="LM_SKIP",e[e.LM_AUTO=1]="LM_AUTO",e[e.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",e[e.LM_LINES=8]="LM_LINES",e[e.LM_STATISTICS=4]="LM_STATISTICS",e[e.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",e[e.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",e[e.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",e[e.LM_CENTRE=128]="LM_CENTRE",e[e.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",e[e.LM_REV=2147483648]="LM_REV"}(X||(X={})),function(e){e[e.PDFRM_RASTER=1]="PDFRM_RASTER",e[e.PDFRM_AUTO=2]="PDFRM_AUTO",e[e.PDFRM_VECTOR=4]="PDFRM_VECTOR",e[e.PDFRM_REV=2147483648]="PDFRM_REV"}(j||(j={})),function(e){e[e.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",e[e.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",e[e.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",e[e.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q"}(q||(q={})),function(e){e[e.RPM_AUTO=1]="RPM_AUTO",e[e.RPM_GENERAL=2]="RPM_GENERAL",e[e.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",e[e.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",e[e.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",e[e.RPM_SKIP=0]="RPM_SKIP",e[e.RPM_REV=2147483648]="RPM_REV"}($||($={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(z||(z={})),function(e){e[e.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",e[e.RT_RAW_TEXT=1]="RT_RAW_TEXT",e[e.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",e[e.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT"}(ee||(ee={})),function(e){e[e.SUM_AUTO=1]="SUM_AUTO",e[e.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",e[e.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",e[e.SUM_SKIP=0]="SUM_SKIP",e[e.SUM_REV=2147483648]="SUM_REV"}(te||(te={})),function(e){e[e.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",e[e.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",e[e.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",e[e.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",e[e.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",e[e.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED"}(ne||(ne={})),function(e){e[e.TFM_AUTO=1]="TFM_AUTO",e[e.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",e[e.TFM_SKIP=0]="TFM_SKIP",e[e.TFM_REV=2147483648]="TFM_REV"}(re||(re={})),function(e){e[e.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",e[e.TROM_POSITION=2]="TROM_POSITION",e[e.TROM_FORMAT=4]="TROM_FORMAT",e[e.TROM_SKIP=0]="TROM_SKIP",e[e.TROM_REV=2147483648]="TROM_REV"}(oe||(oe={})),function(e){e[e.TDM_AUTO=1]="TDM_AUTO",e[e.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",e[e.TDM_SKIP=0]="TDM_SKIP",e[e.TDM_REV=2147483648]="TDM_REV"}(ie||(ie={}));export{b as BarcodeReader,B as EnumBarcodeColourMode,P as EnumBarcodeComplementMode,L as EnumBarcodeFormat,F as EnumBarcodeFormat_2,V as EnumBinarizationMode,x as EnumClarityCalculationMethod,k as EnumClarityFilterMode,U as EnumColourClusteringMode,G as EnumColourConversionMode,H as EnumConflictMode,Z as EnumDPMCodeReadingMode,K as EnumDeblurMode,W as EnumDeformationResistingMode,y as EnumErrorCode,Y as EnumGrayscaleTransformationMode,O as EnumIMResultDataType,C as EnumImagePixelFormat,Q as EnumImagePreprocessingMode,J as EnumIntermediateResultSavingMode,M as EnumIntermediateResultType,X as EnumLocalizationMode,j as EnumPDFReadingMode,q as EnumQRCodeErrorCorrectionLevel,$ as EnumRegionPredetectionMode,z as EnumResultCoordinateType,ee as EnumResultType,te as EnumScaleUpMode,ne as EnumTerminatePhase,re as EnumTextFilterMode,oe as EnumTextResultOrderMode,ie as EnumTextureDetectionMode}; diff --git a/dist/types/class/barcodereader.d.ts b/dist/types/class/barcodereader.d.ts index e0fca57..196da76 100644 --- a/dist/types/class/barcodereader.d.ts +++ b/dist/types/class/barcodereader.d.ts @@ -100,6 +100,7 @@ export default class BarcodeReader { static get deviceFriendlyName(): string; /** @ignore */ static set deviceFriendlyName(value: string); + static authCacheVersion: string; /** @ignore */ static _isShowRelDecodeTimeInResults: boolean; /** @ignore */ diff --git a/dist/types/class/barcodescanner.d.ts b/dist/types/class/barcodescanner.d.ts index a1e0318..1d716fc 100644 --- a/dist/types/class/barcodescanner.d.ts +++ b/dist/types/class/barcodescanner.d.ts @@ -314,6 +314,7 @@ export default class BarcodeScanner extends BarcodeReader { */ isOpen(): boolean; setVideoFit(value: string): void; + getVideoFit(): string; /** * Whether to show scan region mask. */ @@ -626,6 +627,27 @@ export default class BarcodeScanner extends BarcodeReader { enableTapToFocus(): Promise; disableTapToFocus(): void; isTapToFocusEnabled(): boolean; + /** + * Transform the coordinates from related to the video to related to the viewport and document. + * @param coord + * @returns + * @private + */ + private transformCoord; + convertToPageCoordinates(point: { + x: number; + y: number; + }): { + x: number; + y: number; + }; + convertToClientCoordinates(point: { + x: number; + y: number; + }): { + x: number; + y: number; + }; /** * Destroy the `BarcodeScanner` instance. If your page needs to create new instances from time to time, don't forget to destroy unused old instances, otherwise it will cause memory leaks. * @category Initialize and Destroy diff --git a/package.json b/package.json index 9ee4a4c..9ca2ff0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dynamsoft-javascript-barcode", - "version": "9.6.10", + "version": "9.6.11", "description": "Dynamsoft Barcode Reader JS is a recognition SDK which enables you to embed barcode reading functionality in your web, desktop, and mobile applications. With a few lines of JavaScript code, you can develop a robust application to scan a linear barcode, QR Code, DaraMatrix, PDF417, and Aztec Code.", "private": false, "files": [ @@ -66,7 +66,7 @@ "@rollup/plugin-typescript": "8.3.0", "@scannerproxy/browser-info": "^1.0.7", "@scannerproxy/curscript-path": "^1.0.3", - "@scannerproxy/dlsjs": "^2.0.5", + "@scannerproxy/dlsjs": "^2.0.7", "@types/node": "16.11.2", "@types/node-fetch": "2.6.1", "@types/node-localstorage": "1.3.0", diff --git a/samples.url b/samples.url index e6f5037..90f8893 100644 --- a/samples.url +++ b/samples.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.10 \ No newline at end of file +URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.11 \ No newline at end of file