diff --git a/.gitignore b/.gitignore index 1eb387f..cde928c 100644 --- a/.gitignore +++ b/.gitignore @@ -21,7 +21,7 @@ yarn-error.log* *.sln *.sw? *.map -.npmrc +*.properties __pycache__ ~~* @@ -30,6 +30,7 @@ __pycache__ package-lock.json yarn.lock .git +.npmrc /*.zip /*.py /*.exe diff --git a/Api Reference.url b/API Reference.url similarity index 74% rename from Api Reference.url rename to API Reference.url index 7269631..5c9fd33 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.32 \ No newline at end of file +URL=https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.6.42 \ No newline at end of file diff --git a/LEGAL.txt b/LEGAL.txt new file mode 100644 index 0000000..3891d15 --- /dev/null +++ b/LEGAL.txt @@ -0,0 +1,533 @@ +=================================================================================== +>>>>>>>>>>>>>>>>>>>>>>>>>> dynamsoft-javascript-barcode <<<<<<<<<<<<<<<<<<<<<<<<<<< +=================================================================================== + +Legal Notices: + +This SDK contains parts of following softwares which are used under license. + +=================================================================================== +Zlib. + +Copyright notice: + + (C) 1995-2022 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +=================================================================================== + + + +=================================================================================== +Google's open-source ZXing ("Zebra Crossing") + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following +boilerplate notice, with the fields enclosed by brackets "[]" +replaced with your own identifying information. (Don't include +the brackets!) The text should be enclosed in the appropriate +comment syntax for the file format. We also recommend that a +file or class name and description of purpose be included on the +same "printed page" as the copyright notice for easier +identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +=================================================================================== + + + +=================================================================================== +OpenCV + +License Agreement +For Open Source Computer Vision Library +(3-clause BSD License) + +Copyright (C) 2000-2015, Intel Corporation, all rights reserved. +Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. +Copyright (C) 2009-2015, NVIDIA Corporation, all rights reserved. +Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +Copyright (C) 2015, OpenCV Foundation, all rights reserved. +Copyright (C) 2015, Itseez Inc., all rights reserved. +Third party copyrights are property of their respective owners. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of +the use of this software, even if advised of the possibility of such damage. +=================================================================================== + + + +=================================================================================== +JsonCpp library + +The JsonCpp library's source code, including accompanying documentation, +tests and demonstration applications, are licensed under the following +conditions... + +The author (Baptiste Lepilleur) explicitly disclaims copyright in all +jurisdictions which recognize such a disclaimer. In such jurisdictions, +this software is released into the Public Domain. + +In jurisdictions which do not recognize Public Domain property (e.g. Germany as of +2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is +released under the terms of the MIT License (see below). + +In jurisdictions which recognize Public Domain property, the user of this +software may choose to accept it either as 1) Public Domain, 2) under the +conditions of the MIT License (see below), or 3) under the terms of dual +Public Domain/MIT License conditions described here, as they choose. + +The MIT License is about as close to Public Domain as a license can get, and is +described in clear, concise terms at: + + http://en.wikipedia.org/wiki/MIT_License + +The full text of the MIT License follows: + +======================================================================== +Copyright (c) 2007-2010 Baptiste Lepilleur + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +======================================================================== +(END LICENSE TEXT) + +The MIT license is compatible with both the GPL and commercial +software, affording one all of the rights of Public Domain with the +minor nuisance of being required to keep the above copyright notice +and license text in the source code. Note also that by accepting the +Public Domain "license" you can re-license your copy using whatever +license you like. +=================================================================================== + + + +=================================================================================== +OpenSSL + + + LICENSE ISSUES + ============== + + The OpenSSL toolkit stays under a double license, i.e. both the conditions of + the OpenSSL License and the original SSLeay license apply to the toolkit. + See below for the actual license texts. + + OpenSSL License + --------------- + +/* ==================================================================== + * Copyright (c) 1998-2019 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + Original SSLeay License + ----------------------- + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +=================================================================================== + + + +=================================================================================== +howler + +Copyright (c) 2013-2020 James Simpson and GoldFire Studios, Inc. +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +=================================================================================== + + + +=================================================================================== +localForage + +-- Offline Storage, Improved +Version 1.7.3 +https://localforage.github.io/localForage +(c) 2013-2017 Mozilla, Apache License 2.0 +=================================================================================== + +=================================================================================== +Protocol Buffers + +This license applies to all parts of Protocol Buffers except the following: + + - Atomicops support for generic gcc, located in + src/google/protobuf/stubs/atomicops_internals_generic_gcc.h. + This file is copyrighted by Red Hat Inc. + + - Atomicops support for AIX/POWER, located in + src/google/protobuf/stubs/atomicops_internals_power.h. + This file is copyrighted by Bloomberg Finance LP. + +Copyright 2014, Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. +=================================================================================== \ No newline at end of file diff --git a/LICENSE b/LICENSE index d925ab9..6cce8bc 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright © 2003–2023 Dynamsoft. All Rights Reserved. +Copyright © 2003–2024 Dynamsoft. All Rights Reserved. The use of this software is governed by the Dynamsoft Terms and Conditions. https://www.dynamsoft.com/barcode-reader/license-agreement/#javascript \ No newline at end of file diff --git a/README.md b/README.md index 3b94752..fbd5871 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,11 @@ Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. -In this guide, you will learn step by step how to integrate the DBR-JS SDK into your website. + + +In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. Table of Contents @@ -29,21 +33,21 @@ In this guide, you will learn step by step how to integrate the DBR-JS SDK into **Popular Examples** -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/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.32&utm_source=github) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.32&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/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.32&utm_source=github) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.32&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/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.32&utm_source=github) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.32&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/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.32&utm_source=github) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.32&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/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.32&utm_source=github) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.32/1.hello-world/14.read-video-webview) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.32&utm_source=github&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/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.32&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.32/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.32&utm_source=github) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/4.use-case/3.show-result-texts-on-the-video.html?ver=9.6.32&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.32/5.others/debug) +- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/1.hello-world.html) +- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.42&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/3.read-video-angular) +- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.42&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/4.read-video-react) +- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.42&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/6.read-video-vue3) +- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.42&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/10.read-video-pwa) +- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.42/1.hello-world/14.read-video-webview) +- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.42&utm_source=github&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/4.use-case/2.read-a-drivers-license.html) +- 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.42/4.use-case/1.fill-a-form-with-barcode-reading.html) +- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) +- 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.42/5.others/debug) You can also: -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.32&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.32&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.32/) +- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.42&utm_source=github) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) +- Try Online Examples - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.42/) ## Hello World - Simplest Implementation @@ -63,9 +67,9 @@ The complete code of the "Hello World" example is shown below - + + ``` - UNPKG ```html - + ``` #### Host the SDK yourself @@ -165,24 +170,24 @@ Options to download the SDK: - From the website - Download the JavaScript Package + Download the JavaScript Package -- yarn +- npm ```cmd - yarn add dynamsoft-javascript-barcode + npm i dynamsoft-javascript-barcode -E ``` -- npm +- yarn ```cmd - npm install dynamsoft-javascript-barcode --save + yarn add dynamsoft-javascript-barcode -E ``` Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: ```html - + ``` or @@ -193,7 +198,7 @@ or or -```ts +```typescript import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; ``` @@ -224,7 +229,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.32&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.42&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. @@ -236,7 +241,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.32/dist/"; +Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/"; ``` ### Interact with the SDK @@ -331,9 +336,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.32&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.42&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) @@ -417,8 +422,8 @@ The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr. ```html ``` @@ -431,7 +436,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.32](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.32). +[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.42](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.42). ## System Requirements @@ -452,7 +457,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.32&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.42&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` @@ -477,7 +482,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.32&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.42&utm_source=github). ## Release Notes diff --git a/dist/dbr-9.6.32.browser.worker.js b/dist/dbr-9.6.32.browser.worker.js deleted file mode 100644 index 2031c10..0000000 --- a/dist/dbr-9.6.32.browser.worker.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Barcode Reader JS Edition - * @website http://www.dynamsoft.com - * @copyright Copyright 2023, Dynamsoft Corporation - * @author Dynamsoft - * @version 9.6.32 (js 20231027) - * @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,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&&([u,_]=JSON.parse(await W(e)))}catch(e){}try{null==u&&(u=H(),x.setItem(C,await z(JSON.stringify([u,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:u,ad:y,os:l,fn:f};w&&(t.rmk=w),s&&(-1!=s.indexOf("-")?t.hs=s:t.og=s);let n={};if(_){let e=await x.getItem(C);e&&([u,_]=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([u,o]))),_=o);let a="auth/?ext="+encodeURIComponent(m(JSON.stringify(t)));S&&(a+="&v="+encodeURIComponent(S));let s,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&&(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 l(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 l(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 l(r)}catch(e){}s&&151==s.errorCode&&(x.removeItem(C),x.removeItem(P),u=H(),t.cu=u,_=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 l(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([u,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(u),!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=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),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||"",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&&(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(),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.expectedBarcodesCount=1,n.deblurLevel=0,n.localizationModes=[16,2,0,0,0,0,0,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(a.isCharge),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)}}(); diff --git a/dist/dbr-9.6.42.browser.worker.js b/dist/dbr-9.6.42.browser.worker.js new file mode 100644 index 0000000..a51398b --- /dev/null +++ b/dist/dbr-9.6.42.browser.worker.js @@ -0,0 +1,11 @@ +/*! + * Dynamsoft JavaScript Library + * @product Dynamsoft Barcode Reader JS Edition + * @website http://www.dynamsoft.com + * @copyright Copyright 2024, Dynamsoft Corporation + * @author Dynamsoft + * @version 9.6.42 (js 20240426) + * @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;"undefined"!=typeof navigator&&(o=navigator,a=o.userAgent,s=o.platform,i=o.mediaDevices),function(){if(!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"})}(),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 _(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 x(e,t){var r=b[e.name].deferredOperations.pop();if(r)return r.reject(t),r.promise}function M(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);_(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 M(e,!1)}function D(e){return M(e,!0)}function P(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),D(e)})).then((()=>function(e){_(e);for(var t=b[e.name],r=t.forages,n=0;n(e.db=t,P(e)?D(e):t))).then((n=>{e.db=t.db=n;for(var o=0;o{throw x(e,t),t}))}(e).then((function(){T(e,t,r,n-1)})))).catch(r);r(o)}}var O={_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;_(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(x(e,t)||Promise.resolve()).catch((()=>{})),t}))})):t.then((t=>{_(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(x(e,t)||Promise.resolve()).catch((()=>{})),t}))}))}else r=Promise.reject("Invalid arguments");return f(r,t),r}};const E=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,E.has(r)||E.set(r,new Map)},getItem:function(e,t){e=h(e);const r=this.ready().then((()=>E.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),E.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((()=>{E.get(this._dbInfo.keyPrefix).delete(e)}));return f(r,t),r},clear:function(e){const t=this.ready().then((()=>{const e=this._dbInfo.keyPrefix;E.has(e)&&E.delete(e)}));return f(t,e),t},length:function(e){const t=this.ready().then((()=>E.get(this._dbInfo.keyPrefix).size));return f(t,e),t},keys:function(e){const t=this.ready().then((()=>[...E.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=>{E.delete(e)})):Promise.reject("Invalid arguments"),f(r,t),r}};const j=(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;A(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){Z(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,h,g,y,p,b,v,w,S,k,_,I,x,M,C,D=t.btoa,P=t.atob,N=e.bd,R=e.dm,T=["https://mlts.dynamsoft.com/","https://slts.dynamsoft.com/"],O=!1,E=Promise.resolve(),B=e.log&&((...t)=>{try{e.log.apply(null,t)}catch(e){setTimeout((()=>{throw e}),0)}})||(()=>{}),F=N&&B||(()=>{}),j=e=>e.join(""),A={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[j(A.c)][j(A.e)][j(A.f)]("raw",new Uint8Array(A.a.concat(A.b,A.d,A.k)),j(A.g),!0,[j(A.h),j(A.i)]),J=async e=>{if(t[j(A.c)]&&t[j(A.c)][j(A.e)]&&t[j(A.c)][j(A.e)][j(A.f)]){let r=P(e),n=new Uint8Array(r.length);for(let e=0;eP(P(e.replace(/\n/g,"+").replace(/\s/g,"=")).substring(1)),W=e=>D(String.fromCharCode(97+25*Math.random())+D(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: ",$=" Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license.",V={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."+$,networkTimeout:L+"network timed out. Check your Internet connection or contact the site administrator for more information.",publicTrialFailConnect:L+"network connection error."+$,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.",dlsOfflineLicenseExpired:"The DLS2 Offline license has expired. Please contact the site administrator for more information."};let Z,K,X,Y,q=async()=>{if(Z)return Z;Z=new n,await(async()=>{v||(v=G)})(),await Promise.race([(async()=>{let e=await v.createInstance({name:"dynamjssdkhello"});await e.setItem("dynamjssdkhello","available")})(),new Promise(((e,t)=>{setTimeout((()=>t(new Error(V.idbTimeout))),5e3)}))]),S=await v.createInstance({name:"dynamdlsinfo"}),k=D(D("v2")+String.fromCharCode(R.charCodeAt(R.length/2)+1)+D(R));try{let e=await S.getItem(k);if(!e){let t=await v.createInstance({name:"dynamltsinfo"});e=await t.getItem(k),e&&await S.setItem(k,e)}e&&([l,p]=JSON.parse(await z(e)))}catch(e){}try{null==l&&(l=H(),S.setItem(k,await W(JSON.stringify([l,null]))))}catch(e){}Z.resolve()},Q=async e=>{if(X=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:R,os:u,fn:f};g&&(t.rmk=g),s&&(-1!=s.indexOf("-")?t.hs=s:t.og=s);let n={};if(p){let e=await S.getItem(k);e&&([l,p]=JSON.parse(await z(e))),n["lts-time"]=p}h&&(t.sp=h);let d=await Promise.race([(async()=>{let r,o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ");p&&(S.setItem(k,await W(JSON.stringify([l,o]))),p=o);let a="auth/?ext="+encodeURIComponent(D(JSON.stringify(t)));y&&(a+="&"+encodeURIComponent(y));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(T[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(T[1]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))])}catch(e){}if(!(i||r&&r.ok||c))try{r=await Promise.race([fetch(T[0]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r)}catch(e){}s&&151==s.errorCode&&(S.removeItem(k),S.removeItem(_),l=H(),t.cu=l,p=void 0,a="auth/?ext="+encodeURIComponent(D(JSON.stringify(t))),r=await Promise.race([fetch(T[0]+a,{headers:n,mode:"cors"}),new Promise(((e,t)=>setTimeout(t,3e4)))]),await u(r)),(()=>{if(!r||!r.ok){let e;d&&S.setItem(_,""),s?111==s.errorCode?e=s.message:(e=s.message.trim(),e.endsWith(".")||(e+="."),e=m?`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=m?V.publicTrialFailConnect:V.failConnect;let t=Error(e);throw s&&s.errorCode&&(t.ltsErrorCode=s.errorCode),t}})();let f=await r.text();try{p||(S.setItem(k,await W(JSON.stringify([l,o]))),p=o),S.setItem(_,f)}catch(e){}return f})(),new Promise(((e,t)=>{let r;r=m?V.publicTrialNetworkTimeout:V.networkTimeout,setTimeout((()=>t(new Error(r))),i?3e3:15e3)}))]);i=d}catch(e){N&&console.error(e),b=e}K.resolve(),K=null},ee=async()=>{Y||(Y=(async()=>{if(F(l),!i){if(!O)throw B(b.message),b;return}let e={dm:R};N&&(e.bd=!0),e.brtk=!0,e.ls=T[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),g&&(e.rmk=g),F(i);try{let t=JSON.parse(await J(i));t.pv&&(e.pv=JSON.stringify(t.pv)),t.ba&&(e.ba=t.ba),t.usu&&(e.usu=t.usu),t.trial&&(e.trial=t.trial),t.its&&(e.its=t.its),1==e.trial&&t.msg?e.msg=t.msg:b?e.msg=b.message||b:t.msg&&(e.msg=t.msg),e.ar=t.in,e.bafc=!!b}catch(e){}F(e);try{await I(e)}catch(e){F("error updl")}await te(),O||(O=!0),Y=null})()),await Y},te=async()=>{let e=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),t=await M();if(F(t),t&&t(E=E.then((async()=>{try{let r=await w.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,255)),e.ls&&e.ls.length&&(T=e.ls,1==T.length&&T.push(T[0])),m=!s||"200001"===s||s.startsWith("200001-"),h=e.sp,g=e.rmk,"string"==typeof g&&(g=g.substring(0,255)),e.cv&&(y=""+e.cv),I=e.updl,x=e.mnet,M=e.mxet,await q(),await(async()=>{_=D(String.fromCharCode(s.charCodeAt(0)+10)+D(r)+D(s)+a+D(""+c)),w=await v.createInstance({name:"dynamdlsuns"+D(D("v2"))+D(String.fromCharCode(s.charCodeAt(0)+10)+D(r)+D(s)+a+D(""+c))});try{i=await S.getItem(_)}catch(e){}j=e=>P(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="))})(),await Q(),await ee(),(!b||b.ltsErrorCode>=102&&b.ltsErrorCode<=120)&&oe(null,!0)},i2:async({updl:e,mxet:t,strDLC2:r})=>{I=e,M=t,await q(),j=e=>P(String.fromCharCode.apply(null,e).replace(/\n/g,"+").replace(/\s/g,"="));let n={pk:r,dm:R};N&&(n.bd=!0),n.cu=l;try{i=r.substring(4);let e=JSON.parse(await J(i));e.pv&&(n.pv=JSON.stringify(e.pv)),e.ba&&(n.ba=e.ba),n.ar=e.in}catch(e){}F(n);try{await I(n)}catch(e){F("error updl")}let o=(new Date).kUtilFormat("yyyy-MM-ddTHH:mm:ss.SSSZ"),a=await M();if(a&&a{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(A.c)]&&t[j(A.c)][j(A.e)]&&t[j(A.c)][j(A.e)][j(A.f)]){let r=new Uint8Array(e.length);for(let t=0;t{await oe()}),36e4)},p:re,u:async()=>(await q(),l),ar:()=>i,pt:()=>m,ae:()=>b}},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;oe.onmessage=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,be("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=>{be(e)},printErr:e=>{console.error(e),be(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")})),be("wasm initialized, cost "+(Date.now()-e)+" ms"),Module=KModule,le.resolve()})();let s=async()=>{try{re=ne({log:be,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.expectedBarcodesCount=1,n.deblurLevel=0,n.localizationModes=[16,2,0,0,0,0,0,0]):(n.expectedBarcodesCount=512,n.scaleDownThreshold=1e5,n.timeout=1e5),se||(n.barcodeFormatIds=238028799),t.updateRuntimeSettings(JSON.stringify(n))}catch(e){we(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){we(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){we(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]),ve(["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){we(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){we(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){we(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){we(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){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0}});break;case"resetRuntimeSettingsToCppDefault":try{ge.get(o).resetRuntimeSettings()}catch(t){we(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){we(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){we(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(a.isCharge),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){we(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){we(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){we(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){we(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){we(e,n);break}oe.postMessage({type:"task",id:n,body:{success:!0,results:e}});break}default:console.warn("Unmatched task: ",e)}var d,l};let be=e=>{oe.postMessage({type:"log",message:e})},ve=e=>{X&&be(e)},we=(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.32.full.wasm b/dist/dbr-9.6.42.full.wasm similarity index 61% rename from dist/dbr-9.6.32.full.wasm rename to dist/dbr-9.6.42.full.wasm index afb396e..88c84ea 100644 Binary files a/dist/dbr-9.6.32.full.wasm and b/dist/dbr-9.6.42.full.wasm differ diff --git a/dist/dbr-9.6.32.full.wasm.js b/dist/dbr-9.6.42.full.wasm.js similarity index 100% rename from dist/dbr-9.6.32.full.wasm.js rename to dist/dbr-9.6.42.full.wasm.js diff --git a/dist/dbr-9.6.32.standby.full.wasm b/dist/dbr-9.6.42.standby.full.wasm similarity index 65% rename from dist/dbr-9.6.32.standby.full.wasm rename to dist/dbr-9.6.42.standby.full.wasm index 5a2af63..e7bc2e7 100644 Binary files a/dist/dbr-9.6.32.standby.full.wasm and b/dist/dbr-9.6.42.standby.full.wasm differ diff --git a/dist/dbr-9.6.32.standby.full.wasm.js b/dist/dbr-9.6.42.standby.full.wasm.js similarity index 99% rename from dist/dbr-9.6.32.standby.full.wasm.js rename to dist/dbr-9.6.42.standby.full.wasm.js index bf41e16..7663398 100644 --- a/dist/dbr-9.6.32.standby.full.wasm.js +++ b/dist/dbr-9.6.42.standby.full.wasm.js @@ -456,7 +456,7 @@ function updateGlobalBufferAndViews(buf) { Module["HEAPF64"] = HEAPF64 = new Float64Array(buf); } -var DYNAMIC_BASE = 7173904, DYNAMICTOP_PTR = 1930864; +var DYNAMIC_BASE = 7170976, DYNAMICTOP_PTR = 1927936; var INITIAL_INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216; @@ -5739,9 +5739,9 @@ function _fd_write(fd, iov, iovcnt, pnum) { } } -var ___tm_current = 1930880; +var ___tm_current = 1927952; -var ___tm_timezone = (stringToUTF8("GMT", 1930928, 4), 1930928); +var ___tm_timezone = (stringToUTF8("GMT", 1928e3, 4), 1928e3); function _gmtime_r(time, tmPtr) { var date = new Date(HEAP32[time >> 2] * 1e3); diff --git a/dist/dbr-9.6.32.standby.wasm b/dist/dbr-9.6.42.standby.wasm similarity index 65% rename from dist/dbr-9.6.32.standby.wasm rename to dist/dbr-9.6.42.standby.wasm index 62793c1..d20b37a 100644 Binary files a/dist/dbr-9.6.32.standby.wasm and b/dist/dbr-9.6.42.standby.wasm differ diff --git a/dist/dbr-9.6.32.standby.wasm.js b/dist/dbr-9.6.42.standby.wasm.js similarity index 99% rename from dist/dbr-9.6.32.standby.wasm.js rename to dist/dbr-9.6.42.standby.wasm.js index 429c950..fadfb77 100644 --- a/dist/dbr-9.6.32.standby.wasm.js +++ b/dist/dbr-9.6.42.standby.wasm.js @@ -456,7 +456,7 @@ function updateGlobalBufferAndViews(buf) { Module["HEAPF64"] = HEAPF64 = new Float64Array(buf); } -var DYNAMIC_BASE = 6638304, DYNAMICTOP_PTR = 1395264; +var DYNAMIC_BASE = 6635360, DYNAMICTOP_PTR = 1392320; var INITIAL_INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216; @@ -5739,9 +5739,9 @@ function _fd_write(fd, iov, iovcnt, pnum) { } } -var ___tm_current = 1395280; +var ___tm_current = 1392336; -var ___tm_timezone = (stringToUTF8("GMT", 1395328, 4), 1395328); +var ___tm_timezone = (stringToUTF8("GMT", 1392384, 4), 1392384); function _gmtime_r(time, tmPtr) { var date = new Date(HEAP32[time >> 2] * 1e3); diff --git a/dist/dbr-9.6.32.wasm b/dist/dbr-9.6.42.wasm similarity index 60% rename from dist/dbr-9.6.32.wasm rename to dist/dbr-9.6.42.wasm index 3d2b76c..5730170 100644 Binary files a/dist/dbr-9.6.32.wasm and b/dist/dbr-9.6.42.wasm differ diff --git a/dist/dbr-9.6.32.wasm.js b/dist/dbr-9.6.42.wasm.js similarity index 100% rename from dist/dbr-9.6.32.wasm.js rename to dist/dbr-9.6.42.wasm.js diff --git a/dist/dbr.d.ts b/dist/dbr.d.ts new file mode 100644 index 0000000..c6dc389 --- /dev/null +++ b/dist/dbr.d.ts @@ -0,0 +1,2473 @@ +import { CameraEnhancer, DCEFrame } from 'dynamsoft-camera-enhancer'; +import { Howl } from 'dm-howler'; + +declare enum EnumResultCoordinateType { + RCT_PIXEL = 1, + RCT_PERCENTAGE = 2 +} + +interface LocalizationResult { + /** + * The angle of a barcode. Values range from 0 to 360. + */ + angle: number; + /** + * The X coordinate of the left-most point. + */ + x1: number; + /** + * The X coordinate of the second point in a clockwise direction. + */ + x2: number; + /** + * The X coordinate of the third point in a clockwise direction. + */ + x3: number; + /** + * The X coordinate of the fourth point in a clockwise direction. + */ + x4: number; + /** + * The Y coordinate of the left-most point. + */ + y1: number; + /** + * The Y coordinate of the second point in a clockwise direction. + */ + y2: number; + /** + * The Y coordinate of the third point in a clockwise direction. + */ + y3: number; + /** + * The Y coordinate of the fourth point in a clockwise direction. + */ + y4: number; + resultCoordinateType: EnumResultCoordinateType; + transformationMatrix: Array; +} + +declare enum EnumBarcodeFormat { + BF_ALL = -29360129, + BF_ONED = 3147775, + BF_GS1_DATABAR = 260096, + BF_CODE_39 = 1, + BF_CODE_128 = 2, + BF_CODE_93 = 4, + BF_CODABAR = 8, + BF_ITF = 16, + BF_EAN_13 = 32, + BF_EAN_8 = 64, + BF_UPC_A = 128, + BF_UPC_E = 256, + BF_INDUSTRIAL_25 = 512, + BF_CODE_39_EXTENDED = 1024, + BF_GS1_DATABAR_OMNIDIRECTIONAL = 2048, + BF_GS1_DATABAR_TRUNCATED = 4096, + BF_GS1_DATABAR_STACKED = 8192, + BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL = 16384, + BF_GS1_DATABAR_EXPANDED = 32768, + BF_GS1_DATABAR_EXPANDED_STACKED = 65536, + BF_GS1_DATABAR_LIMITED = 131072, + BF_PATCHCODE = 262144, + BF_PDF417 = 33554432, + BF_QR_CODE = 67108864, + BF_DATAMATRIX = 134217728, + BF_AZTEC = 268435456, + BF_MAXICODE = 536870912, + BF_MICRO_QR = 1073741824, + BF_MICRO_PDF417 = 524288, + BF_GS1_COMPOSITE = -2147483648, + BF_MSI_CODE = 1048576, + BF_CODE_11 = 2097152, + BF_NULL = 0 +} + +/** + * @see [C++ TextResult](https://www.dynamsoft.com/barcode-reader/programming/c-cplusplus/struct/TextResult.html?src=cpp&&ver=latest) +*/ +interface TextResult { + /** + * The barcode text. + */ + barcodeText: string; + /** + * The barcode format. + */ + barcodeFormat: number | EnumBarcodeFormat; + /** + * Barcode type in string. + */ + barcodeFormatString: string; + /** + * The barcode content in a byte array. + */ + barcodeBytes: number[]; + /** + * The corresponding localization result. + */ + localizationResult: LocalizationResult; +} + +interface Region { + regionBottom: number; + regionRight: number; + regionLeft: number; + regionTop: number; + regionMeasuredByPercentage: number | boolean; +} + +declare enum EnumIntermediateResultType { + IRT_NO_RESULT = 0, + IRT_ORIGINAL_IMAGE = 1, + IRT_COLOUR_CLUSTERED_IMAGE = 2, + IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE = 4, + IRT_TRANSFORMED_GRAYSCALE_IMAGE = 8, + IRT_PREDETECTED_REGION = 16, + IRT_PREPROCESSED_IMAGE = 32, + IRT_BINARIZED_IMAGE = 64, + IRT_TEXT_ZONE = 128, + IRT_CONTOUR = 256, + IRT_LINE_SEGMENT = 512, + IRT_FORM = 1024, + IRT_SEGMENTATION_BLOCK = 2048, + IRT_TYPED_BARCODE_ZONE = 4096, + IRT_PREDETECTED_QUADRILATERAL = 8192 +} + +declare enum EnumTerminatePhase { + TP_REGION_PREDETECTED = 1, + TP_IMAGE_PREPROCESSED = 2, + TP_IMAGE_BINARIZED = 4, + TP_BARCODE_LOCALIZED = 8, + TP_BARCODE_TYPE_DETERMINED = 16, + TP_BARCODE_RECOGNIZED = 32 +} + +declare enum EnumTextResultOrderMode { + TROM_CONFIDENCE = 1, + TROM_POSITION = 2, + TROM_FORMAT = 4, + TROM_SKIP = 0, + TROM_REV = 2147483648 +} + +declare enum EnumBinarizationMode { + BM_AUTO = 1, + BM_LOCAL_BLOCK = 2, + BM_SKIP = 0, + BM_THRESHOLD = 4, + BM_REV = 2147483648 +} + +declare enum EnumScaleUpMode { + SUM_AUTO = 1, + SUM_LINEAR_INTERPOLATION = 2, + SUM_NEAREST_NEIGHBOUR_INTERPOLATION = 4, + SUM_SKIP = 0, + SUM_REV = 2147483648 +} + +declare enum EnumLocalizationMode { + LM_SKIP = 0, + LM_AUTO = 1, + LM_CONNECTED_BLOCKS = 2, + LM_LINES = 8, + LM_STATISTICS = 4, + LM_SCAN_DIRECTLY = 16, + LM_STATISTICS_MARKS = 32, + LM_STATISTICS_POSTAL_CODE = 64, + LM_CENTRE = 128, + LM_ONED_FAST_SCAN = 256, + LM_REV = 2147483648 +} + +declare enum EnumBarcodeFormat_2 { + BF2_NULL = 0, + BF2_POSTALCODE = 32505856, + BF2_NONSTANDARD_BARCODE = 1, + BF2_USPSINTELLIGENTMAIL = 1048576, + BF2_POSTNET = 2097152, + BF2_PLANET = 4194304, + BF2_AUSTRALIANPOST = 8388608, + BF2_RM4SCC = 16777216, + BF2_DOTCODE = 2, + BF2_PHARMACODE_ONE_TRACK = 4, + BF2_PHARMACODE_TWO_TRACK = 8, + BF2_PHARMACODE = 12, + BF2_ALL = -1 +} + +/** + * @see [C++ RuntimeSettings](https://www.dynamsoft.com/barcode-reader/programming/c-cplusplus/struct/PublicRuntimeSettings.html?src=cpp&&ver=latest) + */ +interface RuntimeSettings { + /** + * Sets the formats of the barcode in BarcodeFormat group 1 to be read. Barcode formats in BarcodeFormat group 1 can be combined. + * ```js + * let runtimeSettings = await reader.getRuntimeSettings(); + * runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; + * await reader.updateRuntimeSettings(runtimeSettings); + * ``` + */ + barcodeFormatIds: number | EnumBarcodeFormat; + /** + * Sets the formats of the barcode in BarcodeFormat group 2 to be read. Barcode formats in BarcodeFormat group 1 can be combined. + */ + barcodeFormatIds_2: number | EnumBarcodeFormat_2; + /** + * Sets the mode and priority for binarization. + */ + binarizationModes: EnumBinarizationMode[]; + /** + * Sets the degree of blurriness of the barcode. + */ + deblurLevel: number; + /** + * Sets the number of barcodes expected to be detected for each image. + */ + expectedBarcodesCount: number; + /** + * Sets the further modes. + */ + furtherModes: any; + /** + * Sets which types of intermediate result to be kept for further reference. Intermediate result types can be combined. + */ + intermediateResultTypes: EnumIntermediateResultType; + /** + * Sets the mode and priority for localization algorithms. + */ + localizationModes: number[] | EnumLocalizationMode[]; + /** + * Sets the range of barcode text length for barcodes search + */ + minBarcodeTextLength: number; + /** + * The minimum confidence of the result + */ + minResultConfidence: number; + /** + * Sets the region definition including the regionTop, regionLeft, regionRight, regionBottom and regionMeasuredByPercentage. + * + * Experimental feature: + * + * In [BarcodeScanner](../BarcodeScanner.md), `region` can be an array. For example `region = [r0, r1, r2]`, 0th frame use `r0`, 1st use `r1`, 2nd use `r2`, 3rd use `r0`, and then loop like this. + */ + region: Region; + /** + * Specifies the format for the coordinates returned + */ + resultCoordinateType: number | EnumResultCoordinateType; + /** + * Sets whether or not to return the clarity of the barcode zone. + */ + returnBarcodeZoneClarity: number; + /** + * Sets the threshold for the image shrinking + */ + scaleDownThreshold: number; + /** + * Sets the mode and priority to control the sampling methods of scale-up for linear barcode with small module sizes. + */ + scaleUpModes: EnumScaleUpMode[]; + /** + * Sets the phase where the algorithm stops. + */ + terminatePhase: EnumTerminatePhase; + /** + * Sets the mode and priority for the order of the text results returned. + */ + textResultOrderModes: EnumTextResultOrderMode[]; + /** + * Sets the maximum amount of time (in milliseconds) that should be spent searching for a barcode per page. + * It does not include the time taken to load/decode an image (Tiff, PNG, etc) from disk into memory. + */ + timeout: number; +} + +declare enum EnumImagePixelFormat { + IPF_Binary = 0, + IPF_BinaryInverted = 1, + IPF_GrayScaled = 2, + IPF_NV21 = 3, + IPF_RGB_565 = 4, + IPF_RGB_555 = 5, + IPF_RGB_888 = 6, + IPF_ARGB_8888 = 7, + IPF_RGB_161616 = 8, + IPF_ARGB_16161616 = 9, + IPF_ABGR_8888 = 10, + IPF_ABGR_16161616 = 11, + IPF_BGR_888 = 12 +} + +declare enum EnumErrorCode { + DBR_SYSTEM_EXCEPTION = 1, + DBR_SUCCESS = 0, + DBR_UNKNOWN = -10000, + DBR_NO_MEMORY = -10001, + DBR_NULL_REFERENCE = -10002, + DBR_LICENSE_INVALID = -10003, + DBR_LICENSE_EXPIRED = -10004, + DBR_FILE_NOT_FOUND = -10005, + DBR_FILETYPE_NOT_SUPPORTED = -10006, + DBR_BPP_NOT_SUPPORTED = -10007, + DBR_INDEX_INVALID = -10008, + DBR_BARCODE_FORMAT_INVALID = -10009, + DBR_CUSTOM_REGION_INVALID = -10010, + DBR_MAX_BARCODE_NUMBER_INVALID = -10011, + DBR_IMAGE_READ_FAILED = -10012, + DBR_TIFF_READ_FAILED = -10013, + DBR_QR_LICENSE_INVALID = -10016, + DBR_1D_LICENSE_INVALID = -10017, + DBR_DIB_BUFFER_INVALID = -10018, + DBR_PDF417_LICENSE_INVALID = -10019, + DBR_DATAMATRIX_LICENSE_INVALID = -10020, + DBR_PDF_READ_FAILED = -10021, + DBR_PDF_DLL_MISSING = -10022, + DBR_PAGE_NUMBER_INVALID = -10023, + DBR_CUSTOM_SIZE_INVALID = -10024, + DBR_CUSTOM_MODULESIZE_INVALID = -10025, + DBR_RECOGNITION_TIMEOUT = -10026, + DBR_JSON_PARSE_FAILED = -10030, + DBR_JSON_TYPE_INVALID = -10031, + DBR_JSON_KEY_INVALID = -10032, + DBR_JSON_VALUE_INVALID = -10033, + DBR_JSON_NAME_KEY_MISSING = -10034, + DBR_JSON_NAME_VALUE_DUPLICATED = -10035, + DBR_TEMPLATE_NAME_INVALID = -10036, + DBR_JSON_NAME_REFERENCE_INVALID = -10037, + DBR_PARAMETER_VALUE_INVALID = -10038, + DBR_DOMAIN_NOT_MATCHED = -10039, + DBR_RESERVEDINFO_NOT_MATCHED = -10040, + DBR_AZTEC_LICENSE_INVALID = -10041, + DBR_LICENSE_DLL_MISSING = -10042, + DBR_LICENSEKEY_NOT_MATCHED = -10043, + DBR_REQUESTED_FAILED = -10044, + DBR_LICENSE_INIT_FAILED = -10045, + DBR_PATCHCODE_LICENSE_INVALID = -10046, + DBR_POSTALCODE_LICENSE_INVALID = -10047, + DBR_DPM_LICENSE_INVALID = -10048, + DBR_FRAME_DECODING_THREAD_EXISTS = -10049, + DBR_STOP_DECODING_THREAD_FAILED = -10050, + DBR_SET_MODE_ARGUMENT_ERROR = -10051, + DBR_LICENSE_CONTENT_INVALID = -10052, + DBR_LICENSE_KEY_INVALID = -10053, + DBR_LICENSE_DEVICE_RUNS_OUT = -10054, + DBR_GET_MODE_ARGUMENT_ERROR = -10055, + DBR_IRT_LICENSE_INVALID = -10056, + DBR_MAXICODE_LICENSE_INVALID = -10057, + DBR_GS1_DATABAR_LICENSE_INVALID = -10058, + DBR_GS1_COMPOSITE_LICENSE_INVALID = -10059, + DBR_PANORAMA_LICENSE_INVALID = -10060, + DBR_DOTCODE_LICENSE_INVALID = -10061, + DBR_PHARMACODE_LICENSE_INVALID = -10062, + DBR_IMAGE_ORIENTATION_INVALID = -10063, + DMERR_NO_LICENSE = -20000, + DMERR_LICENSE_SYNC_FAILED = -20003, + DMERR_TRIAL_LICENSE = -20010, + DMERR_FAILED_TO_REACH_LTS = -20200 +} + +interface BarcodeReaderException extends Error { + code?: EnumErrorCode; +} + +interface DSImage { + data: Uint8Array; + width: number; + height: number; + pixelFormat: string; +} + +interface ImageSource { + getImage(): Promise | DSImage; +} + +/** + * let scanSettings = await scanner.getScanSettings(); + * scanSettings.intervalTime = 100; // 100ms + * scanSettings.duplicateForgetTime = 3000; // 3s + * await scanner.updateScanSettings(scanSettings); + */ +interface ScanSettings { + intervalTime?: number; + duplicateForgetTime?: number; + oneDRememberFrameCount?: number; + oneDTrustFrameCount?: number; + /** + * Whether to play sound when the scanner reads a barcode successfully. + * Default value is `never`, which does not play sound. + * Use `frame` to play a sound when any barcode is found within a frame. + * Use `unique` to play a sound only when any unique/unduplicated barcode is found within a frame. + * ```js + * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies + * startPlayButton.addEventListener('click', function() { + * scanner.whenToPlaySoundforSuccessfulRead = 'frame'; + * }); + * ``` + * refer: `favicon bug` https://bugs.chromium.org/p/chromium/issues/detail?id=1069731&q=favicon&can=2 + */ + whenToPlaySoundforSuccessfulRead?: string; + /** + * The sound to play when the scanner get successfull read. + * ```js + * scanner.soundOnSuccessfullRead = new Audio("./pi.mp3"); + * ``` + */ + soundOnSuccessfullRead?: string; + /** + * Whether to vibrate when the scanner reads a barcode successfully. + * Default value is `never`, which does not vibrate. + * Use `frame` to vibrate when any barcode is found within a frame. + * Use `unique` to vibrate only when any unique/unduplicated barcode is found within a frame. + * ```js + * // Can I use? https://caniuse.com/?search=vibrate + * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies + * startPlayButton.addEventListener('click', function() { + * scanner.whenToVibrateforSuccessfulRead = 'frame'; + * }); + * ``` + */ + whenToVibrateforSuccessfulRead?: string; + /** + * Get or set how long (ms) the vibration lasts. + * @see [[whenToVibrateforSuccessfulRead]] + */ + vibrateDuration?: number; + captureAndDecodeInParallel?: boolean; + autoZoom?: boolean; + autoFocus?: boolean; + autoSuggestTip?: boolean; +} + +interface ScannerPlayCallbackInfo { + height: number; + width: number; + deviceId: string; +} + +interface Warning { + id: number; + message: string; +} + +/** + * The `BarcodeReader` class is used for image decoding + * Comparing to `BarcodeScanner`, the default decoding settings are more accurate but slower. + * @example + * ```js + * (async()=>{ + * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); + * let results = await reader.decode(imageSource); + * for(let result of results){ + * console.log(result.barcodeText); + * } + * })(); + * ``` + */ +declare class BarcodeReader { + private static _jsVersion; + private static _jsEditVersion; + protected static _version: string; + /** + * Returns the version of the library including the detailed version numbers of the engine and the main JavaScript code. + * + * The engine version is only valid after {@link loadWasm} has been called. + * @readonly + */ + static get version(): string; + protected static _license: string; + /** + * Specify an online license or an offline license. Dynamsoft usually provides an online license. + * + * `license` needs to be set before {@link createInstance} or {@link loadWasm}. + * + * Besides, it is also recommended to set license in `data-license` attribute of `script` tag, instead of in `Javascript` code. + * @example + * ```html + * + * ``` + * or + * ```js + * Dynamsoft.DBR.BarcodeReader.license = "YOUR-LICENSE-KEY"; + * ``` + */ + static get license(): string; + static set license(license: string); + /** @ignore */ + static get productKeys(): string; + /** @ignore */ + static set productKeys(keys: string); + /** @ignore */ + static get handshakeCode(): string; + /** @ignore */ + static set handshakeCode(keys: string); + /** @ignore */ + static get organizationID(): string; + /** @ignore */ + static set organizationID(keys: string); + protected static _sessionPassword: string; + /** @ignore */ + static set sessionPassword(value: string); + static get sessionPassword(): string; + /** + * @ignore + */ + static browserInfo: { + browser: string; + version: number; + OS: string; + }; + /** + * Detects the current running environment and returns a report. + * @returns A promise resolving to an object which contains some information of the current running environment. + * @example + * ```js + * console.log(await Dynamsoft.DBR.BarcodeReader.detectEnvironment()); + * // {"wasm":true, "worker":true, "getUserMedia":true, "camera":true, "browser":"Chrome", "version":90, "OS":"Windows"} + * ``` + */ + static detectEnvironment(): Promise; + /** @ignore */ + static _workerName: string; + protected static _engineResourcePath?: string; + static get engineResourcePath(): string; + /** + * Specify the Barcode Reader SDK engine (WASM) url. The SDK tries to automatically explore the engine location. + * If the auto-explored engine location is incorrect, you can manually specify the engine location. + * The property needs to be set before [[loadWasm]]. + * ```js + * Dynamsoft.DBR.BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode/dist/"; + * await Dynamsoft.DBR.BarcodeReader.loadWasm(); + * ``` + */ + static set engineResourcePath(value: string); + /** @ignore */ + protected static _licenseServer?: string[]; + static get licenseServer(): string[] | string; + /** + * Specify the license server URL. + */ + static set licenseServer(value: string[] | string); + private static _deviceFriendlyName; + /** + * Sets a human-readable name that identifies the device. + * This name will appear in the device details table when you check the statistics of the according license. + * @defaultValue `""` + */ + static get deviceFriendlyName(): string; + /** @ignore */ + static set deviceFriendlyName(value: string); + static authCacheVersion: string; + /** @ignore */ + static _isShowRelDecodeTimeInResults: boolean; + /** @ignore */ + static _onLog: any; + /** @ignore */ + static _bWasmDebug: boolean; + /** @ignore */ + static _bNeverShowDialog: boolean; + /** + * Whether to use full feature wasm. The api may change in later version. + * For web, `_bUseFullFeature` is false as default. + * For Node.js, `_bUseFullFeature` will not work, and BarcodeReader will always work on full feature. + * The property needs to be set before `loadWasm`. + *
+     * Compact wasm:
+     * oned + qr + pdf417 + datamatrix.
+     * ===
+     * Full wasm:
+     * all supported barcode format +
+     * high level deblur available (lv8, 9) +
+     * DPM +
+     * template API +
+     * intermediate results API
+     * ===
+     * e.g.:
+     * Use compact in video deocode (small, download and initialization fast).
+     * Use full in file decode (need high level deblur).
+     * 
+ * + * ```js + * DBR.BarcodeReader._bUseFullFeature = true; + * await DBR.BarcodeReader.loadWasm(); + * ``` + */ + protected static __bUseFullFeature: boolean; + static get _bUseFullFeature(): boolean; + static set _bUseFullFeature(value: boolean); + /** @ignore */ + static _dbrWorker: Worker; + protected static _nextTaskID: number; + protected static _taskCallbackMap: Map void>; + private static _pLoad; + /** @ignore */ + static isImageSource(value: any): boolean; + /** @ignore */ + static isDSImage(value: any): boolean; + /** @ignore */ + static isDCEFrame(value: any): boolean; + /** @ignore */ + _instanceID: number; + protected _ifSaveOriginalImageInACanvas: boolean; + /** + * Whether to save the original image into a `HTMLCanvasElement` element. The original image refers to the actual image the library tried to read barcodes from. It can be returned by {@link getOriginalImageInACanvas}. + * @defaultValue `false` + * @example + * ```js + * reader.ifSaveOriginalImageInACanvas = true; + * let results = await reader.decode(source); + * document.body.append(reader.getOriginalImageInACanvas()); + * ``` + * @see {@link getOriginalImageInACanvas} + */ + get ifSaveOriginalImageInACanvas(): boolean; + set ifSaveOriginalImageInACanvas(value: boolean); + /** @ignore */ + protected oriCanvas?: HTMLCanvasElement; + /** @ignore */ + protected oriCanvasData?: any; + /** + * An `HTMLCanvasElement` that holds the original image. + * The original image refers to the actual image the library tried to read barcodes from. + * ```js + * reader.ifSaveOriginalImageInACanvas = true; + * let results = await reader.decode(source); + * document.body.append(reader.getOriginalImageInACanvas()); + * ``` + * @see {@link ifSaveOriginalImageInACanvas} + */ + getOriginalImageInACanvas(): any; + /** @ignore */ + private canvas; + protected bFilterRegionInJs: boolean; + protected userDefinedRegion: any; + protected _region?: Region | Region[]; + protected set region(value: null | Region | Region[]); + protected get region(): null | Region | Region[]; + /** @ignore */ + _timeStartDecode: any; + /** @ignore */ + _timeEnterInnerDBR: any; + /** @ignore */ + _timeGetMessage: any; + /** @ignore */ + decodeRecords: any; + /** + * @ignore A callback when wasm download success in browser environment. + */ + static _onWasmDownloaded: () => void; + /** + * Check if the decoding module is loaded. + * @category Initialize and Destroy + */ + static isWasmLoaded(): boolean; + protected bDestroyed: boolean; + /** + * Returns whether the instance has been destroyed. + * @see {@link destroyContext} + */ + isContextDestroyed(): boolean; + /** @ignore */ + protected static _lastErrorCode: number; + /** @ignore */ + static get lastErrorCode(): number; + /** @ignore */ + protected static _lastErrorString: string; + /** @ignore */ + static get lastErrorString(): string; + /** @ignore */ + protected static _setWarnnedEx: Set; + /** @ignore */ + protected _lastErrorCode: number; + /** @ignore */ + get lastErrorCode(): number; + /** @ignore */ + protected _lastErrorString: string; + /** @ignore */ + get lastErrorString(): string; + /** @ignore */ + _lastInnerDecodeDuration: number; + private static _defaultUIElementURL; + /** + * Returns or sets the URL of the *.html* file that defines the default UI Element. + * The URL can only be set before the {@link createInstance} is called. + */ + static get defaultUIElementURL(): string; + static set defaultUIElementURL(value: string); + /** + * A callback which is triggered when the running environment is not ideal. In this version, it may get triggered in two scenarios: + * + * 1. If the page is opened from the disk + * 2. The page is hosted in a HTTP site without SSL + * + * In both cases, the following warning is returned: + * ```js + * { + * id: 2, + * message: "Not connected via SSL (HTTPS), the SDK may not work correctly." + * } + * ``` + * @defaultValue `undefined` + * @see {@link Warning} + */ + static onWarning: (warning: Warning) => void; + protected static _fireHTTPSWarnning(): void; + /** @ignore */ + intervalTime: number; + /** @ignore */ + protected _intervalGetVideoFrame: number; + protected _loopReadVideoTimeoutId: any; + /** @ignore */ + protected array_getFrameTimeCost: any[]; + /** @ignore */ + protected array_decodeFrameTimeCost: any[]; + /** @ignore */ + protected _indexCurrentDecodingFrame: number; + protected _dbrDrawingLayer: any; + protected _arrPolygons: any; + protected _bPauseScan: boolean; + protected _intervalDetectVideoPause: number; + /** @ignore */ + beepSound: Howl; + private _soundSource; + private get soundSource(); + private set soundSource(value); + /** + * Whether to play sound when the scanner reads a barcode successfully. + * Default value is `false`, which does not play sound. + * Use `frame` or `true` to play a sound when any barcode is found within a frame. + * Use `unique` to play a sound only when any unique/unduplicated barcode is found within a frame. + * ```js + * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies + * startPlayButton.addEventListener('click', function() { + * scanner.bPlaySoundOnSuccessfulRead = true; + * }); + * ``` + * refer: `favicon bug` https://bugs.chromium.org/p/chromium/issues/detail?id=1069731&q=favicon&can=2 + * @ignore + */ + protected bPlaySoundOnSuccessfulRead: (boolean | string); + private get whenToPlaySoundforSuccessfulRead(); + /** + * Whether to play sound when the scanner reads a barcode successfully. + * Default value is `never`, which does not play sound. + * Use `frame` to play a sound when any barcode is found within a frame. + * Use `unique` to play a sound only when any unique/unduplicated barcode is found within a frame. + * ```js + * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies + * startPlayButton.addEventListener('click', function() { + * scanner.whenToPlaySoundforSuccessfulRead = 'frame'; + * }); + * ``` + * refer: `favicon bug` https://bugs.chromium.org/p/chromium/issues/detail?id=1069731&q=favicon&can=2 + * @ignore + */ + private set whenToPlaySoundforSuccessfulRead(value); + /** + * Whether to vibrate when the scanner reads a barcode successfully. + * Default value is `false`, which does not vibrate. + * Use `frame` or `true` to vibrate when any barcode is found within a frame. + * Use `unique` to vibrate only when any unique/unduplicated barcode is found within a frame. + * ```js + * // Can I use? https://caniuse.com/?search=vibrate + * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies + * startVibrateButton.addEventListener('click', function() { + * scanner.bVibrateOnSuccessfulRead = true; + * }); + * ``` + * @ignore + */ + protected bVibrateOnSuccessfulRead: (boolean | string); + /** + * Get or set how long (ms) the vibration lasts. + * @see [[whenToVibrateforSuccessfulRead]] + * @ignore + */ + protected vibrateDuration: number; + private get whenToVibrateforSuccessfulRead(); + /** + * Whether to vibrate when the scanner reads a barcode successfully. + * Default value is `never`, which does not vibrate. + * Use `frame` to vibrate when any barcode is found within a frame. + * Use `unique` to vibrate only when any unique/unduplicated barcode is found within a frame. + * ```js + * // Can I use? https://caniuse.com/?search=vibrate + * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies + * startPlayButton.addEventListener('click', function() { + * scanner.whenToVibrateforSuccessfulRead = 'frame'; + * }); + * ``` + * @ignore + */ + private set whenToVibrateforSuccessfulRead(value); + protected captureAndDecodeInParallel: boolean; + protected autoSuggestTip: boolean; + protected suggestTipFrameArray: Array; + protected suggestTipFrameLimit: number[]; + protected noIntermediateResultsCount: number; + protected noIntermediateResultsTipLimit: number; + protected tinyBarcodeTipModuleSizeLimit: number; + protected hugeBarcodeTipLimit: number; + protected autoZoomInFrameArray: Array; + protected autoZoomInFrameLimit: number[]; + protected autoZoomInStepRate: number; + protected autoZoomInMaxStep: number; + protected autoZoomInMaxTimes: number; + protected autoZoomInMinStep: number; + protected autoZoomInIdealModuleSize: number; + protected autoZoomOutFrameCount: number; + protected autoZoomOutFrameLimit: number; + protected autoZoomOutStepRate: number; + protected autoZoomOutMinValue: number; + protected autoZoomOutMinStep: number; + protected autoZoomOutStepRate_2: number; + protected autoZoomOutMinValue_2: number; + protected frameArrayInIdealZoom: Array; + protected frameLimitInIdealZoom: number[]; + protected enableZoomOutInIdealZoom: boolean; + protected nextActionInIdealZoom: string; + protected autoFocusFrameArray: Array; + protected autoFocusFrameLimit: number[]; + protected autoZoomIdealArea: number[]; + protected autoZoomTargetBorder: number; + protected autoZoomDetectionArea: number; + protected autoZoom: boolean; + protected autoFocus: boolean; + protected _clearResultsCanvasTimeoutId: any; + _resultHighlightingDuration: number; + private _dce; + protected set dce(value: CameraEnhancer); + protected get dce(): CameraEnhancer; + protected _drawingItemNamespace: any; + protected _styleIdBeforeVerification: number; + private _dceControler; + private _imgSource; + private callbackCameraChange?; + private callbackResolutionChange?; + private callbackCameraClose?; + private callbackSingleFrameAcquired?; + protected _maxCvsSideLength: number; + /** @ignore */ + set maxCvsSideLength(value: number); + get maxCvsSideLength(): number; + private _registerDCEControler; + private _logoutDCEControler; + /** + * Sets an image source for continous scanning. + * @param imgSource Specifies the image source. + * @param options Options to help with the usage of the `ImageSource` object. At present, it only contains one property `resultsHighlightBaseShapes` that accepts `Dynamsoft.DCE.DrawingItem` as its value to help with the highlighting of barcode regions as shown in the code snippet below. More properties will be added as needed in the future. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); + * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); + * let options = { resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem }; + * await reader.setImageSource(enhancer, options); + * reader.onUniqueRead = (txt, result) => { + * console.log(txt); + * }; + * await reader.startScanning(true); + * ``` + * @see {@link ImageSource} + */ + setImageSource(imgSource: ImageSource | CameraEnhancer, options?: any): Promise; + /** + * Downloads and compiles the engine to get it loaded/ready for a `BarcodeReader` or `BarcodeScanner` instance to be created. + * You can call this API to silently set the operating environment of the library as soon as the page is loaded, avoiding unnecessary waiting time when using the library later. + * + * If this API is not called beforehand, it will be called automatically when creating an instance of `BarcodeReader` or `BarcodeScanner`. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * window.addEventListener('DOMContentLoaded', (event) => { + * Dynamsoft.DBR.BarcodeReader.loadWasm(); + * }); + * ``` + * @category Initialize and Destroy + */ + static loadWasm(): Promise; + /** + * @param type "warn" or "error" + * @param content + * @returns + */ + protected static showDialog(type: string, content: string): Promise; + protected static createInstanceInWorker(bScanner?: boolean): Promise; + protected constructor(); + /** + * Creates a `BarcodeReader` instance. + * @returns A promise resolving to the created `BarcodeReader` object. + * @example + * ``` + * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); + * ``` + * @see {@link destroyContext} + * @category Initialize and Destroy + */ + static createInstance(): Promise; + protected clearMapDecodeRecord(): Promise; + /** + * Decode barcodes from a image. + * If the content in the binary data is raw img data, such as `RGBA` , use {@link decodeBuffer} instead. + * + * Note: To speed up the reading, the image will be scaled down when it exceeds a size limit either horizontally or vertically. + * The limit is 2048 pixels on mobile devices and 4096 on other devices. + * If the template "dense" or "distance" is used, the limit is 4096 regardless of which device is used. + * @param source specifies the image to decode. The supported image formats include `png` , `jpeg` , `bmp` , `gif` and a few others (some browsers support `webp` , `tif` ). + * Also note that the image can be specified in a lot of ways including binary data, base64 string (with MIME), URL, etc. + * @returns A promise resolving to an array of `TextResult` that contains all the barcode results found in this image. + * @example + * ```js + * let results1 = await reader.decode(blob); + * let results2 = await reader.decode(htmlImageElement); + * let results3 = await reader.decode(url); + * let results4 = await reader.decode(base64WithMime); // like `data:image/png;base64,iV************` + * ``` + * + * You can even use an `HTMLVideoElement` as the source. If the video is playing, the current frame will be decoded. + * + * ```js + * let results; + * try{ + * // The current frame will be decoded. + * results = await reader.decode(htmlVideoElement); + * }catch(ex){ + * // If no frame in the video, will throw an exception. + * } + * ``` + * @see {@link TextResult} + * @see {@link decodeBuffer} + * @category Decode + */ + decode(source: Blob | ArrayBuffer | Uint8Array | Uint8ClampedArray | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | string | DCEFrame | DSImage): Promise; + /** + * Decodes barcodes from a base64-encoded image (with or without MIME). + * @param base64 Specifies the image represented by a string. + * @returns A promise resolving to an array of {@link TextResult} object that contains the barcode results found in this image. + * @example + * ```js + * let results = await reader.decodeBase64String(strBase64); //e.g. `data:image/jpg;base64,Xfjshekk....` or `Xfjshekk...`. + * for(let result of results){ + * console.log(result.barcodeText); + * } + * ``` + * @see {@link TextResult} + * @category Decode + */ + decodeBase64String(base64: string): Promise; + /** + * Decodes barcodes from an image specified by its URL. + * + * Note that the image should either be from the same domain or has the 'Access-Control-Allow-Origin' header set to allow access from your current domain. + * @param url Specifies the image by its URL. + * @returns A promise resolving to an array of {@link TextResult} object that contains the barcode results found in this image. + * @example + * ```js + * let results = await reader.decodeUrl("https://www.yourdomain.com/imageWithBarcodes.png"); + * for(let result of results){ + * console.log(result.barcodeText); + * } + * ``` + * @see {@link TextResult} + * @category Decode + */ + decodeUrl(url: string): Promise; + /** + * Decodes barcodes from the memory buffer containing image pixels in defined format. + * @ignore + */ + _decodeBuffer_Uint8Array(buffer: Uint8Array | Uint8ClampedArray, width: number, height: number, stride: number, format: EnumImagePixelFormat, orientation?: number, config?: any): Promise; + /** + * + * @param buffer + * @param width + * @param height + * @param stride + * @param format + * @param config + * @ignore + */ + _decodeBuffer_Blob(buffer: Blob, width: number, height: number, stride: number, format: EnumImagePixelFormat, orientation?: number, config?: any): Promise; + /** + * Decodes barcodes from raw image data. It is an advanced API, if you don't know what you are doing, use [decode](#decode) instead. + * @param buffer Specifies the raw image represented by a `Uint8Array` , `Uint8ClampedArray` , `ArrayBuffer` or `Blob` object. + * @param width Image width. + * @param height Image height. + * @param stride `image-width * pixel-byte-length`. + * @param format Pixel format. + * @param config Specifies the oritation of the image data. + * @returns A promise resolving to an array of {@link TextResult} object that contains the barcode results found in this image. + * @example + * ```js + * let results = await reader.decodeBuffer(u8RawImage, 1280, 720, 1280 * 4, Dynamsoft.DBR.EnumImagePixelFormat.IPF_ABGR_8888); + * for (let result of results) { + * console.log(result.barcodeText); + * } + * ``` + * @see {@link TextResult} + * @see {@link EnumImagePixelFormat} + * @category Decode + */ + decodeBuffer(buffer: Uint8Array | Uint8ClampedArray | ArrayBuffer | Blob, width: number, height: number, stride: number, format: EnumImagePixelFormat, orientation?: number, config?: any): Promise; + /** @ignore */ + _decodeFileInMemory_Uint8Array(bytes: Uint8Array): Promise; + /** + * Returns the current runtime settings. + * @returns A promise resolving to a {@link RuntimeSettings} object that contains the settings for barcode reading. + * @example + * ```js + * let settings = await reader.getRuntimeSettings(); + * settings.deblurLevel = 5; + * await reader.updateRuntimeSettings(settings); + * ``` + * @see {@link RuntimeSettings} + * @see {@link updateRuntimeSettings} + * @see {@link resetRuntimeSettings} + * @category Runtime Settings + */ + getRuntimeSettings(): Promise; + /** + * Updates runtime settings. + * @param settings a {@link RuntimeSettings} object, or a string represent one of preset templates: + * + * `speed`: fast but may miss a few codes; + * + * `coverage`: slow but try to find all codes, this is the default setting for a `BarcodeReader` instance; + * + * `balance`: between `speed` and `coverage`; + * + * `dense`: optimized for scanning dense barcodes such as the PDF417 on driver's license; + * + * `distance`: optimized for scanning a barcode that is placed far from the device and appear small in the video stream. + * + * Note: If the settings `barcodeFormatIds` , `barcodeFormatIds_2` and `region` have been changed by the customer, changing the template will preserve the previous settings. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await reader.updateRuntimeSettings('balance'); + * let settings = await reader.getRuntimeSettings(); + * settings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED; + * await reader.updateRuntimeSettings(settings); + * ``` + * @see {@link RuntimeSettings} + * @see {@link getRuntimeSettings} + * @see {@link resetRuntimeSettings} + * @category Runtime Settings + */ + updateRuntimeSettings(settings: RuntimeSettings | string): Promise; + /** + * Resets all parameters to default values. + * + * For a `BarcodeReader` instance, it is equivalent to setting the `coverage` template. + * + * For a `BarcodeScanner` instance, it is equivalent to setting the `single` template. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await reader.resetRuntimeSettings(); + * ``` + * @category Runtime Settings + */ + resetRuntimeSettings(): Promise; + /** + * + * @returns + * @ignore + */ + _resetRuntimeSettingsToCppDefault(): Promise; + /** + * Return the current `RuntimeSettings` in the form of a string. + * @returns A promise resolving to a string which represents the current `RuntimeSettings`. + * @example + * ```js + * let strSettings = await reader.outputRuntimeSettingsToString(); + * ``` + * @see {@link RuntimeSettings} + * @see {@link getRuntimeSettings} + * @category Runtime Settings + */ + outputRuntimeSettingsToString(): Promise; + /** + * Initialize runtime settings with the settings in given JSON string. + * @param settings A string representing the template. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await reader.initRuntimeSettingsWithString("{\"Version\":\"3.0\", \"ImageParameter\":{\"Name\":\"IP1\", \"BarcodeFormatIds\":[\"BF_QR_CODE\"], \"ExpectedBarcodesCount\":10}}"); + * ``` + * @see {@link RuntimeSettings} + * @see {@link updateRuntimeSettings} + * @category Runtime Settings + */ + initRuntimeSettingsWithString(settings: any): Promise; + private _decode_Blob; + /** + * + * @param arrayBuffer + * @param config + * @ignore + */ + private _decode_ArrayBuffer; + /** + * + * @param uint8Array + * @param config + * @ignore + */ + private _decode_Uint8Array; + /** + * + * @param image + * @param config + * @ignore + */ + private _decode_Image; + private _decode_Canvas; + /** + * decode video is not multi call safe in an instance, we reuse many thing for speed, so make sure wait util one finish then call next + * @param video + * @param config + * @ignore + */ + _decode_Video(video: HTMLVideoElement, config?: any): Promise; + /**@ignore */ + _decode_DCEFrame(dceFrame: DCEFrame, config?: any): Promise; + /**@ignore */ + _decode_DSImage(dsImage: DSImage, config?: any): Promise; + private _decode_Base64; + private _decode_Url; + /** + * The coordinates of results are related to the cropping image gotten from DCE JS. Transform it to the coordinates related to the whole video/image. + * @ignore + */ + static recalculateResultLocation(results: Array<{ + localizationResult: any; + }>, sx: number, sy: number, sWidth: number, sHeight: number, dWidth: number, dHeight: number): void; + /** @ignore */ + static BarcodeReaderException(ag0: any, ag1: any): BarcodeReaderException; + protected _handleRetJsonString(objRet: any): any; + /** + * Sets the argument value for the specified mode parameter. + * @param modeName Specifies the mode which contains one or multiple elements. + * @param index Specifies an element of the mode by its index. + * @param argumentName Specifies the argument. + * @param argumentValue Specifies the value. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await reader.setModeArgument("BinarizationModes", 0, "EnableFillBinaryVacancy", "1"); + * ``` + * @see {@link getModeArgument} + * @category Runtime Settings + */ + setModeArgument(modeName: string, index: number, argumentName: string, argumentValue: string): Promise; + /** + * Returns the argument value for the specified mode parameter. + * @param modeName Specifies the mode which contains one or multiple elements. + * @param index Specifies an element of the mode by its index. + * @param argumentName Specifies the argument. + * @returns A promise resolving to a string which represents the value of the argument. + * @example + * ```js + * let argumentValue = await reader.getModeArgument("BinarizationModes", 0, "EnableFillBinaryVacancy"); + * ``` + * @see {@link setModeArgument} + * @category Runtime Settings + */ + getModeArgument(modeName: string, index: number, argumentName: string): Promise; + /** + * The method is only supported in the full feature edition. + * Returns intermediate results containing the original image, the colour clustered image, the binarized Image, contours, Lines, TextBlocks, etc. + * ```js + * let imResults = await reader.getIntermediateResults(); + * ``` + * @ignore + */ + getIntermediateResults(): Promise; + /** @ignore */ + getIntermediateCanvas(): Promise; + /** + * This event is triggered after the library finishes scanning a image. + * @event onImageRead + * @defaultValue `undefined` + * @param results An array of `TextResult` object that contains the barcode results in this frame. + * @example + * ```js + * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); + * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); + * let options = { + * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem + * }; + * await reader.setImageSource(enhancer, options); + * reader.onImageRead = (results) => { + * if (results.length > 0) { + * results.forEach(result => { + * console.log(result.barcodeText); + * }); + * } + * }; + * await reader.startScanning(true); + * ``` + * @see {@link TextResult} + * @see {@link onUniqueRead} + */ + onImageRead?: (results: TextResult[]) => void; + /** + * This event is triggered when a new, unduplicated label is found. + * @event onUniqueRead + * @defaultValue `undefined` + * @param txt A string that holds the barcode text. + * @param txt A {@link TextResult} object that contains more detailed info. + * @example + * ```js + * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); + * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); + * let options = { + * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem + * }; + * await reader.setImageSource(enhancer, options); + * reader.onUniqueRead = (txt, result) => { + * console.log(txt); + * }; + * await reader.startScanning(true); + * ``` + * @see {@link TextResult} + * @see {@link onImageRead} + */ + onUniqueRead?: (txt: string, result: TextResult) => void; + /** + * Get current scan settings. + * @returns A promise resolving to a {@link ScanSettings}. + * @example + * ```js + * let scanSettings = await scanner.getScanSettings(); + * scanSettings.intervalTime = 50; + * scanSettings.duplicateForgetTime = 1000; + * await scanner.updateScanSettings(scanSettings); + * ``` + * @see {@link ScanSettings} + * @see {@link updateScanSettings} + */ + getScanSettings(): Promise; + /** + * Changes scan settings with the object passed in. + * @param settings Specifies the new scan settings. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * let scanSettings = await scanner.getScanSettings(); + * scanSettings.intervalTime = 50; + * scanSettings.duplicateForgetTime = 1000; + * await scanner.updateScanSettings(scanSettings); + * ``` + * @see {@link ScanSettings} + * @see {@link getScanSettings} + */ + updateScanSettings(settings: ScanSettings): Promise; + /** @ignore */ + _cloneDecodeResults(results: any): any; + protected _loopReadVideo(): Promise; + /** + * start dce fetching frame loop, and get frame from frame queue + * @ignore + */ + protected _getVideoFrame(): DCEFrame; + /** + * Add drawing items according to results, and add notes to drawing items. + * @param results + * @param notes + * @returns + * @ignore + */ + protected _drawResults(results: Array<{ + localizationResult: any; + resultState?: number; + }>, notes?: Array): void; + /** + * _promiseStartScan.status == "pending"; // camera is openning. + * _promiseStartScan.status == "fulfilled"; // camera is opened. + * _promiseStartScan == null; // camera is closed. + * @ignore + */ + private _promiseStartScan; + /** + * Open the camera and starts continuous scanning of incoming images. + * @param appendOrShowUI this parameter specifies how to handle the UI that comes with the bound CameraEnhancer instance. + * When set to true, if the UI doesn't exist in the DOM tree, the `CameraEnhancer` instance will append it in the DOM and show it; if the UI already exists in the DOM tree but is hidden, it'll be displayed. + * When not set or set to false, it means not to change the original state of that UI: if it doesn't exist in the DOM tree, nothing shows up on the page; if it exists in the DOM tree, it may or may not show up depending on its original state. + * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object which contains the resolution of the video. + * @example + * ```js + * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); + * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); + * let options = { + * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem + * }; + * await reader.setImageSource(enhancer, options); + * reader.onUniqueRead = (txt, result) => { + * console.log(txt); + * }; + * await reader.startScanning(true); + * ``` + * @see {@link ScannerPlayCallbackInfo} + * @see {@link stopScanning} + * @see {@link pauseScanning} + * @see {@link resumeScanning} + * @category Open and Close + */ + startScanning(bShowUI?: boolean): Promise; + /** + * Stops continuous scanning and closes the video stream. + * @param hideUI this parameter specifies how to handle the UI that comes with the bound `CameraEnhancer` instance. + * When set to true, if the UI doesn't exist in the DOM tree or it exists but is hidden, nothing is done; if the UI already exists in the DOM tree and is shown, it'll be hidden. + * When not set or set to false, it means not to change the original state of that UI: if it doesn't exist in the DOM tree, nothing happens; if it exists in the DOM tree, it may or may not be hidden depending on its original state. + * @example + * ```js + * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); + * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); + * let options = { + * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem + * }; + * await reader.setImageSource(enhancer, options); + * reader.onUniqueRead = (txt, result) => { + * console.log(txt); + * reader.stopScanning(true); + * }; + * await reader.startScanning(true); + * ``` + * @see {@link startScanning} + * @see {@link pauseScanning} + * @see {@link resumeScanning} + * @category Open and Close + */ + stopScanning(bHideUI?: boolean): void; + /** + * Pause continuous scanning but keep the video stream. + * @param options Options to configure how the pause works. + * At present, it only contains one property `keepResultsHighlighted` which, when set to `true`, will keep the barcodes found on the frame (at the time of the pause) highlighted. + * @see {@link resumeScanning} + * @category Pause and Resume + */ + pauseScanning(options?: any): void; + /** + * Resumes continuous scanning. + * @see {@link pauseScanning} + * @category Pause and Resume + */ + resumeScanning(): void; + /** + * Destroy the `BarcodeReader` instance. + * If your page needs to create new instances from time to time, don't forget to destroy unused old instances. + * @see {@link isContextDestroyed} + * @category Initialize and Destroy + */ + destroyContext(): void; +} + +interface VideoDeviceInfo { + deviceId: string; + label: string; + /** @ignore */ + _checked: boolean; +} + +/** + * The `BarcodeScanner` class is used for video decoding. + * Its instance gets access to a camera via the 'MediaDevices' interface, then uses its built-in UI to show the camera input and perform continuous barcode scanning on the incoming frames. + * @example + * ```js + * let scanner; + * (async()=>{ + * scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); + * scanner.onUniqueRead = txt => console.log(txt); + * await scanner.show(); + * })(); + * ``` + * @extends BarcodeReader + */ +declare class BarcodeScanner extends BarcodeReader { + #private; + /** @ignore */ + static set _onLog(value: (message: any) => void); + static get _onLog(): (message: any) => void; + /** + * Returns the version of the library including the detailed version numbers of the engine and the main JavaScript code. + * + * The engine version is only valid after {@link loadWasm} has been called. + * @readonly + */ + static get version(): string; + /** + * A callback which is triggered when the running environment is not ideal. In this version, it may get triggered in two scenarios: + * + * 1. If the page is opened from the disk + * 2. The page is hosted in a HTTP site without SSL + * + * In both cases, the following warning is returned: + * ```js + * { + * id: 2, + * message: "Not connected via SSL (HTTPS), the SDK may not work correctly." + * } + * ``` + * @defaultValue `undefined` + * @see {@link Warning} + */ + static onWarning: (warning: Warning) => void; + protected static _fireHTTPSWarnning(): void; + /** + * Test whether there is an available camera. It is also a trick to speed up the opening of the camera. + * @returns A promise resolving to a object contains the message. + */ + static testCameraAccess(): Promise<{ + ok: boolean; + message: string; + }>; + /** + * A callback which is triggered when the resolution is not ideal (< 720P). + * @defaultValue `undefined` + * @see {@link Warning} + */ + onWarning: (warning: Warning) => void; + private _fireResolutionWarning; + /** + * Returns the HTML element that is used by the `BarcodeScanner` instance. + * @returns The HTML element that is used by the `BarcodeScanner` instance. + * @see {@link setUIElement} + * @category UI + */ + getUIElement(): HTMLElement; + /** + * Specifies an HTML element for the `BarcodeScanner` instance to use as its UI. The structure inside the element determines the appearance of the UI. + * @param elementOrUrl specifies the element or the element url. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```html + *
+ * + * ``` + * @see {@link getUIElement} + * @category UI + */ + setUIElement(elementOrUrl: HTMLElement | string): Promise; + /** + * Returns or sets the status of single frame mode. + * If enabled, the video input will not be played and the user can choose to take a picture with the system camera (mobile only) or select an existing image from the photo library for barcode reading. + * + * Because the system camera of a mobile device can provide pictures with better quality, the API is useful when facing complex scenarios such as reading the dense PDF417 code on a driver license. + * + * The single-frame mode can only be enabled or disabled before the video input starts playing (before `scanner.show()` is called). + * @defaultValue In general, the default value is `false`. But if the browser does not support the `MediaDevices`/`getUserMedia`, it will be set as `true` automatically when {@link createInstance} is called. + * @example + * ```js + * let scanner; + * (async()=>{ + * scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); + * scanner.singleFrameMode = true; + * await scanner.show(); + * })(); + * ``` + */ + get singleFrameMode(): boolean | "image" | "camera"; + set singleFrameMode(value: boolean | "image" | "camera"); + /** + * Specifies an event handler which fires after the library finishes scanning a frame. + * @event onFrameRead + * @defaultValue `undefined` + * @param results An array of {@link TextResult} object that contains the barcode results in this frame. + * @example + * ```js + * scanner.onFrameRead = results => { + * for(let result of results){ + * console.log(result.barcodeText); + * } + * }; + * ``` + * @see {@link TextResult} + * @see {@link onUniqueRead} + */ + onFrameRead?: (results: TextResult[]) => void; + /** + * @deprecated Use {@link onUniqueRead} instead. + */ + get onUnduplicatedRead(): (txt: string, result: TextResult) => void; + set onUnduplicatedRead(value: (txt: string, result: TextResult) => void); + /** + * Returns `HTMLVideoElement` element that the `BarcodeScanner` instance used. + * @readonly + */ + get video(): HTMLVideoElement; + /** + * Sets or returns the source of the video. + * You can use this property to specify an existing video as the source to play which will be processed the same way as the video feed from a live camera. + * @defaultValue `null` + */ + set videoSrc(source: string | MediaStream | MediaSource | Blob); + get videoSrc(): string | MediaStream | MediaSource | Blob; + /** + * Sets or returns the the maximum time allowed for opening a selected camera. + * @defaultValue `4000` + */ + set cameraOpenTimeout(value: number); + get cameraOpenTimeout(): number; + /** + * An event that gets triggered whenever a 'Tip' is suggested. + * @event onTipSuggested + * @defaultValue `undefined` + * @param occasion Specifies the occasion for the Tip. + * @param message The 'Tip' message for the occasion. + * @see {@link showTip} + */ + set onTipSuggested(value: (occasion: string, message: string) => void); + get onTipSuggested(): (occasion: string, message: string) => void; + private _assertOpen; + private _barcodeFillStyle; + /** + * Specifies the color used inside the shape which highlights a found barcode. + * @defaultValue `"rgba(254,180,32,0.3)"` + * @see {@link barcodeStrokeStyle} + * @see {@link barcodeLineWidth} + * @see {@link barcodeFillStyleBeforeVerification} + * @see {@link barcodeStrokeStyleBeforeVerification} + * @see {@link barcodeLineWidthBeforeVerification} + * @category UI + */ + set barcodeFillStyle(style: string); + get barcodeFillStyle(): string; + private _barcodeStrokeStyle; + /** + * Specifies the color used to paint the outline of the shape which highlights a found barcode. + * @defaultValue `"rgba(254,180,32,0.9)"` + * @see {@link barcodeFillStyle} + * @see {@link barcodeLineWidth} + * @see {@link barcodeFillStyleBeforeVerification} + * @see {@link barcodeStrokeStyleBeforeVerification} + * @see {@link barcodeLineWidthBeforeVerification} + * @category UI + */ + set barcodeStrokeStyle(style: string); + get barcodeStrokeStyle(): string; + private _barcodeLineWidth; + /** + * Specifies the line width of the outline of the shape which highlights a found barcode. + * @defaultValue `1` + * @see {@link barcodeFillStyle} + * @see {@link barcodeStrokeStyle} + * @see {@link barcodeFillStyleBeforeVerification} + * @see {@link barcodeStrokeStyleBeforeVerification} + * @see {@link barcodeLineWidthBeforeVerification} + * @category UI + */ + set barcodeLineWidth(width: number); + get barcodeLineWidth(): number; + private _barcodeFillStyleBeforeVerification; + /** + * Specifies the color used inside the shape which highlights a found linear barcode which has not been verified. + * @defaultValue `"rgba(248,252,0,0.2)"` + * @see {@link barcodeStrokeStyleBeforeVerification} + * @see {@link barcodeLineWidthBeforeVerification} + * @see {@link barcodeFillStyle} + * @see {@link barcodeStrokeStyle} + * @see {@link barcodeLineWidth} + * @category UI + */ + set barcodeFillStyleBeforeVerification(style: string); + get barcodeFillStyleBeforeVerification(): string; + private _barcodeStrokeStyleBeforeVerification; + /** + * Specifies the color used to paint the outline of the shape which highlights a found linear barcode which has not been verified. + * @defaultValue `"transparent"` + * @see {@link barcodeFillStyleBeforeVerification} + * @see {@link barcodeLineWidthBeforeVerification} + * @see {@link barcodeFillStyle} + * @see {@link barcodeStrokeStyle} + * @see {@link barcodeLineWidth} + * @category UI + */ + set barcodeStrokeStyleBeforeVerification(style: string); + get barcodeStrokeStyleBeforeVerification(): string; + private _barcodeLineWidthBeforeVerification; + /** + * Specifies the line width of the outline of the shape which highlights a found linear barcode which has not been verified. + * @defaultValue `2` + * @see {@link barcodeFillStyleBeforeVerification} + * @see {@link barcodeStrokeStyleBeforeVerification} + * @see {@link barcodeFillStyle} + * @see {@link barcodeStrokeStyle} + * @see {@link barcodeLineWidth} + * @category UI + */ + set barcodeLineWidthBeforeVerification(width: number); + get barcodeLineWidthBeforeVerification(): number; + /** + * Specifies the color used in the square-loop shape between the actual scanning area and the boundary of the video input. This shape only appears when the barcode scanning is limited to a specified region. + * @defaultValue `"rgba(0, 0, 0, 0.5)"` + * @see {@link regionMaskStrokeStyle} + * @see {@link regionMaskLineWidth} + * @category UI + */ + set regionMaskFillStyle(value: string); + get regionMaskFillStyle(): string; + /** + * Specifies the color used to paint the outline of the scanning region. This outline only appears when the barcode scanning is limited to a specified region. + * @defaultValue `"rgb(254, 142, 20)"` + * @see {@link regionMaskFillStyle} + * @see {@link regionMaskLineWidth} + * @category UI + */ + set regionMaskStrokeStyle(value: string); + get regionMaskStrokeStyle(): string; + /** + * Specifies the width of the outline of the scanning region. This outline only appears when the barcode scanning is limited to a specified region. + * @defaultValue `2` + * @see {@link regionMaskFillStyle} + * @see {@link regionMaskStrokeStyle} + * @category UI + */ + set regionMaskLineWidth(value: string); + get regionMaskLineWidth(): string; + protected bFilterRegionInJs: boolean; + protected set region(value: null | Region | Region[]); + protected get region(): null | Region | Region[]; + /** + * Whether to save the original image into a `HTMLCanvasElement` element. The original image refers to the actual image the library tried to read barcodes from. It can be returned by {@link getOriginalImageInACanvas}. + * @defaultValue `false` + * @example + * ```js + * scanner.ifSaveOriginalImageInACanvas = true; + * let results = await scanner.decode(source); + * document.body.append(scanner.getOriginalImageInACanvas()); + * ``` + * @see {@link getOriginalImageInACanvas} + */ + set ifSaveOriginalImageInACanvas(value: boolean); + get ifSaveOriginalImageInACanvas(): boolean; + private createDCEInstance; + /** @ignore */ + set maxCvsSideLength(value: number); + get maxCvsSideLength(): number; + private constructor(); + /** + * Create a `BarcodeScanner` object. + * @returns A promise resolving to the created `BarcodeScanner` object. + * @example + * ```js + * let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); + * ``` + * @see {@link destroyContext} + * @category Initialize and Destroy + */ + static createInstance(config?: any): Promise; + /** + * Decode barcodes from the current frame of the video. + * @returns A promise resolving to an array of {@link TextResult} that contains all the barcode results. + * @example + * ```js + * await scanner.showVideo(); + * console.log(await scanner.decodeCurrentFrame()); + * ``` + * @see {@link TextResult} + * @category Decode + */ + decodeCurrentFrame(config?: any): Promise; + /** + * Update runtime settings. + * @param settings a `RuntimeSettings` object, or a string represent one of preset templates: + * + * `speed`: fast but may miss a few codes; + * + * `coverage`: slow but try to find all codes, this is the default setting for a `BarcodeReader` instance; + * + * `balance`: between `speed` and `coverage`; + * + * `single`: optimized for scanning one single barcode from a video input, this is the default setting for a `BarcodeScanner` instance; + * + * `dense`: optimized for scanning dense barcodes such as the PDF417 on driver's license; + * + * `distance`: optimized for scanning a barcode that is placed far from the device and appear small in the video stream. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await scanner.updateRuntimeSettings('balance'); + * let settings = await scanner.getRuntimeSettings(); + * settings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED; + * await scanner.updateRuntimeSettings(settings); + * ``` + * @see {@link RuntimeSettings} + * @see {@link getRuntimeSettings} + * @see {@link resetRuntimeSettings} + * @category Runtime Settings + */ + updateRuntimeSettings(settings: RuntimeSettings | string): Promise; + /** @ignore */ + _bindUI(): void; + /** @ignore */ + _unbindUI(): void; + private _onPlayed; + /** + * This event is triggered when the video stream starts playing. + * @event + * @defaultValue `null` + * @example + * ```js + * scanner.onPlayed = rsl=>{ console.log(rsl.width+'x'+rsl.height) }; + * await scanner.show(); // or open, play, setCurrentCamera, like these. + * ``` + */ + set onPlayed(value: (info: ScannerPlayCallbackInfo) => void); + get onPlayed(): (info: ScannerPlayCallbackInfo) => void; + /** + * Returns infomation of all available cameras on the device. + * @returns A promise resolving to an array of {@link VideoDeviceInfo} objects. + * @example + * ```js + * let cameras = await scanner.getAllCameras(); + * if(cameras.length){ + * await scanner.setCurrentCamera(cameras[0]); + * } + * ``` + * @see {@link VideoDeviceInfo} + * @see {@link getCurrentCamera} + * @category Camera Settings + */ + getAllCameras(): Promise; + /** + * Returns information about the current camera. + * @returns A promise resolving to a {@link VideoDeviceInfo} object. + * @example + * ```js + * let camera = await scanner.getCurrentCamera(); + * ``` + * @see {@link VideoDeviceInfo} + * @see {@link getAllCameras} + * @see {@link setCurrentCamera} + * @category Camera Settings + */ + getCurrentCamera(): Promise; + /** + * Chooses a camera as the video source. + * @param cameraInfoOrDeviceId Specifies the camera. + * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. + * @example + * ```js + * let cameras = await scanner.getAllCameras(); + * if(cameras.length){ + * await scanner.setCurrentCamera(cameras[0]); + * } + * ``` + * @fires {@link onPlayed} + * @see {@link ScannerPlayCallbackInfo} + * @see {@link getCurrentCamera} + * @category Camera Settings + */ + setCurrentCamera(cameraInfoOrDeviceId: any): Promise; + /** + * Returns the resolution of the current video input. + * @returns An array of two numbers representing the resolution. + * @example + * ```js + * let rsl = await scanner.getResolution(); + * console.log(rsl[0] + " x " + rsl[1]); + * ``` + * @see {@link setResolution} + * @category Camera Settings + */ + getResolution(): number[]; + /** + * Sets the resolution of the current video input. If the specified resolution is not exactly supported, the closest resolution will be applied. + * + * If called before `open()` or `show()`, the camera will use the set resolution when it opens. Otherwise, the default resolution is used, which is 1280 x 720 on mobile devices or 1920 x 1080 on desktop. + * @param width Specifies the horizontal resolution. + * @param height Specifies the vertical resolution. + * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. + * @example + * ```js + * await scanner.setResolution(width, height); + * ``` + * @fires {@link onPlayed} + * @see {@link ScannerPlayCallbackInfo} + * @see {@link getResolution} + * @category Camera Settings + */ + setResolution(width: number | number[], height: number): Promise; + /** + * Returns the current video settings. + * @returns A `MediaStreamConstraints` object. + * @see {@link updateVideoSettings} + * @category Camera Settings + */ + getVideoSettings(): MediaStreamConstraints; + /** + * Modify and update video settings. + * @param mediaStreamConstraints Specifies the new video settings. + * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. + * @example + * ```js + * await scanner.updateVideoSettings({ video: {width: {ideal: 1280}, height: {ideal: 720}, facingMode: {ideal: 'environment'}} }); + * ``` + * @see {@link ScannerPlayCallbackInfo} + * @see {@link getVideoSettings} + * @category Camera Settings + */ + updateVideoSettings(mediaStreamConstraints: any): Promise; + /** + * Indicates whether the camera is turned on. + * @returns A boolean indicates whether the camera is turned on. + * @example + * ```js + * await scanner.show(); // or open(), showVideo(), openVideo(); + * console.assert(scanner.isOpen(), "scanner should be opened."); + * await scanner.hide(); // or close(); + * console.assert(!scanner.isOpen(), "scanner should be closed."); + * ``` + * @category Open and Close + */ + isOpen(): boolean; + /** + * Sets the `object-fit` CSS property of the video element. + * @param value Specify the new fit type. At present, only "cover" and "contain" are allowed. + * @see {@link getVideoFit} + */ + setVideoFit(value: string): void; + /** + * Returns the value of the object-fit CSS property of the video element. + * @returns The value of the object-fit CSS property. + * @see {@link setVideoFit} + */ + getVideoFit(): string; + /** + * Whether to show the scan region mask. + * @defaultValue `true` + */ + set ifShowScanRegionMask(value: boolean); + get ifShowScanRegionMask(): boolean; + /** + * Returns or sets whether to save the last used camera and resolution. + * This feature makes use of the `localStorage` of the browser. + * + * Note: This feature only works on mainstream browsers like Chrome, Firefox and Safari. Other browsers may change the device IDs dynamically thus making it impossible to track the camera. + * @defaultValue `false` + */ + set ifSaveLastUsedCamera(value: boolean); + get ifSaveLastUsedCamera(): boolean; + /** + * Returns or sets whether to skip camera inspection at initialization to save time. + * Note that if a previously used camera is already available in the `localStorage`, the inspection is skipped automatically. Read more on {@link ifSaveLastUsedCamera}. + * @defaultValue `false` + */ + set ifSkipCameraInspection(value: boolean); + get ifSkipCameraInspection(): boolean; + /** + * Stops the video and releases the camera. + * @example + * ```js + * scanner.stop() + * // *** a lot of work *** + * await scanner.play(); + * ``` + * @see {@link play} + * @category Play and Pause + */ + stop(): void; + /** + * Pauses the video without releasing the camera. + * @example + * ```js + * scanner.pause(); + * // *** a lot of work *** + * await scanner.play(); + * ``` + * @see {@link play} + * @category Play and Pause + */ + pause(): void; + /** + * Play the video if it is already open but paused or stopped. If the video is already playing, it will start again. + * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. + * @fires [[onPlayed]] + * @example + * ```js + * scanner.pause(); // or scanner.stop() + * // *** a lot of work *** + * await scanner.play(); + * ``` + * @see {@link ScannerPlayCallbackInfo} + * @see {@link stop} + * @see {@link pause} + * @category Play and Pause + */ + play(deviceId?: string, width?: number, height?: number): Promise; + /** + * Pause continuous scanning but keep the video stream. + * @param options Options to configure how the pause works. At present, it only contains one property `keepResultsHighlighted` which, when set to `true`, will keep the barcodes found on the frame (at the time of the pause) highlighted. + * @see {@link resumeScan} + * @category Play and Pause + */ + pauseScan(options?: any): void; + /** + * Resumes the decoding process. + * @see {@link pauseScan} + * @category Play and Pause + */ + resumeScan(): void; + /** + * Inspects and returns the capabilities of the current camera. + * + * Note: At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported). + * Also, it should be called when a camera is open. + * @returns A `MediaTrackCapabilities` object which specifies the values or range of values for each constrainable property of the current camera. + * @example + * ``` + * scanner.getCapabilities() + * // Result sample + * { + * "aspectRatio":{"max":3840,"min":0.000462962962962963}, + * "colorTemperature":{max: 7000, min: 2850, step: 50}, + * "deviceId":"1e...3af7", + * "exposureCompensation": {max: 2.0000040531158447, min: -2.0000040531158447, step: 0.16666699945926666}, + * "exposureMode":["continuous","manual"], + * "facingMode":["environment"], + * "focusMode":["continuous","single-shot","manual"], + * "frameRate":{"max":30,"min":0}, + * "groupId":"71...a935", + * "height":{"max":2160,"min":1}, + * "resizeMode":["none","crop-and-scale"], + * "torch":true, + * "whiteBalanceMode":["continuous","manual"], + * "width":{"max":3840,"min":1}, + * "zoom":{max: 606, min: 100, step: 2} + * } + * ``` + * @category Camera Settings + */ + getCapabilities(): MediaTrackCapabilities; + /** @ignore */ + getCameraSettings(): MediaTrackSettings; + /** @ignore */ + getConstraints(): MediaTrackConstraints; + /** + * @ignore + * Set the camera capabilities. + * Only available when the scanner is open. + * It's a low-level API, usually you can use the wrapped APIs instead. + * ```js + * await scanner.applyConstraints({ frameRate: { ideal:5 } }); + * ``` + */ + applyConstraints(constraints: MediaTrackConstraints): Promise; + /** + * Turns on the torch/flashlight if the current camera supports it. This method should be called when the camera is turned on. + * + * Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * @returns A promise that resolves when the operation succeeds. + * @see {@link turnOffTorch} + * @see {@link getCapabilities} + * @category Camera Settings + */ + turnOnTorch(): Promise; + /** + * Turns off the torch/flashlight. + * + * Note: At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. + * @see {@link turnOnTorch} + * @category Camera Settings + */ + turnOffTorch(): Promise; + /** + * Adjusts the color temperature. + * + * Note: At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. + * @param value Specifies the new color temperature. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await scanner.setColorTemperature(5000); + * ``` + * @see {@link getColorTemperature} + * @see {@link getCapabilities} + * @category Camera Settings + */ + setColorTemperature(value: number): Promise; + /** + * Returns the color temperature of the selected camera. This method should be called when the camera is turned on. + * + * Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * @returns Color temperature of the selected camera. + * @see {@link setColorTemperature} + * @category Camera Settings + */ + getColorTemperature(): number; + /** + * Sets the exposure compensation index. + * + * Note: At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. + * @param value Specifies the new exposure compensation index. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await scanner.setExposureCompensation(-0.7); + * ``` + * @see {@link getExposureCompensation} + * @see {@link getCapabilities} + * @category Camera Settings + */ + setExposureCompensation(value: number): Promise; + /** + * Returns the exposure compensation index of the selected camera. This method should be called when the camera is turned on. + * + * Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. + * @returns Exposure compensation index of the selected camera. + * @see {@link setExposureCompensation} + * @category Camera Settings + */ + getExposureCompensation(): number; + /** + * Sets current zoom value. + * + * At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. + * @param settings Specifies the new zoom value. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await scanner.setZoom(2); + * ``` + * @see {@link getZoomSettings} + * @see {@link resetZoom} + * @see {@link getCapabilities} + * @category Camera Settings + */ + setZoom(settings: number | { + factor: number; + centerPoint?: { + x: string; + y: string; + }; + }): Promise; + /** + * Returns the zoom settings. + * @returns An object that describes the zoom settings. As of version 3.2, it contains only the zoom factor. + * @see {@link setZoom} + * @category Camera Settings + */ + getZoomSettings(): { + factor: number; + }; + /** + * Resets the zoom level of the video. + * @returns A promise that resolves when the operation succeeds. + * @see {@link setZoom} + * @category Camera Settings + */ + resetZoom(): Promise; + /** + * Adjusts the frame rate. + * + * At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. + * @param value Specifies the new frame rate. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await scanner.setFrameRate(10); + * ``` + * @see {@link getFrameRate} + * @see {@link getCapabilities} + * @category Camera Settings + */ + setFrameRate(value: number): Promise; + /** + * Returns the real-time frame rate. + * @returns The calculated real-time frame rate. + * @see {@link setFrameRate} + * @category Camera Settings + */ + getFrameRate(): number; + /** + * Sets the focus mode and focus distance of the camera. + * + * At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. + * @param settings Specifies the focus mode, the available values include `continuous` and `manual`. + * @param distance Specifies the focus distance, only required when the `mode` is set to `manual`. + * @returns A promise that resolves when the operation succeeds. + * @example + * ```js + * await scanner.setFocus("manual", 5); + * ``` + * @see {@link getFocusSettings} + * @see {@link getCapabilities} + * @category Camera Settings + */ + setFocus(settings: string | { + mode: string; + } | { + mode: "manual"; + distance: number; + } | { + mode: "manual"; + area: { + centerPoint: { + x: string; + y: string; + }; + width?: string; + height?: string; + }; + }, distance?: number): Promise; + /** + * @deprecated Use {@link getFocusSettings} instead. + */ + getFocus(): Object; + /** + * Returns the focus settings. + * @returns The current focus settings. + * @see {@link setFocus} + * @category Camera Settings + */ + getFocusSettings(): Object; + protected _loopReadVideo(): Promise; + /** + * start dce fetching frame loop, and get frame from frame queue + * @ignore + */ + protected _getVideoFrame(): DCEFrame; + /** + * Binds UI, turns on the camera and starts decoding. + * + * This method does not change the original state of the UI: if it doesn't exist in the DOM tree, nothing shows up on the page; if it exists in the DOM tree, it may or may not show up depending on its original state. + * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. + * @fires {@link onPlayed} + * @example + * ```js + * await scanner.setUIElement(document.getElementById("my-barcode-scanner")); + * scanner.onUniqueRead = (txt, result) => { alert(txt); console.log(result); }; + * await scanner.open(); + * // await scanner.close(); + * ``` + * @see {@link close} + * @see {@link hide} + * @see {@link ScannerPlayCallbackInfo} + * @category Open and Close + */ + open(): Promise; + /** + * Bind UI, open the camera, but not decode. + * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. + * @fires {@link onPlayed} + * @example + * ```js + * await scanner.setUIElement(document.getElementById("my-barcode-scanner")); + * await scanner.openVideo(); + * console.log(await scanner.decodeCurrentFrame()); + * // await scanner.close(); + * ``` + * @see {@link close} + * @see {@link hide} + * @see {@link ScannerPlayCallbackInfo} + * @category Open and Close + */ + openVideo(): Promise; + /** + * Stops decoding, releases camera, unbinds and hides UI. + * @example + * ```js + * await scanner.open(); + * await scanner.close(); + * ``` + * @example + * ```js + * await scanner.openVideo(); + * await scanner.close(); + * ``` + * @see {@link hide} + * @category Open and Close + */ + close(): void; + /** + * Binds and shows UI, opens the camera and starts decoding. + * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. + * @fires {@link onPlayed} + * @example + * ```js + * await scanner.setUIElement("https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode/dist/dbr.ui.html"); + * scanner.onUniqueRead = (txt, result) => { alert(txt); console.log(result); }; + * await scanner.show(); + * // await scanner.hide(); + * ``` + * @see {@link close} + * @see {@link hide} + * @see {@link ScannerPlayCallbackInfo} + * @category Open and Close + */ + show(): Promise; + /** + * Bind UI, open the camera, but not decode, and remove the UIElement `display` style if the original style is `display:none;`. + * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. + * @fires {@link onPlayed} + * @example + * ```js + * await scanner.showVideo() + * console.log(await scanner.decodeCurrentFrame()); + * // await scanner.hide(); + * ``` + * @see {@link close} + * @see {@link hide} + * @see {@link ScannerPlayCallbackInfo} + * @category Open and Close + */ + showVideo(): Promise; + /** + * Stops decoding, releases camera and unbinds and hides UI. + * @example + * ```js + * await scanner.show(); + * await scanner.hidee(); + * ``` + * @example + * ```js + * await scanner.showVideo(); + * await scanner.hide(); + * ``` + * @see {@link close} + * @see {@link ScannerPlayCallbackInfo} + * @category Open and Close + */ + hide(): void; + /** + * Shows a Tip message. + * @param x Specifies the x coordinate of the Tip message. + * @param y Specifies the y coordinate of the Tip message. + * @param width Specifies the width of the Tip message, wrapping if the message is too long. + * @param initialMessage Optional. The initial message. + * @param duration Optional. The time during which a Tip message is displayed. The duration is reset each time the message is updated. Default value is `3000`. + * @param autoShowSuggestedTip Optional. Whether or not the Tip box is updated automatically when a tip is suggested. A tip is usually suggested by another SDK such as Dynamsoft Barcode Reader. + * @example + * ```js + * scanner.showTip(500, 200, 500, "The camera is too far away, please move closer!", 3000, true); + * ``` + * @see {@link hideTip} + */ + showTip(x: number, y: number, width: number, initialMessage?: string, duration?: number, autoShowSuggestedTip?: boolean): void; + /** + * Hides the Tip message. + * @see {@link showTip} + */ + hideTip(): void; + /** + * Changes the Tip message. + * @param message Specifies a new message as the Tip. + */ + updateTipMessage(message: string): void; + /** + * Enables manual camera focus when clicking/tapping on the video. + * + * At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). + * @see {@link disableTapToFocus} + * @see {@link isTapToFocusEnabled} + */ + enableTapToFocus(): Promise; + /** + * Disables manual camera focus when clicking/tapping on the video. + * @see {@link enableTapToFocus} + * @see {@link isTapToFocusEnabled} + */ + disableTapToFocus(): void; + /** + * Returns whether clicking/tapping on the video invokes the camera to focus. + * @returns `true` means clicking/tapping on the video will invoke the camera to focus. `false` means clicking/tapping on the video does nothing. + * @see {@link enableTapToFocus} + * @see {@link disableTapToFocus} + */ + isTapToFocusEnabled(): boolean; + /** + * Converts coordinates of a barcode location to the coordinates relative to the top left point of the entire document. + * + * Note: Call this method only after `scanner` is open. + * @param point The coordinates to convert. + * @returns The converted coordinates. + * @see {@link convertToClientCoordinates} + */ + convertToPageCoordinates(point: { + x: number; + y: number; + }): { + x: number; + y: number; + }; + /** + * Converts coordinates of a barcode location to the coordinates within the application's viewport at which the event occurred (as opposed to the coordinate within the page). + * + * Note: Call this method only after `scanner` is open. + * @param point The coordinates to convert. + * @returns The converted coordinates. + * @see {@link convertToClientCoordinates} + */ + convertToClientCoordinates(point: { + x: number; + y: number; + }): { + x: number; + y: number; + }; + /** + * Destroys the `BarcodeScanner` instance. If your page needs to create a new instance from time to time, don't forget to destroy unused old instances. + * @see {@link isContextDestroyed} + * @category Initialize and Destroy + */ + destroyContext(): void; +} + +declare enum EnumBarcodeColourMode { + BICM_DARK_ON_LIGHT = 1, + BICM_LIGHT_ON_DARK = 2, + BICM_DARK_ON_DARK = 4, + BICM_LIGHT_ON_LIGHT = 8, + BICM_DARK_LIGHT_MIXED = 16, + BICM_DARK_ON_LIGHT_DARK_SURROUNDING = 32, + BICM_SKIP = 0, + BICM_REV = 2147483648 +} + +declare enum EnumBarcodeComplementMode { + BCM_AUTO = 1, + BCM_GENERAL = 2, + BCM_SKIP = 0, + BCM_REV = 2147483648 +} + +declare enum EnumClarityCalculationMethod { + ECCM_CONTRAST = 1 +} + +declare enum EnumClarityFilterMode { + CFM_GENERAL = 1 +} + +declare enum EnumColourClusteringMode { + CCM_AUTO = 1, + CCM_GENERAL_HSV = 2, + CCM_SKIP = 0, + CCM_REV = 2147483648 +} + +declare enum EnumColourConversionMode { + CICM_GENERAL = 1, + CICM_SKIP = 0, + CICM_REV = 2147483648 +} + +declare enum EnumConflictMode { + CM_IGNORE = 1, + CM_OVERWRITE = 2 +} + +declare enum EnumDeblurMode { + DM_SKIP = 0, + DM_DIRECT_BINARIZATION = 1, + DM_THRESHOLD_BINARIZATION = 2, + DM_GRAY_EQUALIZATION = 4, + DM_SMOOTHING = 8, + DM_MORPHING = 16, + DM_DEEP_ANALYSIS = 32, + DM_SHARPENING = 64, + DM_BASED_ON_LOC_BIN = 128, + DM_SHARPENING_SMOOTHING = 256 +} + +declare enum EnumDeformationResistingMode { + DRM_AUTO = 1, + DRM_GENERAL = 2, + DRM_BROAD_WARP = 4, + DRM_LOCAL_REFERENCE = 8, + DRM_DEWRINKLE = 16, + DRM_SKIP = 0, + DRM_REV = 2147483648 +} + +declare enum EnumDPMCodeReadingMode { + DPMCRM_AUTO = 1, + DPMCRM_GENERAL = 2, + DPMCRM_SKIP = 0, + DPMCRM_REV = 2147483648 +} + +declare enum EnumGrayscaleTransformationMode { + GTM_INVERTED = 1, + GTM_ORIGINAL = 2, + GTM_SKIP = 0, + GTM_REV = 2147483648 +} + +declare enum EnumImagePreprocessingMode { + IPM_AUTO = 1, + IPM_GENERAL = 2, + IPM_GRAY_EQUALIZE = 4, + IPM_GRAY_SMOOTH = 8, + IPM_SHARPEN_SMOOTH = 16, + IPM_MORPHOLOGY = 32, + IPM_SKIP = 0, + IPM_REV = 2147483648 +} + +declare enum EnumIMResultDataType { + IMRDT_IMAGE = 1, + IMRDT_CONTOUR = 2, + IMRDT_LINESEGMENT = 4, + IMRDT_LOCALIZATIONRESULT = 8, + IMRDT_REGIONOFINTEREST = 16, + IMRDT_QUADRILATERAL = 32 +} + +declare enum EnumIntermediateResultSavingMode { + IRSM_MEMORY = 1, + IRSM_FILESYSTEM = 2, + IRSM_BOTH = 4 +} + +declare enum EnumQRCodeErrorCorrectionLevel { + QRECL_ERROR_CORRECTION_H = 0, + QRECL_ERROR_CORRECTION_L = 1, + QRECL_ERROR_CORRECTION_M = 2, + QRECL_ERROR_CORRECTION_Q = 3 +} + +declare enum EnumRegionPredetectionMode { + RPM_AUTO = 1, + RPM_GENERAL = 2, + RPM_GENERAL_RGB_CONTRAST = 4, + RPM_GENERAL_GRAY_CONTRAST = 8, + RPM_GENERAL_HSV_CONTRAST = 16, + RPM_SKIP = 0, + RPM_REV = 2147483648 +} + +declare enum EnumResultType { + RT_STANDARD_TEXT = 0, + RT_RAW_TEXT = 1, + RT_CANDIDATE_TEXT = 2, + RT_PARTIAL_TEXT = 3 +} + +declare enum EnumTextFilterMode { + TFM_AUTO = 1, + TFM_GENERAL_CONTOUR = 2, + TFM_SKIP = 0, + TFM_REV = 2147483648 +} + +declare enum EnumTextureDetectionMode { + TDM_AUTO = 1, + TDM_GENERAL_WIDTH_CONCENTRATION = 2, + TDM_SKIP = 0, + TDM_REV = 2147483648 +} + +export { BarcodeReader, BarcodeScanner, DSImage, EnumBarcodeColourMode, EnumBarcodeComplementMode, EnumBarcodeFormat, EnumBarcodeFormat_2, EnumBinarizationMode, EnumClarityCalculationMethod, EnumClarityFilterMode, EnumColourClusteringMode, EnumColourConversionMode, EnumConflictMode, EnumDPMCodeReadingMode, EnumDeblurMode, EnumDeformationResistingMode, EnumErrorCode, EnumGrayscaleTransformationMode, EnumIMResultDataType, EnumImagePixelFormat, EnumImagePreprocessingMode, EnumIntermediateResultSavingMode, EnumIntermediateResultType, EnumLocalizationMode, EnumQRCodeErrorCorrectionLevel, EnumRegionPredetectionMode, EnumResultCoordinateType, EnumResultType, EnumScaleUpMode, EnumTerminatePhase, EnumTextFilterMode, EnumTextResultOrderMode, EnumTextureDetectionMode, ImageSource, Region, RuntimeSettings, ScanSettings, TextResult }; diff --git a/dist/dbr.js b/dist/dbr.js index 22ebc22..5ebacc6 100644 --- a/dist/dbr.js +++ b/dist/dbr.js @@ -2,20 +2,21 @@ * Dynamsoft JavaScript Library * @product Dynamsoft Barcode Reader JS Edition * @website http://www.dynamsoft.com - * @copyright Copyright 2023, Dynamsoft Corporation + * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft - * @version 9.6.32 (js 20231027) + * @version 9.6.42 (js 20240426) * @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,i=t?{}:self;let r,n,s,o,a;if("undefined"!=typeof navigator&&(r=navigator,n=r.userAgent,s=r.platform,o=r.mediaDevices),!t){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:r.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 i="unknownBrowser",o=0,l="unknownOS";for(let t in e){const r=e[t]||{};let s=r.str||n,a=r.search||t,l=r.verStr||n,h=r.verSearch||t;if(h instanceof Array||(h=[h]),-1!=s.indexOf(a)){i=t;for(let e of h){let t=l.indexOf(e);if(-1!=t){o=parseFloat(l.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let r=i.str||n,s=i.search||e;if(-1!=r.indexOf(s)){l=e;break}}"Linux"==l&&-1!=n.indexOf("Windows NT")&&(l="HarmonyOS"),a={browser:i,version:o,OS:l}}t&&(a={browser:"ssr",version:0,OS:"ssr"});const l="undefined"!=typeof WebAssembly&&n&&!(/Safari/.test(n)&&!/Chrome/.test(n)&&/\(.+\s11_2_([2-6]).*\)/.test(n)),h=!("undefined"==typeof Worker),c=!(!o||!o.getUserMedia),u=async()=>{let e=!1;if(c)try{(await o.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===a.browser&&a.version>66||"Safari"===a.browser&&a.version>13||"OPR"===a.browser&&a.version>43||"Edge"===a.browser&&a.version;const d=(()=>{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"./"})(),f=" is not allowed to change after `createInstance` or `loadWasm` is called.",g=!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"))||"",_=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",p=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 C extends Promise{constructor(e){let t,i;super(((e,r)=>{t=e,i=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",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,w(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 x=function(){this.init()};x.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 t=this||T;if(e=parseFloat(e),t.ctx||F(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,T.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,F()),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,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\/(.*?) /),l=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:!(l||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(l||!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||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 t=function(i){for(;e._html5AudioPool.length0?o._seek:i._sprite[e][0]/1e3),h=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-l),c=1e3*h/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=l,o._start=u,o._stop=d,o._loop=!(!o._loop&&!i._sprite[e][2])};if(!(l>=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,T.ctx.currentTime),o._playStart=T.ctx.currentTime,void 0===g.bufferSource.start?o._loop?g.bufferSource.noteGrainOn(0,l,86400):g.bufferSource.noteGrainOn(0,l,h):o._loop?g.bufferSource.start(0,l,86400):g.bufferSource.start(0,l,h),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"===T.state&&"interrupted"!==T.ctx.state?_():(i._playLock=!0,i.once("resume",_),i._clearTimer(o._id))}else{var p=function(){g.currentTime=l,g.muted=o._muted||i._muted||T._muted||g.muted,g.volume=o._volume*T.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&&T._navigator.isCocoonJS;if(g.readyState>=3||m)p();else{i._playLock=!0,i._state="loading";var v=function(){i._state="loaded",p(),g.removeEventListener(T._canPlayEvent,v,!1)};g.addEventListener(T._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/h:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=l*n,a=Math.round(100*a)/100,a=l<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(T.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)?T.ctx.currentTime-o._playStart:0,l=o._rateSeek?o._rateSeek-o._seek:0;return o._seek+(l+a*Math.abs(o._rate))}return o._node.currentTime}var h=i.playing(t);h&&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(){h&&i.play(t,!0),i._emit("seek",t)};if(h&&!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&&T._howls.splice(r,1);var n=!0;for(i=0;i=0){n=!1;break}return O&&n&&delete O[e._src],T.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(T._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))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 I=function(e){this._parent=e,this.init()};I.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=++T._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=T._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===T.ctx.createGain?T.ctx.createGainNode():T.ctx.createGain(),e._node.gain.setValueAtTime(i,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=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*T.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=++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,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(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={},A=function(e){var t=e._src;if(O[t])return e._duration=O[t].duration,void M(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(O[t._src]=e,M(t,e)):i()};"undefined"!=typeof Promise&&1===T.ctx.decodeAudioData.length?T.ctx.decodeAudioData(e).then(r).catch(i):T.ctx.decodeAudioData(e,r,i)},M=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())},F=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),t=T._navigator&&T._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var r=/safari/.test(T._navigator&&T._navigator.userAgent.toLowerCase());T._navigator&&!r&&(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,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 l=a._orientation;return i="number"!=typeof i?l[1]:i,r="number"!=typeof r?l[2]:r,n="number"!=typeof n?l[3]:n,s="number"!=typeof s?l[4]:s,o="number"!=typeof o?l[5]:o,"number"!=typeof e?l:(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}`)}})}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`"+f);i._license=t})(P,e)}static get productKeys(){return this._license}static set productKeys(e){P.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){P.license=e}static get organizationID(){return this._license}static set organizationID(e){P.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+f);i._sessionPassword=t})(P,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:l,worker:h,getUserMedia:c,camera:await u(),browser:a.browser,version:a.version,OS:a.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.");P._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`"+f);i._licenseServer=p(t)})(P,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+f);i._deviceFriendlyName=t||""})(P,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.");P.__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=P._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",P.engineResourcePath)}static set defaultUIElementURL(e){P._defaultUIElementURL=e}static _fireHTTPSWarnning(){P.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{P.onWarning&&P.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 E({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;P._onLog&&P._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:l}=e;i=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),P.recalculateResultLocation(i,r,n,a,l,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&&(P._onLog&&P._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(!P.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:r,sp:n,rmk:s}=(e=>{const t=e;if(t._pLoad.isEmpty){let e,r,n=t._license||"",s=JSON.parse(JSON.stringify(t._licenseServer)),o=t._sessionPassword,a=0;if(n.startsWith("t")||n.startsWith("f"))a=0;else if(0===n.length||n.startsWith("P")||n.startsWith("L")||n.startsWith("Y")||n.startsWith("A"))a=1;else{a=2;const t=n.indexOf(":");if(-1!=t&&(n=n.substring(t+1)),n.startsWith("DLS2")){let t;try{let e=n.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(n=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof n&&(n=JSON.stringify(n)),0===s.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),s=p(e)}!o&&t.sessionPassword&&(o=t.sessionPassword),e=t.remark}("200001"===n||n.startsWith("200001-"))&&(s&&s.length||(n="")),n||(a=1)}if(a&&(i.crypto||(r="Please upgrade your browser to support online key."),i.crypto.subtle||(r="Require https to use online key in this browser.")),r){if(1!==a)throw new Error(r);a=0,console.warn(r),t._lastErrorCode=-1,t._lastErrorString=r}return 1===a&&(n="",console.warn("Applying for a public trial license ...")),{lt:a,l:n,ls:s,sp:o,rmk:e}}throw new Error("Can't preprocess license again"+f)})(P);this._pLoad.task=async(i,o)=>{let l=P.engineResourcePath+P._workerName;P.engineResourcePath.startsWith(location.origin)||(l=await fetch(l).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),P._dbrWorker=new Worker(l),P._dbrWorker.onerror=e=>{let t=new Error(e.message);o(t)},P._dbrWorker.onmessage=async t=>{let r=t.data?t.data:t;switch(r.type){case"log":P._onLog&&P._onLog(r.message);break;case"load":{r.message&&(r.message=r.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,n=!1;1===e&&(n=!0,r.message||(r.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),r.success?(P._dbrWorker.onerror=null,P._version=r.version+"(JS "+P._jsVersion+"."+P._jsEditVersion+")",P._onLog&&P._onLog("load dbr worker success"),r.message&&console.warn(r.message)):(t=new Error(r.message),t.stack=r.stack+"\n"+t.stack,t.ltsErrorCode=r.ltsErrorCode,n||111==r.ltsErrorCode&&-1!=r.message.toLowerCase().indexOf("trial license")&&(n=!0)),n&&P.showDialog(r.success?"warn":"error",r.message),r.success?i():o(t);break}case"task":{let e=r.id,t=r.body;try{P._taskCallbackMap.get(e)(t),P._taskCallbackMap.delete(e)}catch(t){throw P._taskCallbackMap.delete(e),t}break}default:P._onLog&&P._onLog(t)}},P._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:P.engineResourcePath,bUseFullFeature:P._bUseFullFeature,bd:P._bWasmDebug,v:P._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:a,cv:P.authCacheVersion,fn:P.deviceFriendlyName,ls:r,sp:n,rmk:s})}}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(!h&&e.classList.contains("dls-license-icon-close"))h=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 l=t.substring(n+1,s);o.setAttribute("href",l),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 P.loadWasm(),await new Promise(((t,i)=>{let r=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){const e=new P;return e._instanceID=await P.createInstanceInWorker(),P._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){P._onLog&&P._onLog("decode(source: any)"),P._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):P.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):P.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,l)=>{let h=P._nextTaskID++;P._taskCallbackMap.set(h,(e=>{if(e.success){let t,i=P._onLog?Date.now():0;P._onLog&&P._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return l(e)}if(P._onLog){let e=Date.now();P._onLog("DBR getting message from worker timestamp: "+i),P._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),P._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),P._onLog("Handling results from DBR worker costs: "+(e-i)),P._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,l(t)}})),this._timeEnterInnerDBR=Date.now(),P._onLog&&P._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),P._dbrWorker.postMessage({type:"decodeBuffer",id:h,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,orientation:s,config:o}},[e.buffer]),P._onLog&&o&&o.timeStamp&&P._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s,o){P._onLog&&P._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 P._onLog&&P._onLog("decodeBuffer(buffer,width,height,stride,format)"),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=P._nextTaskID++;P._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)}})),P._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(!P._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=P._nextTaskID++;P._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)}})),P._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=L,await new Promise(((e,t)=>{let i=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=L,await new Promise(((e,t)=>{let i=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){P._onLog&&P._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){P._onLog&&P._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}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl);let l=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(l,0,0,n,s,i,r),l}async _decode_Canvas(t,i){if(P._onLog&&P._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(P._onLog&&P._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}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r);let l=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(l,0,0,n,s,i,r),l}async _decode_DCEFrame(t,i){if(P._onLog&&P._onLog("_decode_DCEFrame(dceFrame)"),!P.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:l,timeStamp:h}=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=h):u={timeStamp:h},a&&l)if("grey"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,l,e.EnumImagePixelFormat.IPF_GrayScaled,0,u);else if("rgba"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,l,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,l,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(P._onLog&&P._onLog("_decode_DSImage(dsImage)"),!P.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 P._onLog&&P._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 l=s/r,h=o/n;e.x1=e.x1/l+t,e.x2=e.x2/l+t,e.x3=e.x3/l+t,e.x4=e.x4/l+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,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),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}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&&!P._setWarnnedEx.has(t.description)&&(P._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==i.DBR_SUCCESS)return t.data;throw P.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!0}})}))}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(P._onLog&&P._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=P._nextTaskID++;P._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)}})),P._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(!P._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=P._nextTaskID++;P._taskCallbackMap.set(r,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),P._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 P._onLog&&P._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));P._onLog&&P._onLog("======= once read ======="),P._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(),!P.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return P._onLog&&P._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:l}=e;t=i.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),P.recalculateResultLocation(t,r,n,a,l,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(P._onLog&&P._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&&(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"),P._onLog&&P._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(P._onLog&&P._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 P._onLog&&P._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.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(P._onLog&&P._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||this._promiseStartScan)&&this.stopScanning(),this.setImageSource(null);let e=P._nextTaskID++;P._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),P._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}P._jsVersion="9.6.32",P._jsEditVersion="20231027",P._version=`loading...(JS ${P._jsVersion}.${P._jsEditVersion})`,P._license=g,P._sessionPassword=_,P.browserInfo=a,P._workerName=`dbr-${P._jsVersion}.browser.worker.js`,P._engineResourcePath=d,P._licenseServer=[],P._deviceFriendlyName="",P._isShowRelDecodeTimeInResults=!1,P._bWasmDebug=!1,P._bNeverShowDialog=!1,P.__bUseFullFeature=!0,P._nextTaskID=0,P._taskCallbackMap=new Map,P._pLoad=new C,P._lastErrorCode=0,P._lastErrorString="",P._setWarnnedEx=new Set,P._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var k={653:(e,t,i)=>{var r,n,s,o,a,l,h,c,u,d,f,g,_,p,m,v,y,S,b,w,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 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 l=new ImageData(a,r,n);i.putImageData(l,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,l=Math.PI/2,x.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/l){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/l){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,l){var h,c,u=new x.Point(a.x,a.y);0===l?(c=e[l+1],h=i?o(x.util.createVector(c,u)).addEquals(u):e[e.length-1]):l===e.length-1?(h=e[l-1],c=i?o(x.util.createVector(h,u)).addEquals(u):e[0]):(h=e[l-1],c=e[l+1]);var d,f,g=x.util.getBisector(u,h,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],l=i[4],h=i[5],c=function(e,t,i,s,o,a,l){var h=Math.PI,c=l*h/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=_*_,b=m*v-m*y-v*S,w=0;if(b<0){var C=Math.sqrt(1-b/(m*v));i*=C,s*=C}else w=(o===a?-1:1)*Math.sqrt(b/(m*y+v*S));var T=w*i*p/s,E=-w*s*_/i,I=d*T-u*E+.5*e,O=u*T+d*E+.5*t,A=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*h:1===a&&R<0&&(R+=2*h);for(var D=Math.ceil(Math.abs(R/h*2)),M=[],F=R/D,L=8/3*Math.sin(F/4)*Math.sin(F/4)/Math.sin(F/2),P=A+F,k=0;kw)for(var T=1,E=_.length;T2;for(t=t||0,h&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,l=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+l*t]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(t,i,r,n,s,o,a,l){var h;if(x.cachesBoundsOfCurve&&(h=e.call(arguments),x.boundsOfCurveCache[h]))return x.boundsOfCurveCache[h];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,b=Math.abs,w=[],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*l,d=3*n-3*i),b(c)<1e-12){if(b(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,O,A=w.length,R=A;A--;)E=(O=1-(f=w[A]))*O*O*t+3*O*O*f*r+3*O*f*f*s+f*f*f*a,C[0][A]=E,I=O*O*O*i+3*O*O*f*n+3*O*f*f*o+f*f*f*l,C[1][A]=I;C[0][R]=t,C[1][R]=i,C[0][R+1]=a,C[1][R+1]=l;var D=[{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[h]=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=l(s),n=s,(r=o(h.x,h.y,i.x,i.y))+a>t?(s-=c,c/=2):(h=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 l=0,h=o.length;l-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},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var h in l)o[l[h]]+=parseInt(t(e,h),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,l=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,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(s),a((function(e){var t,h=e||+new Date,c=i.duration||500,u=h+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-h,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),b=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=b,s.durationRate=n,!o){if(!f(S,b,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 l()):(d(S,b,n),void a(e));l()}}(h)})),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,l=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(l){if(Array.isArray(t))return l(e(t,t,0),i,r);l(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=l?i.map(s):s(i,n)}}else i="";return!l&&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;)l.shift(),h=t.util.multiplyTransformMatrices(h,l[0]);return h}}();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,l,h=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=!h||!(h=h.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,b={},w="",C=0,x=0;if(b.width=0,b.height=0,b.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 b;if(m)return b.width=s(d),b.height=s(f),b;if(i=-parseFloat(h[1]),r=-parseFloat(h[2]),n=parseFloat(h[3]),o=parseFloat(h[4]),b.minX=i,b.minY=r,b.viewBoxWidth=n,b.viewBoxHeight=o,y?(b.width=n,b.height=o):(b.width=s(d),b.height=s(f),c=b.width/n,u=b.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=b.width-n*c,x=b.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 b;if((g||_)&&"#document"!==e.parentNode.nodeName&&(w=" translate("+s(g)+" "+s(_)+") "),a=w+" matrix("+c+" 0 0 "+u+" "+(i*c+C)+" "+(r*u+x)+") ","svg"===e.nodeName){for(l=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)l.appendChild(e.firstChild);e.appendChild(l)}else(l=e).removeAttribute("x"),l.removeAttribute("y"),a=l.getAttribute("transform")+a;return l.setAttribute("transform",a),b}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),l=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),h=(s.y-n.y)*(r.x-e.x)-(s.x-n.x)*(r.y-e.y);if(0!==h){var c=a/h,u=l/h;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===l?"Coincident":"Parallel");return o},t.Intersection.intersectLinePolygon=function(e,t,r){var n,s,o,a,l=new i,h=r.length;for(a=0;a0&&(l.status="Intersection"),l},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),l=new t.Point(s.x,o.y),h=i.intersectLinePolygon(s,a,e),c=i.intersectLinePolygon(a,o,e),u=i.intersectLinePolygon(o,l,e),d=i.intersectLinePolygon(l,s,e),f=new i;return f.appendPoints(h.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]),l=t.util.array.min([e,i,r]);if(o=(a+l)/2,a===l)n=s=0;else{var h=a-l;switch(s=o>.5?h/(2-a-l):h/(a+l),a){case e:n=(i-r)/h+(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===h&&e.originY===h}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),l=e(t,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),l}}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 b(e,i,r,n,s){var o=e.target,a=o.controls[e.corner],l=o.canvas.getZoom(),h=o.padding/l,c=o.toLocalPoint(new t.Point(n,s),i,r);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=a.offsetX,c.y-=a.offsetY,c}function w(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,h=t.target,c=h._getTransformedDimensions(0,h.skewY),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=h.skewX;f<2?n=0:(n=u(Math.atan2(f/h.scaleX,c.y/h.scaleY)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().y;h.set("skewX",n),C(h,"skewY","scaleY","y",p)}return _}function T(e,t,i,r){var n,h=t.target,c=h._getTransformedDimensions(h.skewX,0),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=h.skewY;f<2?n=0:(n=u(Math.atan2(f/h.scaleY,c.x/h.scaleX)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().x;h.set("skewY",n),C(h,"skewX","scaleX","x",p)}return _}function E(e,t,i,r,n){n=n||{};var s,o,a,l,h,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),w=m(f,y,S),C=t.gestureScale;if(w)return!1;if(C)o=t.scaleX*C,a=t.scaleY*C;else{if(s=b(t,t.originX,t.originY,i,r),h="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,t.signX||(t.signX=h),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==h||t.signY!==u))return!1;if(l=f._getTransformedDimensions(),S&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=t.original,E=x/(Math.abs(l.x*T.scaleX/f.scaleX)+Math.abs(l.y*T.scaleY/f.scaleY));o=T.scaleX*E,a=T.scaleY*E}else o=Math.abs(s.x*f.scaleX/l.x),a=Math.abs(s.y*f.scaleY/l.y);p(t)&&(o*=2,a*=2),t.signX!==h&&"y"!==y&&(t.originX=c[t.originX],o*=-1,t.signX=h),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.signY=u)}var I=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)),I!==f.scaleX||O!==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,l=Math.atan2(n.ey-o.y,n.ex-o.x),h=Math.atan2(r-o.y,i-o.x),c=u(h-l+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(l)&&(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=b(t,h,h,i,r).y>0?o:l:(c>0&&(n=u===s?o:l),c<0&&(n=u===s?l:o),w(a)&&(n=n===o?l: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,l=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),l&&n.set("top",o),(a||l)&&g("moving",v(e,t,i,r)),a||l},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=b,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,l=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,h=l?"stroke":"fill",c=!l&&(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[h](),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,l=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(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[h+"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,l,h,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),l=f*t.util.cos(_),h=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),o=l=f*t.util.cos(g),a=h=f*t.util.sin(g);return{tl:{x:r-h,y:n-l},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+h,y:n+l}}},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 l=o.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),s=l.length;s--;){var h=l[s].split(/\s*:\s*/),c=h[0].trim(),u=h[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),l=(i=i||{},t(this.colorStops,!0)),h=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(l.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(h)for((l=l.concat()).reverse(),r=0,n=l.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=l.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,l,h,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)),l=c.length;l--;)f.push(e(c[l],s));return h=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:h,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,l=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 l;if(e.style||(e.style={}),void 0===e.getContext)throw l;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,l="",h={},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",l,"","\n"].join("")),l},_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+h&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),h++;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,l=this._activeObject,h=0;if(e===l&&"activeSelection"===e.type)for(r=(a=l._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,l=this.viewportTransform;return e.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(l[0],l[1],l[2],l[3],l[4],l[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,l=this._getActionFromCorner(r,s,e,i),h=this._getOriginFromCorner(i,s),c=e[this.centeredKey],u={target:i,action:l,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:h.x,originY:h.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,l,c)&&(u.originX="center",u.originY="center"),u.original.originX=h.x,u.original.originY=h.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),l=Math.max(r.x,s.x),h=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(o,a,l-o,h-a)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,o+=c,a+=c,l-=c,h-=c,x.Object.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(o,a,l-o,h-a))},findTarget:function(e,t){if(!this.skipTargetFind){var r,n,s=this.getPointer(e,!0),o=this._activeObject,a=this.getActiveObjects(),l=i(e),h=a.length>1&&!t||1===a.length;if(this.targets=[],h&&o._findTargetCorner(s,l))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,l=o.height||0;a&&l||("top"in o&&"bottom"in o&&(l=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 h=this.getRetinaScaling();return 1!==h&&(n.x/=h,n.y/=h),r=0===a||0===l?{width:1,height:1}:{width:s.width/a,height:s.height/l},{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 l,h;if(t){if(l=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[l],u=c&&c.getMouseUpHandler(e,t,c);u&&u(e,i,(h=this.getPointer(e)).x,h.y)}t.isMoving=!1}if(i&&(i.target!==t||i.corner!==l)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(e,t,c);h=h||this.getPointer(e),f&&f(e,i,h.x,h.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)),l=new x.Point(y(r,s),y(n,o)),h=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((t=this._objects[u])&&t.selectable&&t.visible&&(h&&t.intersectsWithRect(a,l,!0)||t.isContainedWithinRect(a,l,!0)||h&&t.containsPoint(a,null,!0)||h&&t.containsPoint(l,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,l=this.viewportTransform,h=(l[4]-(t.left||0))*e,c=(l[5]-(t.top||0))*e,u=this.interactive,d=[a,0,0,a,h,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=l,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()),l=t.minCacheSideLimit,h=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=h!==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,b=h>y||c>S;v=b||(h<.9*y||c<.9*S)&&y>l&&S>l,b&&!a.capped&&(h>l||c>l)&&(p=.1*h,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(h+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=h,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(),l=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,l=t.util.multiplyTransformMatrices(a,l),r=t.util.qrDecompose(l),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,l=n.y/this.scaleY/o;s.width=a,s.height=l,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,l),r.lineTo(0,l),r.closePath(),r.translate(a/2,l/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 l,h,c,u,d=t.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+h)*o(l.scaleX),_.y=2*Math.round(o(g.offsetY)+h)*o(l.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,b={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,l=e.x,h=e.y;return"string"==typeof t?t=b[t]:t-=.5,"string"==typeof r?r=b[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(),l=e.x+s*a.x,h=e.y+o*a.y),new x.Point(l,h)},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?b[this.originX]:this.originX-.5,i="string"==typeof e?b[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()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=e.indexOf("COMMON_PARTS"),p=t.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+x.Object.__uid++,r='\n'+l.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,h,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)),l&&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;l--)if(n=a[l],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,l=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,-l/2,a,l),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 l={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(l.startValue,l.endValue,l.duration,l):x.util.animate(l)}}),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,l=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 l: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,l=.4477152502;e.beginPath(),e.moveTo(s+t,o),e.lineTo(s+r-t,o),a&&e.bezierCurveTo(s+r-l*t,o,s+r,o+l*i,s+r,o+i),e.lineTo(s+r,o+n-i),a&&e.bezierCurveTo(s+r,o+n-l*i,s+r-l*t,o+n,s+r-t,o+n),e.lineTo(s+t,o+n),a&&e.bezierCurveTo(s+l*t,o+n,s,o+n-l*i,s,o+n-i),e.lineTo(s,o+i),a&&e.bezierCurveTo(s,o+l*i,s+l*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,l=0,h=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_'+l+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,e=["\t\n'],this.fill=h}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,l=s.width,h=s.height;o.width=l,o.height=h,this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=n,x.filterBackend.applyFilters([e],s,l,h,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,l=a(this.cropX,0),h=a(this.cropY,0),c=t.naturalWidth||t.width,u=t.naturalHeight||t.height,d=l*i,f=h*r,g=o(n*i,c-d),_=o(s*r,u-f),p=-n/2,m=-s/2,v=o(n,c/i-l),y=o(s,u/r-h);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,l=0,h=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&&(l=e/2),"Max"===t.alignX&&(l=e),e=r-u/s,"Mid"===t.alignY&&(h=e/2),"Max"===t.alignY&&(h=e),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:l,cropY:h}}}),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 l,h,c={imageBuffer:a,destinationWidth:e,destinationHeight:t,targetCanvas:o};o.width=e,o.height=t,l=window.performance.now(),E.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),I.call(c,this.gl,c),h>window.performance.now()-l?(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 l={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},h=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,h),e.forEach((function(e){e&&e.applyTo(l)})),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)}(l),this.copyGLTo2D(a,l),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(l.sourceTexture),a.deleteTexture(l.targetTexture),a.deleteFramebuffer(h),n.getContext("2d").setTransform(1,0,0,1,0,0),l},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,l=this.matrix,h=this.colorsOnly;for(s=0;s=S||o<0||o>=y||(l=4*(a*y+o),h=p[f*m+d],t+=_[l]*h,i+=_[l+1]*h,r+=_[l+2]*h,C||(n+=_[l+3]*h));w[s]=t,w[s+1]=i,w[s+2]=r,w[s+3]=C?_[s+3]:n}e.imageData=b},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;th[0]&&n>h[1]&&s>h[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,l,h=e.imageData.data,c=h.length,u=1-this.alpha;i=(l=new t.Color(this.color).getSource())[0]*this.alpha,r=l[1]*this.alpha,n=l[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,l=o(s*i),h=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(e,s,a,l,h):"hermite"===this.resizeType?n=this.hermiteFastResize(e,s,a,l,h):"bilinear"===this.resizeType?n=this.bilinearFiltering(e,s,a,l,h):"lanczos"===this.resizeType&&(n=this.lanczosResize(e,s,a,l,h)),e.imageData=n},sliceByTwo:function(e,i,n,s,o){var a,l,h=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-b.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-b.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,O+=T*c[E=4*(L*t+x)],A+=T*c[E+1],R+=T*c[E+2],D+=T*c[E+3]))}d[E=4*(C*a+l)]=O/I,d[E+1]=A/I,d[E+2]=R/I,d[E+3]=D/I}return++l1&&F<-1||(y=2*F*F*F-3*F*F+1)>0&&(T+=y*f[3+(M=4*(D+I*t))],b+=y,f[M+3]<255&&(y=y*f[M+3]/250),w+=y*f[M],C+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=w/S,_[v+1]=C/S,_[v+2]=x/S,_[v+3]=T/b}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,l=e.fillStyle,h=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:l,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):{},l=this._measureChar(e,o,r,a),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),h+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:h,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[t][i-1];u.left=d.left+d.width+l.kernedWidth-l.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),h&&m&&(e.fillStyle=m,e.fillRect(I,c+w*r+o,d,this.fontSize/15)),u=f.left,d=f.width,h=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-b,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 l=0;l0?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,l=e.topOffset,h=this.getValueOfPropertyAt(r,n,"deltaY");l+=(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,l+e.top+h,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,l=o.lineIndex,h=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=l;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][h].left),u>=a&&u1)&&(g/=this.lineHeight);var v=e.left+f+_,y=p-_,S=g,b=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,b=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+b,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(),l={x:t.left+o,y:t.top+t.topOffset+s},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/h,d=c.height/h,f=u-s,g=d-s,_=c.clientWidth/u,p=c.clientHeight/d;return l=x.util.transformPoint(l,a),(l=x.util.transformPoint(l,this.canvas.viewportTransform)).x*=_,l.y*=p,l.x<0&&(l.x=0),l.x>f&&(l.x=f),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.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,l=s.lineIndex,h=s.charIndex;if(o!==l){if(this.styles[o])for(i=a;i=h&&(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 l in i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&(n=this.styles[e][0===t?t:t-1]),this.styles[e]){var h=parseInt(l,10);h>=t&&(o=!0,s[h-t]=this.styles[e][l],a&&0===t||delete this.styles[e][l])}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 l=n[t?t-1:1];l&&i--;)this.styles[e][t+i]=C(l)},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,l=0,h=this._textLines.length;l0&&(o+=this._textLines[l-1].length+this.missingNewlineOffset(l-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,l=this._text.length,h=a.length,c=h-l,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):h0&&(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),l=this._textLines[n].slice(0,s),h=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-l.length+(1-h)},_getIndexOnLine:function(e,t){for(var i,r,n=this._textLines[e],s=this._getLineLeftOffset(e),o=0,a=0,l=n.length;at){r=!0;var h=s-i,c=s,u=Math.abs(h-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,l,h=this.getHeightOfLine(t),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[t];r+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)l=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&&!l&&this._reSpaceAndTab.test(f[g])&&(l=!0),l||(n=n||this.getCompleteStyleDeclaration(t,g),s=this.getCompleteStyleDeclaration(t,g+1),l=this._hasStyleChangedForSvg(n,s)),l&&(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,l=0,h=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 l in i[a])if(l>=r&&(!n||lr&&!p?(a.push(l),l=[],s=f,p=!0):s+=m,p||o||l.push(d),l=l.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(l),_+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:()=>{}},B={};function N(e){var t=B[e];if(void 0!==t)return t.exports;var i=B[e]={exports:{}};return k[e](i,i.exports,N),i.exports}N.d=(e,t)=>{for(var i in t)N.o(t,i)&&!N.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},N.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var j={};(()=>{let e;N.d(j,{R:()=>e}),e="undefined"!=typeof document&&"undefined"!=typeof window?N(653).fabric:{version:"5.2.1"}})();var V=j.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,i=t?{}:self;let r,n,s,o,a;"undefined"!=typeof navigator&&(r=navigator,n=r.userAgent,s=r.platform,o=r.mediaDevices),function(){if(!t){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:r.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 i="unknownBrowser",o=0,l="unknownOS";for(let t in e){const r=e[t]||{};let s=r.str||n,a=r.search||t,l=r.verStr||n,h=r.verSearch||t;if(h instanceof Array||(h=[h]),-1!=s.indexOf(a)){i=t;for(let e of h){let t=l.indexOf(e);if(-1!=t){o=parseFloat(l.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let r=i.str||n,s=i.search||e;if(-1!=r.indexOf(s)){l=e;break}}"Linux"==l&&-1!=n.indexOf("Windows NT")&&(l="HarmonyOS"),a={browser:i,version:o,OS:l}}t&&(a={browser:"ssr",version:0,OS:"ssr"})}();const l="undefined"!=typeof WebAssembly&&n&&!(/Safari/.test(n)&&!/Chrome/.test(n)&&/\(.+\s11_2_([2-6]).*\)/.test(n)),h=!("undefined"==typeof Worker),c=!(!o||!o.getUserMedia),u=async()=>{let e=!1;if(c)try{(await o.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===a.browser&&a.version>66||"Safari"===a.browser&&a.version>13||"OPR"===a.browser&&a.version>43||"Edge"===a.browser&&a.version;const d=(()=>{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"./"})(),f=" is not allowed to change after `createInstance` or `loadWasm` is called.",g=!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"))||"",_=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",p=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 C extends Promise{constructor(e){let t,i;super(((e,r)=>{t=e,i=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",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,w(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 x=function(){this.init()};x.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 t=this||T;if(e=parseFloat(e),t.ctx||L(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,T.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,L()),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,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\/(.*?) /),l=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:!(l||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(l||!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||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 t=function(i){for(;e._html5AudioPool.length0?o._seek:i._sprite[e][0]/1e3),h=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-l),c=1e3*h/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=l,o._start=u,o._stop=d,o._loop=!(!o._loop&&!i._sprite[e][2])};if(!(l>=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,T.ctx.currentTime),o._playStart=T.ctx.currentTime,void 0===g.bufferSource.start?o._loop?g.bufferSource.noteGrainOn(0,l,86400):g.bufferSource.noteGrainOn(0,l,h):o._loop?g.bufferSource.start(0,l,86400):g.bufferSource.start(0,l,h),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"===T.state&&"interrupted"!==T.ctx.state?_():(i._playLock=!0,i.once("resume",_),i._clearTimer(o._id))}else{var p=function(){g.currentTime=l,g.muted=o._muted||i._muted||T._muted||g.muted,g.volume=o._volume*T.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&&T._navigator.isCocoonJS;if(g.readyState>=3||m)p();else{i._playLock=!0,i._state="loading";var v=function(){i._state="loaded",p(),g.removeEventListener(T._canPlayEvent,v,!1)};g.addEventListener(T._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]):n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10)),!(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 s=0;s0?r/h:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=l*n,a=Math.round(100*a)/100,a=l<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(T.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 s=0;s=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 n=i._soundById(t);if(n){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var s=i.playing(t)?T.ctx.currentTime-n._playStart:0,o=n._rateSeek?n._rateSeek-n._seek:0;return n._seek+(o+s*Math.abs(n._rate))}return n._node.currentTime}var a=i.playing(t);a&&i.pause(t,!0),n._seek=e,n._ended=!1,i._clearTimer(t),i._webAudio||!n._node||isNaN(n._node.duration)||(n._node.currentTime=e);var l=function(){a&&i.play(t,!0),i._emit("seek",t)};if(a&&!i._webAudio){var h=function(){i._playLock?setTimeout(h,0):l()};setTimeout(h,0)}else l()}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&&T._howls.splice(r,1);var n=!0;for(i=0;i=0){n=!1;break}return O&&n&&delete O[e._src],T.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(T._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))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 I=function(e){this._parent=e,this.init()};I.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=++T._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,i=T._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===T.ctx.createGain?T.ctx.createGainNode():T.ctx.createGain(),e._node.gain.setValueAtTime(i,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=t._src,e._node.preload=!0===t._preload?"auto":t._preload,e._node.volume=i*T.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=++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,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(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={},A=function(e){var t=e._src;if(O[t])return e._duration=O[t].duration,void M(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(O[t._src]=e,M(t,e)):i()};"undefined"!=typeof Promise&&1===T.ctx.decodeAudioData.length?T.ctx.decodeAudioData(e).then(r).catch(i):T.ctx.decodeAudioData(e,r,i)},M=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())},L=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),t=T._navigator&&T._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),i=t?parseInt(t[1],10):null;if(e&&i&&i<9){var r=/safari/.test(T._navigator&&T._navigator.userAgent.toLowerCase());T._navigator&&!r&&(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,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 l=a._orientation;return i="number"!=typeof i?l[1]:i,r="number"!=typeof r?l[2]:r,n="number"!=typeof n?l[3]:n,s="number"!=typeof s?l[4]:s,o="number"!=typeof o?l[5]:o,"number"!=typeof e?l:(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{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+f);i._license=t})(P,e)}static get productKeys(){return this._license}static set productKeys(e){P.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){P.license=e}static get organizationID(){return this._license}static set organizationID(e){P.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+f);i._sessionPassword=t})(P,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:l,worker:h,getUserMedia:c,camera:await u(),browser:a.browser,version:a.version,OS:a.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.");P._engineResourcePath=(e=>{if(null==e&&(e="./"),t);else{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`"+f);i._licenseServer=p(t)})(P,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+f);i._deviceFriendlyName=t||""})(P,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.");P.__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=P._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",P.engineResourcePath)}static set defaultUIElementURL(e){P._defaultUIElementURL=e}static _fireHTTPSWarnning(){P.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{P.onWarning&&P.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 E({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;P._onLog&&P._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:l}=e;i=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),P.recalculateResultLocation(i,r,n,a,l,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&&(P._onLog&&P._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(!P.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:r,sp:n,rmk:s}=((e,t=!1)=>{const r=e;if(r._pLoad.isEmpty){let e,n,s,o=r._license||"",a=JSON.parse(JSON.stringify(r._licenseServer)),l=r._sessionPassword,h=0;if(o.startsWith("t")||o.startsWith("f"))h=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))h=1;else{h=2;const t=o.indexOf(":");-1!=t&&(o=o.substring(t+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))h=0;else{if(o.startsWith("DLS2")){let t;try{let e=o.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(o=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),a=p(e)}!l&&t.sessionPassword&&(l=t.sessionPassword),e=t.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(h=1)}}if(h&&(t||(i.crypto||(s="Please upgrade your browser to support online key."),i.crypto.subtle||(s="Require https to use online key in this browser."))),s){if(1!==h)throw new Error(s);h=0,console.warn(s),r._lastErrorCode=-1,r._lastErrorString=s}return 1===h&&(o="",console.warn("Applying for a public trial license ...")),{lt:h,l:o,ls:a,sp:l,rmk:e,cv:n}}throw new Error("Can't preprocess license again"+f)})(P);this._pLoad.task=async(i,o)=>{let l=P.engineResourcePath+P._workerName;P.engineResourcePath.startsWith(location.origin)||(l=await fetch(l).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),P._dbrWorker=new Worker(l),URL.revokeObjectURL(l),P._dbrWorker.onerror=e=>{let t=new Error(e.message);o(t)},P._dbrWorker.onmessage=async t=>{let r=t.data?t.data:t;switch(r.type){case"log":P._onLog&&P._onLog(r.message);break;case"load":{r.message&&(r.message=r.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,n=!1;1===e&&(n=!0,r.message||(r.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),r.success?(P._dbrWorker.onerror=null,P._version=r.version+"(JS "+P._jsVersion+"."+P._jsEditVersion+")",P._onLog&&P._onLog("load dbr worker success"),r.message&&console.warn(r.message)):(t=new Error(r.message),t.stack=r.stack+"\n"+t.stack,t.ltsErrorCode=r.ltsErrorCode,n||111==r.ltsErrorCode&&-1!=r.message.toLowerCase().indexOf("trial license")&&(n=!0)),n&&P.showDialog(r.success?"warn":"error",r.message),r.success?i():o(t);break}case"task":{let e=r.id,t=r.body;try{P._taskCallbackMap.get(e)(t),P._taskCallbackMap.delete(e)}catch(t){throw P._taskCallbackMap.delete(e),t}break}default:P._onLog&&P._onLog(t)}},P._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:P.engineResourcePath,bUseFullFeature:P._bUseFullFeature,bd:P._bWasmDebug,v:P._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:a,cv:P.authCacheVersion,fn:P.deviceFriendlyName,ls:r,sp:n,rmk:s})}}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(!h&&e.classList.contains("dls-license-icon-close"))h=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 l=t.substring(n+1,s);o.setAttribute("href",l),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 P.loadWasm(),await new Promise(((t,i)=>{let r=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}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.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,this.beepSound=new E({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}static async createInstance(){const e=new P;return e._instanceID=await P.createInstanceInWorker(),P._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){P._onLog&&P._onLog("decode(source: any)"),P._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):P.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):P.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,l)=>{let h=P._nextTaskID++;P._taskCallbackMap.set(h,(e=>{if(e.success){let t,i=P._onLog?Date.now():0;P._onLog&&P._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return l(e)}if(P._onLog){let e=Date.now();P._onLog("DBR getting message from worker timestamp: "+i),P._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),P._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),P._onLog("Handling results from DBR worker costs: "+(e-i)),P._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,l(t)}})),this._timeEnterInnerDBR=Date.now(),P._onLog&&P._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),P._dbrWorker.postMessage({type:"decodeBuffer",id:h,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,orientation:s,config:o}},[e.buffer]),P._onLog&&o&&o.timeStamp&&P._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s,o){P._onLog&&P._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 P._onLog&&P._onLog("decodeBuffer(buffer,width,height,stride,format)"),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=P._nextTaskID++;P._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)}})),P._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(!P._bUseFullFeature){if(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=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!P._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof 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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){P._onLog&&P._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.src=r,n.onload=()=>{URL.revokeObjectURL(n.src),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){P._onLog&&P._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}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r);let l=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(l,0,0,n,s,i,r),l}async _decode_Canvas(t,i){if(P._onLog&&P._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(P._onLog&&P._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}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r);let l=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(l,0,0,n,s,i,r),l}async _decode_DCEFrame(t,i){if(P._onLog&&P._onLog("_decode_DCEFrame(dceFrame)"),!P.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:l,timeStamp:h}=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=h):u={timeStamp:h},a&&l)if("grey"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,l,e.EnumImagePixelFormat.IPF_GrayScaled,0,u);else if("rgba"===a)r=await this._decodeBuffer_Uint8Array(c,n,s,l,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,l,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(P._onLog&&P._onLog("_decode_DSImage(dsImage)"),!P.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)}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 l=s/r,h=o/n;e.x1=e.x1/l+t,e.x2=e.x2/l+t,e.x3=e.x3/l+t,e.x4=e.x4/l+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,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),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}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&&!P._setWarnnedEx.has(t.description)&&(P._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==i.DBR_SUCCESS)return t.data;throw P.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!0}})}))}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(P._onLog&&P._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=P._nextTaskID++;P._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)}})),P._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(!P._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=P._nextTaskID++;P._taskCallbackMap.set(r,(i=>{if(i.success)return e();{let e=new Error(i.message);return e.stack+="\n"+i.stack,t(e)}})),P._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 P._onLog&&P._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));P._onLog&&P._onLog("======= once read ======="),P._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(),!P.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return P._onLog&&P._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:l}=e;t=i.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),P.recalculateResultLocation(t,r,n,a,l,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(P._onLog&&P._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&&(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"),P._onLog&&P._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(P._onLog&&P._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 P._onLog&&P._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;const t=e=>this.dce.getDrawingLayers().some((t=>t.getId()===e));if(!t(3)&&!(null==e?void 0:e.length))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.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(P._onLog&&P._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||this._promiseStartScan)&&this.stopScanning(),this.setImageSource(null);let e=P._nextTaskID++;P._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),P._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}P._jsVersion="9.6.42",P._jsEditVersion="20240426",P._version=`loading...(JS ${P._jsVersion}.${P._jsEditVersion})`,P._license=g,P._sessionPassword=_,P.browserInfo=a,P._workerName=`dbr-${P._jsVersion}.browser.worker.js`,P._engineResourcePath=d,P._licenseServer=[],P._deviceFriendlyName="",P._isShowRelDecodeTimeInResults=!1,P._bWasmDebug=!1,P._bNeverShowDialog=!1,P.__bUseFullFeature=!0,P._nextTaskID=0,P._taskCallbackMap=new Map,P._pLoad=new C,P._lastErrorCode=0,P._lastErrorString="",P._setWarnnedEx=new Set,P._defaultUIElementURL="@engineResourcePath/dbr.ui.html","function"==typeof SuppressedError&&SuppressedError; /*! * Dynamsoft JavaScript Library * @product Dynamsoft Camera Enhancer JS Edition * @website https://www.dynamsoft.com - * @copyright Copyright 2023, Dynamsoft Corporation + * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft - * @version 3.3.9 (js 20231205) + * @version 3.3.10 (js 20240130) * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest - */const U="undefined"==typeof self;let G,W,H,Y,X;if("undefined"!=typeof navigator&&(G=navigator,W=G.userAgent,H=G.platform,Y=G.mediaDevices),!U){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:G.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:H,search:"Win"},Mac:{str:H},Linux:{str:H}};let i="unknownBrowser",r=0,n="unknownOS";for(let t in e){const n=e[t]||{};let s=n.str||W,o=n.search||t,a=n.verStr||W,l=n.verSearch||t;if(l instanceof Array||(l=[l]),-1!=s.indexOf(o)){i=t;for(let e of l){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||W,s=i.search||e;if(-1!=r.indexOf(s)){n=e;break}}"Linux"==n&&-1!=W.indexOf("Windows NT")&&(n="HarmonyOS"),X={browser:i,version:r,OS:n}}U&&(X={browser:"ssr",version:0,OS:"ssr"});const z="undefined"!=typeof WebAssembly&&W&&!(/Safari/.test(W)&&!/Chrome/.test(W)&&/\(.+\s11_2_([2-6]).*\)/.test(W)),Z=!("undefined"==typeof Worker),J=!(!Y||!Y.getUserMedia),K=async()=>{let e=!1;if(J)try{(await Y.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===X.browser&&X.version>66||"Safari"===X.browser&&X.version>13||"OPR"===X.browser&&X.version>43||"Edge"===X.browser&&X.version;const q=(()=>{if(!U&&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,l=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,h=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),c=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),u=h/c,d=a/l,f=this._drawingLayer._getObjectFit();let g,_,p,m,v=1;if("contain"===f)u0?i-1:r,te),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 V.Control({positionHandler:$,actionHandler:ie(r>0?r-1:i,te),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=V.util.transformPoint({x:r,y:n},t.calcTransformMatrix());e.push({x:s.x,y:s.y})}return e}}}const ne=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"===h?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}},V.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();V.util.addListener(V.document,"touchend",this._onTouchEnd,{passive:!1}),V.util.addListener(V.document,"touchmove",this._onMouseMove,{passive:!1}),V.util.removeListener(i,r+"down",this._onMouseDown)},V.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,l=[],h=[],c=a?V.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?(l.push(h),h=[],o=g,m=!0):o+=v,m||a||h.push(f),h=h.concat(u),_=a?0:this._measureWord([f],t,d),d++,m=!1,g>p&&(p=g);return y&&l.push(h),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),l});class oe{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 V.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 oe(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 le{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 ce;!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"}(ce||(ce={}));const ue=(e,t,i,r)=>{if(!i)return e;let n=t+Math.round((e-t)/i)*i;return r&&(n=Math.min(n,r)),n};class de{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._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameInputContainer=null,this._clickIptSingleFrameMode=()=>{if(!this._isSingleFrameModeEnabled())return;if(this.getDrawingLayers().some((e=>"editor"==e.getMode())))return;let e;if(this._singleFrameInputContainer)e=this._singleFrameInputContainer.firstElementChild;else{e=document.createElement("input"),e.setAttribute("type","file"),"camera"===this.singleFrameMode?(e.setAttribute("capture",""),e.setAttribute("accept","image/*")):1!=this.singleFrameMode&&"image"!==this.singleFrameMode||(e.removeAttribute("capture"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),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()),l={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},h=this._getImageData(e,r,n,s,null,{pixelFormat:a});if(!h)return null;const c=Date.now();return de._onLog&&de._onLog("DCE: _getVideoData(region?) END: "+c),l.data=h.data,l.pixelFormat=l.colorMode=h.pixelFormat,l._bUseWebGL=h._bUseWebGL,l.timeSpent=c-t,l.timeStamp=c,h.pixelFormat===ce.GREY?l.stride=l.width:l.stride=4*l.width,l};(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="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent";const t=document.createElement("div");t.append(e),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.pointerEvents="none",this._elContainer.prepend(t),this._singleFrameInputContainer=t}null==e||e.click()},this.styleEls=[],this._framePixelFormat=void 0,this._defaultFramePixelFormat="rgba",this.mapPixelFormatString_Enum=new Map([["grey",ce.GREY],["grey32",ce.GREY32],["rgba",ce.RGBA],["rbga",ce.RBGA],["grba",ce.GRBA],["gbra",ce.GBRA],["brga",ce.BRGA],["bgra",ce.BGRA]]),this.shaderPixelFormat=ce.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._isSingleFrameModeEnabled())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,l=this._elContainer.getBoundingClientRect(),h=l.left,c=l.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-h)/p,n=(i-c-(f-d/_)/2)/p):(p=f/a,n=(i-c)/p,r=(t-h-(d-f*_)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");_>g?(p=f/a,n=(i-c)/p,r=(t-h+(f*_-d)/2)/p):(p=d/o,r=(t-h)/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.cameraOpenTimeout=4e3,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._isSingleFrameModeEnabled())if("visible"===document.visibilityState){if(de._onLog&&de._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];if(this._video.srcObject.active&&e)if(e.muted&&["iPhone","iPad","Mac"].includes(X.OS)){if(X.version>=17)return;this.play()}else this._video.play();else this.play()}}else if("hidden"===document.visibilityState)if(de._onLog&&de._onLog("DCE: document hidden."),["iPhone","iPad","Mac"].includes(X.OS)){if(this._vc_bPlayingVideoBeforeHide=!0,X.version>=17)return;this._video&&this._video.pause()}else 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._windowResizeListener=()=>{this._windowWidth!==document.documentElement.clientWidth&&(this._windowWidth=document.documentElement.clientWidth,this._updateLayers())},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null,navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this._singleFrameMode=!1:this._singleFrameMode=!0}static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:z,worker:Z,getUserMedia:J,camera:await K(),browser:X.browser,version:X.version,OS:X.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");de._engineResourcePath=(e=>{if(null==e&&(e="./"),!U){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){de._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=de._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",de.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(){var e,t;let i,r,n;if(this._isSingleFrameModeEnabled()?(i=this._imgWidth,r=this._imgHeight,n="contain"):(i=null===(e=this._video)||void 0===e?void 0:e.videoWidth,r=null===(t=this._video)||void 0===t?void 0:t.videoHeight,n=this.getVideoFit()),!i||!r)throw new Error("Invalid content dimensions.");return{width:i,height:r,objectFit:n}}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;let t;try{t=this._calculateCvsSize()}catch(e){if("Invalid content dimensions."===(e.message||e))return;throw e}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,l=o.dHeight;e.width==a&&e.height==l||(e.width=a,e.height=l);const h=window.getComputedStyle(this._elContainer),c=parseFloat(h.width),u=parseFloat(h.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._isSingleFrameModeEnabled())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);if(!i)return;const 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,l=this._decoratorArea.width/100*r,h=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(l),Math.round(h)),s.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),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(l+s.lineWidth),Math.round(h+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(l),Math.round(h)),s.fillStyle=this._viewDecoratorInfo.focus.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),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 de;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,de.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{de.onWarning&&de.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((()=>{de.onWarning&&de.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 ae,t}static async playVideo(e,t,i){if(!e)throw new Error("Invalid 'videoEl'.");if(!t)throw new Error("Invalid 'source'.");return"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,new Promise(((t,r)=>{let n;const s=()=>{e.removeEventListener("loadstart",l),e.removeEventListener("abort",h),e.removeEventListener("play",c),e.removeEventListener("error",u)},o=()=>{n&&clearTimeout(n),s(),t(e)},a=e=>{n&&clearTimeout(n),s(),r(e)},l=()=>{e.addEventListener("abort",h,{once:!0})},h=()=>{const e=new Error("Video playing was interrupted.");e.name="AbortError",a(e)},c=()=>{o()},u=()=>{a(new Error(`Video error ${e.error.code}: ${e.error.message}.`))};e.addEventListener("loadstart",l,{once:!0}),e.autoplay?(e.addEventListener("play",c,{once:!0}),e.addEventListener("error",u,{once:!0})):(e.load(),e.play().then((()=>{o()})).catch((e=>{a(e)}))),i&&(n=setTimeout((()=>{s(),r(new Error("Failed to play video. Timeout."))}),i))}))}static findBestRearCameraInIOS(e){if(!e||!e.length)return null;const t=["back","baksidan","bakre","bak","後置","后置","背面","خلفية","задна","posteriore","posterior","zadní","bagside","rück","πίσω","trasera","taka","arrière","אחורית","बैक","stražnja","hátsó","belakang","aртқы","후면","achterzijde","tylny","traseira","spate","задняя","задней","zadná","านหลัง","arka","sau"],i=["triple","三镜头","三鏡頭","トリプル","ثلاثية","тройна","trojný","τριπλή","kolmois","משולשת","ट्रिपल","trostruka","tiga","tripla","үштік","트리플","trippelt","trippel","trójobiektywowy","triplă","тройная","trojitá","สาม","üçlü","потроєна","ba camera"],r=["dual wide","dual-weitwinkel","dual con gran angular","dual","doble","double","双广角","雙廣角","デュアル広角","مزدوجة عريضة","двойна широкоъгълна","duální širokoúhlý","διπλή ευρεία","laajakulmainen kaksois","כפולה רחבה","ड्युअल वाइड","dvostruka široka","kettős, széles látószögű","ganda","doppia con grandangolo","қос кең бұрышты","듀얼 와이드","dwikamera","dobbelt vidvinkelkamera","dwuobiektywowy","dupla grande-angular","grande angular dupla","dublă","двойная широкоугольная","duálna širokouhlá","dubbel vidvinkel","คู่ด้านหลังมุมกว้าง","çift geniş","здвоєна ширококутна","kép rộng mặt sau"],n=e.filter((e=>{const i=e.label.toLowerCase();return t.some((e=>i.includes(e)))}));if(!n.length)return null;const s=n.find((e=>{const t=e.label.toLowerCase();return i.some((e=>t.includes(e)))}));if(s)return s.deviceId;const o=n.find((e=>{const t=e.label.toLowerCase();return r.some((e=>t.includes(e)))}));return o?o.deviceId:n[0].deviceId}static findBestRearCamera(e){if(!e||!e.length)return null;if(["iPhone","iPad","Mac"].includes(X.OS))return de.findBestRearCameraInIOS(e);const t=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","posterior","后面","後面","背面","后置","後置","背置","задней","خلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","taka","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक","задна","aртқы","задняя","bakre","านหลัง"];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(X.OS)?e[e.length-1].deviceId:null}_isSingleFrameModeEnabled(){return 0!=this.singleFrameMode}async play(e,t,i,r){let n;if(this._video&&this.videoSrc){de._onLog&&(n=Date.now(),de._onLog("DCE: start loading static video: "+n));const e=await de.playVideo(this._video,this.videoSrc,this.cameraOpenTimeout);if(de._onLog&&de._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._isSingleFrameModeEnabled())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 n;try{this._video&&this._video.srcObject&&this.stop(),de._onLog&&de._onLog("DCE: ======before video========");const s=()=>{if(!this._video)throw l&&l.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},o=this.getVideoSettings();let a,l;if("boolean"==typeof o.video&&(o.video={}),e)delete o.video.facingMode,o.video.deviceId={exact:e};else if(o.video.deviceId);else if(this._lastDeviceId)delete o.video.facingMode,o.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&de.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete o.video.facingMode,o.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&&(o.video.width=e,o.video.height=t)}else if(this.ifSkipCameraInspection);else if(o.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=o.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){a=!0;const e=de.findBestRearCamera(this._allCameras);e&&(delete o.video.facingMode,o.video.deviceId={exact:e})}}t&&(o.video.width={ideal:t}),i&&(o.video.height={ideal:i}),de._onLog&&de._onLog("DCE: ======try getUserMedia========");let h=[0,500],c=null;const u=async e=>{for(let t of h){t&&await new Promise((e=>setTimeout(e,t))),s();try{de._onLog&&de._onLog("DCE: ask "+JSON.stringify(e)),l=await navigator.mediaDevices.getUserMedia(e);break}catch(e){if(s(),"NotFoundError"===e.name||"NotAllowedError"===e.name)throw e;c=e,de._onLog&&de._onLog("DCE: "+e.message||e)}}s()};let d;if(await u(o),l||(de._onLog&&de._onLog("DCE: ======try getUserMedia again========"),d=JSON.parse(JSON.stringify(o)),"object"==typeof d.video&&(["iPhone","iPad"].includes(X.OS)?(t>=1280||i>=1280?d.video.width=1280:t>=640||i>=640?d.video.width=640:(t<640||i<640)&&(d.video.width=320),delete d.video.height):a&&!o.video.deviceId?(delete d.video.facingMode,this._allCameras.length&&(d.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):d.video=!0),de._onLog&&de._onLog("DCE: "+d),await u(d)),l||(h=[1e3,2e3],await u(o)),l||await u(d),!l)throw c;const f=()=>{const e=l.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),s(),a&&!this.ifSkipCameraInspection){f();const e=de.findBestRearCamera(this._allCameras),t=null===(n=this._currentCamera)||void 0===n?void 0:n.deviceId;e&&e!=t&&(l.getTracks().forEach((e=>{e.stop()})),h=[0,500,1e3,2e3],o.video.deviceId={exact:e},await u(o))}de._onLog&&de._onLog("DCE: ======play video========"),s(),await de.playVideo(this._video,l,this.cameraOpenTimeout),s(),de._onLog&&de._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const g="got "+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=g,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),de._onLog&&de._onLog("DCE: got "+g),f(),this._renderSelCameraInfo();const _={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(_.deviceId&&(this._lastDeviceId=_.deviceId,this.ifSaveLastUsedCamera&&de.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),o.video.width&&o.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(o.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(o.video.height))))),!r||!r.notTriggerPlayedEvent){const e=this.mapCameraEvents.get("played");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(_));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return this.promisePlay=null,_}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}})(),de._onLog&&(n=Date.now(),de._onLog("DCE: start opening camera: "+n));const o=await this.promisePlay;return de._onLog&&de._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()}isPaused(){var e;return!this._isSingleFrameModeEnabled()&&!0===(null===(e=this._video)||void 0===e?void 0:e.paused)}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t=17&&e.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),this._video=e;const i=document.createElement("div");i.append(e),i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.width="100%",i.style.height="100%",i.style.overflow="hidden",this._videoContainer=i,t.prepend(i)}else!this._divScanArea&&t.classList.contains("dce-scanarea")?this._divScanArea=t:!this._divScanLight&&t.classList.contains("dce-scanlight")?this._divScanLight=t:!this._bgLoading&&t.classList.contains("dce-bg-loading")?this._bgLoading=t:!this._bgCamera&&t.classList.contains("dce-bg-camera")?this._bgCamera=t:!this._selCam&&t.classList.contains("dce-sel-camera")?this._selCam=t:!this._selRsl&&t.classList.contains("dce-sel-resolution")?(this._selRsl=t,this.videoSrc||this._isSingleFrameModeEnabled()||this._selRsl.options.length||(this._selRsl.innerHTML=[this._optGotRsl?"":'','','',''].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._isSingleFrameModeEnabled()||this.videoSrc?(this._isSingleFrameModeEnabled()&&(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(X.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)),this._windowWidth=document.documentElement.clientWidth,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){this._isSingleFrameModeEnabled()?(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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=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._windowResizeListener)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}async open(e){this.UIElement||await this.setUIElement(de.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._isSingleFrameModeEnabled()&&(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&&(de._onLog&&de._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&&(de._onLog&&de._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){var t,i;let r="";const n=(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},s=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 o=null===(i=null===(t=this.videoSettings)||void 0===t?void 0:t.video)||void 0===i?void 0:i.deviceId;if(!o)return null;if(r=o.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:o.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!r)return null;let a=this._mapCameraResolutions.get(r);if(a&&!e)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),a=this._mapCameraResolutions.get(r);for(let e of this._predefinedResolutions){const t=await s(r,e.width,e.height);t&&!n(r,t)&&a.push([t.width,t.height])}return a}if(this._currentCamera){r=this._currentCamera.deviceId;let t=this._mapCameraResolutions.get(r);if(t&&!e)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),t=this._mapCameraResolutions.get(r);let i=this._videoTrack;for(let e of this._predefinedResolutions){await i.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const s=i.getSettings(),o={width:s.width,height:s.height};n(r,o)||t.push([o.width,o.height])}return this._video.srcObject.getTracks().forEach((e=>{e.stop()})),await this.play(r,null,null,{notTriggerPlayedEvent:!0}),t}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._isSingleFrameModeEnabled())throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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=ue(e,t.min,t.step,t.max),await this._videoTrack.applyConstraints({advanced:[{zoom:e}]}),e}_getHardwareScale(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(e,t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(e,t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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=ue(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._isSingleFrameModeEnabled())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=ue(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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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=ue(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 l=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:n,sy:s,sWidth:o,sHeight:a,dWidth:o,dHeight:a},null,{pixelFormat:ce.RGBA});if(!l)return this._setFocusAndGetContract(e,t);const h=l.data;let c=0;for(let e=0,t=h.length-8;eo&&oc)return await this._doFocusDetail(e,s,o,r,n,h,c)}else{let a=await this._setFocusAndGetContract(e,h);if(o>a)return await this._doFocusDetail(e,s,o,r,n,h,a);if(o==a)return await this._doFocusDetail(e,s,o,h,a);let c=await this._setFocusAndGetContract(e,l);if(c>o&&o{try{(null==t||tthis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=ue(Math.sqrt(i*(t||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=ue(Math.sqrt((t||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=ue(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),l=await this._setFocusAndGetContract(e,r);if(a>l&&lo&&a>o){let t=await this._setFocusAndGetContract(e,i);const n=await this._doFocusDetail(e,r,l,i,t,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==l&&ll){const t=await this._doFocusDetail(e,r,l,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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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=h*(1-1/e)*(i/2-this._scaleCenter.x),u=h*(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,l=e,h=t;const c={regionLeft:0,regionTop:0,regionRight:l,regionBottom:h,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*l/100,c.regionTop=i.regionTop*h/100,c.regionRight=i.regionRight*l/100,c.regionBottom=i.regionBottom*h/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),l=Math.round(c.regionRight-c.regionLeft),h=Math.round(c.regionBottom-c.regionTop)):(n=0,s=0,l=Math.round(l),h=Math.round(h));const u=Math.max(l,h);if(r&&r>0&&u>r){const e=r/u;l>h?(o=r,a=Math.round(h*e)):(o=Math.round(l*e),a=r)}else o=l,a=h;return o<=0||a<=0?null:{sx:n,sy:s,sWidth:l,sHeight:h,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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;de._onLog&&(a=Date.now(),de._onLog("DCE: _drawImage(), START: "+a));let l=0,h=0,c=i,u=r,d=0,f=0,g=i,_=r;n&&(n.sx&&(l=Math.round(n.sx)),n.sy&&(h=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=ce.RGBA;o&&o.pixelFormat&&(p=o.pixelFormat);const m=e;if(!o||!o.bUseWebGL){de._onLog&&de._onLog("DCE: _drawImage() in context2d."),m.ctx2d||(m.ctx2d=m.getContext("2d",{willReadFrequently:!0}));const e=m.ctx2d;if(!e)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(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 `,l=r(e,[n(e,e.VERTEX_SHADER,s),n(e,e.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:l,attribLocations:{vertexPosition:e.getAttribLocation(l,"a_position"),texPosition:e.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:e.getUniformLocation(l,"u_image"),uColorFactor:e.getUniformLocation(l,"uColorFactor"),uMatrix:e.getUniformLocation(l,"u_matrix"),uTextureMatrix:e.getUniformLocation(l,"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,[ce.GREY,ce.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(),l/i,h/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;de._onLog&&(o=Date.now(),de._onLog("DCE: _getImageData(), START: "+o));const a=Math.round(r.sx),l=Math.round(r.sy),h=Math.round(r.sWidth),c=Math.round(r.sHeight),u=Math.round(r.dWidth),d=Math.round(r.dHeight);let f=ce.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(de._onLog&&de._onLog("DCE: _getImageData() in WebGL."),n)if(f===ce.GREY){if(p=new Uint8Array(u*d*4),_=this._drawImage(g,e,t,i,{sx:a,sy:l,sWidth:h,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=()=>{de._onLog&&de._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(de._onLog&&de._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t),de._onLog&&de._onLog("DCE: finish fetching a frame into buffer: "+Date.now());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()?(de._onLog&&de._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):0===this.refreshInterval&&t()),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._isSingleFrameModeEnabled())throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,de._onLog&&de._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(de._onLog&&de._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 se(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 le(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._isSingleFrameModeEnabled()&&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)}transformCoord(e){if(!this.isOpen())throw new Error("Unavailable when the camera is not open.");if(this._isSingleFrameModeEnabled()&&!this._cvsSingleFrameMode)throw new Error("No image is selected. ");const t=this._elContainer.getBoundingClientRect();let i,r,n,s,o,a=t.left,l=t.top,h=a+window.scrollX,c=l+window.scrollY;this._isSingleFrameModeEnabled()?(i=this._cvsSingleFrameMode.width,r=this._cvsSingleFrameMode.height,n=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).width),s=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,r=this.video.videoHeight,n=parseFloat(window.getComputedStyle(this._elContainer).width),s=parseFloat(window.getComputedStyle(this._elContainer).height),o=this.videoFit);const u=n/s,d=i/r;let f,g,_,p,m=1;if("contain"===o)u({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 V.Control({positionHandler:$,actionHandler:ie(i>0?i-1:r,te),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=V.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 V.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 ge(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 _e(e){return Math.abs(e)<1e-6?0:e<0?-1:1}function pe(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))}var me,ve,ye,Se,be,we,Ce,xe,Te,Ee,Ie,Oe,Ae,Re,De,Me,Fe,Le,Pe,ke,Be,Ne,je,Ve,Ue,Ge,We,He;class Ye extends P{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._onPlayed=null}static set _onLog(e){!function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?n.call(e,i):n?n.value=i:t.set(e,i)}(Ye,me,e,"f",ve),de._onLog=e}static get _onLog(){return function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)}(Ye,me,"f",ve)}static get version(){return this._version+`(DCE ${de.getVersion()})`}static _fireHTTPSWarnning(){Ye.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{Ye.onWarning&&Ye.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return de.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){if("boolean"!=typeof e&&!["image","camera"].includes(e))throw new Error("Invalid value.");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||(P._onLog&&P._onLog("createDCEInstance()"),de.defaultUIElementURL=null,this.dce=await de.createInstance(),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=fe,["iPhone","iPad","Android","HarmonyOS"].includes(P.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:l,pixelFormat:h,timeStamp:c,_sWidth:u,_sHeight:d}=t,f={timeStamp:c};if("grey"===h)i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_GrayScaled,0,f);else if("rgba"===h)i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_ABGR_8888,0,f);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_ARGB_8888,0,f)}if(await this.clearMapDecodeRecord(),P.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){const t=new Ye;t._instanceID=await Ye.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(Ye.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),Ye._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(!P._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=P._nextTaskID++;P._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)}})),P._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 P._onLog&&P._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));P._onLog&&P._onLog("======= once read ======="),P._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return P._onLog&&P._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:l,pixelFormat:h,timeStamp:c,_sWidth:u,_sHeight:d}=t,f={timeStamp:c};if("grey"===h)i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_GrayScaled,0,f);else if("rgba"===h)i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_ABGR_8888,0,f);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_ARGB_8888,0,f)}if(P.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=async()=>new Promise(((e,t)=>{let i=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!1}})})),i=await t(),r=(e,t,i,r,n,s,o)=>{let a=s/r,l=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/l+i,e.y2=e.y2/l+i,e.y3=e.y3/l+i,e.y4=e.y4/l+i},l=t=>{if(!t)return null;const i={};let l,h,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!=_e(a.y-i)>0&&_e(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)=>!!(pe([e[0],e[1]],[e[2],e[3]],[t.x1,t.y1],[t.x2,t.y2])||pe([e[0],e[1]],[e[2],e[3]],[t.x2,t.y2],[t.x3,t.y3])||pe([e[0],e[1]],[e[2],e[3]],[t.x3,t.y3],[t.x4,t.y4])||pe([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 i of t){if(i.resultType!==e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE)continue;const t=i.scaleDownRatio;for(let e of i.results){if(!e)continue;const i={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};r(i,n,s,u,d,o,a),_(g,i)&&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 i=h.x1/u,l=(u-h.x3)/u,c=h.y1/d,f=(d-h.y3)/d;if(i>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-i),(.5-t)/(.5-l),(.5-t)/(.5-c),(.5-t)/(.5-f)].filter((e=>e>0)),r=Math.min(...e,this.autoZoomInIdealModuleSize/h.result.moduleSize),n=this.dce.getZoomSettings().factor;let s=Math.max(Math.pow(n*r,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);s=Math.min(s,r);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){r(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-i),(.5-t)/(.5-l),(.5-t)/(.5-c),(.5-t)/(.5-f)].filter((e=>e>0));let r=Math.min(...e)*this.dce.getZoomSettings().factor;await this.setZoom({factor:r}),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{r(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(P._onLog&&P._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,P._onLog&&P._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&&(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){P._onLog&&P._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 P._onLog&&P._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._drawResults(null),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()}convertToPageCoordinates(e){return this.dce.convertToPageCoordinates(e)}convertToClientCoordinates(e){return this.dce.convertToClientCoordinates(e)}destroyContext(){this.close(),this.dce&&this.dce.dispose(!1),this.bDestroyed||super.destroyContext()}}me=Ye,ve={value:void 0},e.EnumBarcodeColourMode=void 0,(ye=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[ye.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",ye[ye.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",ye[ye.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",ye[ye.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",ye[ye.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",ye[ye.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",ye[ye.BICM_SKIP=0]="BICM_SKIP",ye[ye.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(Se=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[Se.BCM_AUTO=1]="BCM_AUTO",Se[Se.BCM_GENERAL=2]="BCM_GENERAL",Se[Se.BCM_SKIP=0]="BCM_SKIP",Se[Se.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(be=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[be.BF2_NULL=0]="BF2_NULL",be[be.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",be[be.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",be[be.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",be[be.BF2_POSTNET=2097152]="BF2_POSTNET",be[be.BF2_PLANET=4194304]="BF2_PLANET",be[be.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",be[be.BF2_RM4SCC=16777216]="BF2_RM4SCC",be[be.BF2_DOTCODE=2]="BF2_DOTCODE",be[be.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",be[be.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",be[be.BF2_PHARMACODE=12]="BF2_PHARMACODE",be[be.BF2_ALL=-1]="BF2_ALL",e.EnumBinarizationMode=void 0,(we=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[we.BM_AUTO=1]="BM_AUTO",we[we.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",we[we.BM_SKIP=0]="BM_SKIP",we[we.BM_THRESHOLD=4]="BM_THRESHOLD",we[we.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(Ce=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[Ce.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(xe=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[xe.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(Te=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[Te.CCM_AUTO=1]="CCM_AUTO",Te[Te.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",Te[Te.CCM_SKIP=0]="CCM_SKIP",Te[Te.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(Ee=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[Ee.CICM_GENERAL=1]="CICM_GENERAL",Ee[Ee.CICM_SKIP=0]="CICM_SKIP",Ee[Ee.CICM_REV=2147483648]="CICM_REV",e.EnumConflictMode=void 0,(Ie=e.EnumConflictMode||(e.EnumConflictMode={}))[Ie.CM_IGNORE=1]="CM_IGNORE",Ie[Ie.CM_OVERWRITE=2]="CM_OVERWRITE",e.EnumDeblurMode=void 0,(Oe=e.EnumDeblurMode||(e.EnumDeblurMode={}))[Oe.DM_SKIP=0]="DM_SKIP",Oe[Oe.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",Oe[Oe.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",Oe[Oe.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",Oe[Oe.DM_SMOOTHING=8]="DM_SMOOTHING",Oe[Oe.DM_MORPHING=16]="DM_MORPHING",Oe[Oe.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",Oe[Oe.DM_SHARPENING=64]="DM_SHARPENING",Oe[Oe.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",Oe[Oe.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(Ae=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[Ae.DRM_AUTO=1]="DRM_AUTO",Ae[Ae.DRM_GENERAL=2]="DRM_GENERAL",Ae[Ae.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",Ae[Ae.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",Ae[Ae.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",Ae[Ae.DRM_SKIP=0]="DRM_SKIP",Ae[Ae.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(Re=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[Re.DPMCRM_AUTO=1]="DPMCRM_AUTO",Re[Re.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",Re[Re.DPMCRM_SKIP=0]="DPMCRM_SKIP",Re[Re.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(De=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[De.GTM_INVERTED=1]="GTM_INVERTED",De[De.GTM_ORIGINAL=2]="GTM_ORIGINAL",De[De.GTM_SKIP=0]="GTM_SKIP",De[De.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(Me=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[Me.IPM_AUTO=1]="IPM_AUTO",Me[Me.IPM_GENERAL=2]="IPM_GENERAL",Me[Me.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",Me[Me.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",Me[Me.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",Me[Me.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",Me[Me.IPM_SKIP=0]="IPM_SKIP",Me[Me.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(Fe=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[Fe.IRSM_MEMORY=1]="IRSM_MEMORY",Fe[Fe.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",Fe[Fe.IRSM_BOTH=4]="IRSM_BOTH",e.EnumLocalizationMode=void 0,(Le=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[Le.LM_SKIP=0]="LM_SKIP",Le[Le.LM_AUTO=1]="LM_AUTO",Le[Le.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",Le[Le.LM_LINES=8]="LM_LINES",Le[Le.LM_STATISTICS=4]="LM_STATISTICS",Le[Le.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",Le[Le.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",Le[Le.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",Le[Le.LM_CENTRE=128]="LM_CENTRE",Le[Le.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",Le[Le.LM_REV=2147483648]="LM_REV",e.EnumPDFReadingMode=void 0,(Pe=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[Pe.PDFRM_RASTER=1]="PDFRM_RASTER",Pe[Pe.PDFRM_AUTO=2]="PDFRM_AUTO",Pe[Pe.PDFRM_VECTOR=4]="PDFRM_VECTOR",Pe[Pe.PDFRM_REV=2147483648]="PDFRM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,(ke=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[ke.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",ke[ke.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",ke[ke.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",ke[ke.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,(Be=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[Be.RPM_AUTO=1]="RPM_AUTO",Be[Be.RPM_GENERAL=2]="RPM_GENERAL",Be[Be.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",Be[Be.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",Be[Be.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",Be[Be.RPM_SKIP=0]="RPM_SKIP",Be[Be.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(Ne=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[Ne.RCT_PIXEL=1]="RCT_PIXEL",Ne[Ne.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,(je=e.EnumResultType||(e.EnumResultType={}))[je.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",je[je.RT_RAW_TEXT=1]="RT_RAW_TEXT",je[je.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",je[je.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(Ve=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[Ve.SUM_AUTO=1]="SUM_AUTO",Ve[Ve.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",Ve[Ve.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",Ve[Ve.SUM_SKIP=0]="SUM_SKIP",Ve[Ve.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(Ue=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[Ue.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",Ue[Ue.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",Ue[Ue.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",Ue[Ue.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",Ue[Ue.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",Ue[Ue.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(Ge=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[Ge.TFM_AUTO=1]="TFM_AUTO",Ge[Ge.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",Ge[Ge.TFM_SKIP=0]="TFM_SKIP",Ge[Ge.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(We=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[We.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",We[We.TROM_POSITION=2]="TROM_POSITION",We[We.TROM_FORMAT=4]="TROM_FORMAT",We[We.TROM_SKIP=0]="TROM_SKIP",We[We.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(He=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[He.TDM_AUTO=1]="TDM_AUTO",He[He.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",He[He.TDM_SKIP=0]="TDM_SKIP",He[He.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=P,e.BarcodeScanner=Ye,Object.defineProperty(e,"__esModule",{value:!0})})); + */ +const k="undefined"==typeof self;let B,N,j,V,U;if("undefined"!=typeof navigator&&(B=navigator,N=B.userAgent,j=B.platform,V=B.mediaDevices),!k){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:B.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:j,search:"Win"},Mac:{str:j},Linux:{str:j}};let i="unknownBrowser",r=0,n="unknownOS";for(let t in e){const n=e[t]||{};let s=n.str||N,o=n.search||t,a=n.verStr||N,l=n.verSearch||t;if(l instanceof Array||(l=[l]),-1!=s.indexOf(o)){i=t;for(let e of l){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||N,s=i.search||e;if(-1!=r.indexOf(s)){n=e;break}}"Linux"==n&&-1!=N.indexOf("Windows NT")&&(n="HarmonyOS"),U={browser:i,version:r,OS:n}}k&&(U={browser:"ssr",version:0,OS:"ssr"});const G="undefined"!=typeof WebAssembly&&N&&!(/Safari/.test(N)&&!/Chrome/.test(N)&&/\(.+\s11_2_([2-6]).*\)/.test(N)),W=!("undefined"==typeof Worker),H=!(!V||!V.getUserMedia),Y=async()=>{let e=!1;if(H)try{(await V.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===U.browser&&U.version>66||"Safari"===U.browser&&U.version>13||"OPR"===U.browser&&U.version>43||"Edge"===U.browser&&U.version;const X=(()=>{if(!k&&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"./"})();var z={653:(e,t,i)=>{var r,n,s,o,a,l,h,c,u,d,f,g,_,p,m,v,y,S,b,w,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 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 l=new ImageData(a,r,n);i.putImageData(l,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,l=Math.PI/2,x.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/l){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/l){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,l){var h,c,u=new x.Point(a.x,a.y);0===l?(c=e[l+1],h=i?o(x.util.createVector(c,u)).addEquals(u):e[e.length-1]):l===e.length-1?(h=e[l-1],c=i?o(x.util.createVector(h,u)).addEquals(u):e[0]):(h=e[l-1],c=e[l+1]);var d,f,g=x.util.getBisector(u,h,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],l=i[4],h=i[5],c=function(e,t,i,s,o,a,l){var h=Math.PI,c=l*h/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=_*_,b=m*v-m*y-v*S,w=0;if(b<0){var C=Math.sqrt(1-b/(m*v));i*=C,s*=C}else w=(o===a?-1:1)*Math.sqrt(b/(m*y+v*S));var T=w*i*p/s,E=-w*s*_/i,I=d*T-u*E+.5*e,O=u*T+d*E+.5*t,A=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*h:1===a&&R<0&&(R+=2*h);for(var D=Math.ceil(Math.abs(R/h*2)),M=[],L=R/D,F=8/3*Math.sin(L/4)*Math.sin(L/4)/Math.sin(L/2),P=A+L,k=0;kw)for(var T=1,E=_.length;T2;for(t=t||0,h&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,l=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+l*t]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(t,i,r,n,s,o,a,l){var h;if(x.cachesBoundsOfCurve&&(h=e.call(arguments),x.boundsOfCurveCache[h]))return x.boundsOfCurveCache[h];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,b=Math.abs,w=[],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*l,d=3*n-3*i),b(c)<1e-12){if(b(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,O,A=w.length,R=A;A--;)E=(O=1-(f=w[A]))*O*O*t+3*O*O*f*r+3*O*f*f*s+f*f*f*a,C[0][A]=E,I=O*O*O*i+3*O*O*f*n+3*O*f*f*o+f*f*f*l,C[1][A]=I;C[0][R]=t,C[1][R]=i,C[0][R+1]=a,C[1][R+1]=l;var D=[{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[h]=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=l(s),n=s,(r=o(h.x,h.y,i.x,i.y))+a>t?(s-=c,c/=2):(h=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 l=0,h=o.length;l-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},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var h in l)o[l[h]]+=parseInt(t(e,h),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,l=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,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(s),a((function(e){var t,h=e||+new Date,c=i.duration||500,u=h+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-h,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),b=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=b,s.durationRate=n,!o){if(!f(S,b,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 l()):(d(S,b,n),void a(e));l()}}(h)})),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,l=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(l){if(Array.isArray(t))return l(e(t,t,0),i,r);l(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=l?i.map(s):s(i,n)}}else i="";return!l&&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;)l.shift(),h=t.util.multiplyTransformMatrices(h,l[0]);return h}}();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,l,h=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=!h||!(h=h.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,b={},w="",C=0,x=0;if(b.width=0,b.height=0,b.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 b;if(m)return b.width=s(d),b.height=s(f),b;if(i=-parseFloat(h[1]),r=-parseFloat(h[2]),n=parseFloat(h[3]),o=parseFloat(h[4]),b.minX=i,b.minY=r,b.viewBoxWidth=n,b.viewBoxHeight=o,y?(b.width=n,b.height=o):(b.width=s(d),b.height=s(f),c=b.width/n,u=b.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=b.width-n*c,x=b.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 b;if((g||_)&&"#document"!==e.parentNode.nodeName&&(w=" translate("+s(g)+" "+s(_)+") "),a=w+" matrix("+c+" 0 0 "+u+" "+(i*c+C)+" "+(r*u+x)+") ","svg"===e.nodeName){for(l=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)l.appendChild(e.firstChild);e.appendChild(l)}else(l=e).removeAttribute("x"),l.removeAttribute("y"),a=l.getAttribute("transform")+a;return l.setAttribute("transform",a),b}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),l=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),h=(s.y-n.y)*(r.x-e.x)-(s.x-n.x)*(r.y-e.y);if(0!==h){var c=a/h,u=l/h;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===l?"Coincident":"Parallel");return o},t.Intersection.intersectLinePolygon=function(e,t,r){var n,s,o,a,l=new i,h=r.length;for(a=0;a0&&(l.status="Intersection"),l},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),l=new t.Point(s.x,o.y),h=i.intersectLinePolygon(s,a,e),c=i.intersectLinePolygon(a,o,e),u=i.intersectLinePolygon(o,l,e),d=i.intersectLinePolygon(l,s,e),f=new i;return f.appendPoints(h.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]),l=t.util.array.min([e,i,r]);if(o=(a+l)/2,a===l)n=s=0;else{var h=a-l;switch(s=o>.5?h/(2-a-l):h/(a+l),a){case e:n=(i-r)/h+(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===h&&e.originY===h}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),l=e(t,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),l}}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 b(e,i,r,n,s){var o=e.target,a=o.controls[e.corner],l=o.canvas.getZoom(),h=o.padding/l,c=o.toLocalPoint(new t.Point(n,s),i,r);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=a.offsetX,c.y-=a.offsetY,c}function w(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,h=t.target,c=h._getTransformedDimensions(0,h.skewY),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=h.skewX;f<2?n=0:(n=u(Math.atan2(f/h.scaleX,c.y/h.scaleY)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().y;h.set("skewX",n),C(h,"skewY","scaleY","y",p)}return _}function T(e,t,i,r){var n,h=t.target,c=h._getTransformedDimensions(h.skewX,0),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=h.skewY;f<2?n=0:(n=u(Math.atan2(f/h.scaleY,c.x/h.scaleX)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().x;h.set("skewY",n),C(h,"skewX","scaleX","x",p)}return _}function E(e,t,i,r,n){n=n||{};var s,o,a,l,h,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),w=m(f,y,S),C=t.gestureScale;if(w)return!1;if(C)o=t.scaleX*C,a=t.scaleY*C;else{if(s=b(t,t.originX,t.originY,i,r),h="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,t.signX||(t.signX=h),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==h||t.signY!==u))return!1;if(l=f._getTransformedDimensions(),S&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=t.original,E=x/(Math.abs(l.x*T.scaleX/f.scaleX)+Math.abs(l.y*T.scaleY/f.scaleY));o=T.scaleX*E,a=T.scaleY*E}else o=Math.abs(s.x*f.scaleX/l.x),a=Math.abs(s.y*f.scaleY/l.y);p(t)&&(o*=2,a*=2),t.signX!==h&&"y"!==y&&(t.originX=c[t.originX],o*=-1,t.signX=h),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.signY=u)}var I=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)),I!==f.scaleX||O!==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,l=Math.atan2(n.ey-o.y,n.ex-o.x),h=Math.atan2(r-o.y,i-o.x),c=u(h-l+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(l)&&(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=b(t,h,h,i,r).y>0?o:l:(c>0&&(n=u===s?o:l),c<0&&(n=u===s?l:o),w(a)&&(n=n===o?l: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,l=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),l&&n.set("top",o),(a||l)&&g("moving",v(e,t,i,r)),a||l},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=b,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,l=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,h=l?"stroke":"fill",c=!l&&(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[h](),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,l=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(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[h+"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,l,h,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),l=f*t.util.cos(_),h=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),o=l=f*t.util.cos(g),a=h=f*t.util.sin(g);return{tl:{x:r-h,y:n-l},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+h,y:n+l}}},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 l=o.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),s=l.length;s--;){var h=l[s].split(/\s*:\s*/),c=h[0].trim(),u=h[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),l=(i=i||{},t(this.colorStops,!0)),h=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(l.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(h)for((l=l.concat()).reverse(),r=0,n=l.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=l.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,l,h,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)),l=c.length;l--;)f.push(e(c[l],s));return h=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:h,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,l=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 l;if(e.style||(e.style={}),void 0===e.getContext)throw l;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,l="",h={},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",l,"","\n"].join("")),l},_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+h&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),h++;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,l=this._activeObject,h=0;if(e===l&&"activeSelection"===e.type)for(r=(a=l._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,l=this.viewportTransform;return e.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(l[0],l[1],l[2],l[3],l[4],l[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,l=this._getActionFromCorner(r,s,e,i),h=this._getOriginFromCorner(i,s),c=e[this.centeredKey],u={target:i,action:l,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:h.x,originY:h.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,l,c)&&(u.originX="center",u.originY="center"),u.original.originX=h.x,u.original.originY=h.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),l=Math.max(r.x,s.x),h=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(o,a,l-o,h-a)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,o+=c,a+=c,l-=c,h-=c,x.Object.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(o,a,l-o,h-a))},findTarget:function(e,t){if(!this.skipTargetFind){var r,n,s=this.getPointer(e,!0),o=this._activeObject,a=this.getActiveObjects(),l=i(e),h=a.length>1&&!t||1===a.length;if(this.targets=[],h&&o._findTargetCorner(s,l))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,l=o.height||0;a&&l||("top"in o&&"bottom"in o&&(l=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 h=this.getRetinaScaling();return 1!==h&&(n.x/=h,n.y/=h),r=0===a||0===l?{width:1,height:1}:{width:s.width/a,height:s.height/l},{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 l,h;if(t){if(l=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[l],u=c&&c.getMouseUpHandler(e,t,c);u&&u(e,i,(h=this.getPointer(e)).x,h.y)}t.isMoving=!1}if(i&&(i.target!==t||i.corner!==l)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(e,t,c);h=h||this.getPointer(e),f&&f(e,i,h.x,h.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)),l=new x.Point(y(r,s),y(n,o)),h=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((t=this._objects[u])&&t.selectable&&t.visible&&(h&&t.intersectsWithRect(a,l,!0)||t.isContainedWithinRect(a,l,!0)||h&&t.containsPoint(a,null,!0)||h&&t.containsPoint(l,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,l=this.viewportTransform,h=(l[4]-(t.left||0))*e,c=(l[5]-(t.top||0))*e,u=this.interactive,d=[a,0,0,a,h,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=l,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()),l=t.minCacheSideLimit,h=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=h!==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,b=h>y||c>S;v=b||(h<.9*y||c<.9*S)&&y>l&&S>l,b&&!a.capped&&(h>l||c>l)&&(p=.1*h,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(h+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=h,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(),l=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,l=t.util.multiplyTransformMatrices(a,l),r=t.util.qrDecompose(l),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,l=n.y/this.scaleY/o;s.width=a,s.height=l,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,l),r.lineTo(0,l),r.closePath(),r.translate(a/2,l/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 l,h,c,u,d=t.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+h)*o(l.scaleX),_.y=2*Math.round(o(g.offsetY)+h)*o(l.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,b={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,l=e.x,h=e.y;return"string"==typeof t?t=b[t]:t-=.5,"string"==typeof r?r=b[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(),l=e.x+s*a.x,h=e.y+o*a.y),new x.Point(l,h)},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?b[this.originX]:this.originX-.5,i="string"==typeof e?b[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()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=e.indexOf("COMMON_PARTS"),p=t.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+x.Object.__uid++,r='\n'+l.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,h,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)),l&&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;l--)if(n=a[l],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,l=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,-l/2,a,l),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 l={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(l.startValue,l.endValue,l.duration,l):x.util.animate(l)}}),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,l=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 l: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,l=.4477152502;e.beginPath(),e.moveTo(s+t,o),e.lineTo(s+r-t,o),a&&e.bezierCurveTo(s+r-l*t,o,s+r,o+l*i,s+r,o+i),e.lineTo(s+r,o+n-i),a&&e.bezierCurveTo(s+r,o+n-l*i,s+r-l*t,o+n,s+r-t,o+n),e.lineTo(s+t,o+n),a&&e.bezierCurveTo(s+l*t,o+n,s,o+n-l*i,s,o+n-i),e.lineTo(s,o+i),a&&e.bezierCurveTo(s,o+l*i,s+l*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,l=0,h=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_'+l+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,e=["\t\n'],this.fill=h}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,l=s.width,h=s.height;o.width=l,o.height=h,this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=n,x.filterBackend.applyFilters([e],s,l,h,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,l=a(this.cropX,0),h=a(this.cropY,0),c=t.naturalWidth||t.width,u=t.naturalHeight||t.height,d=l*i,f=h*r,g=o(n*i,c-d),_=o(s*r,u-f),p=-n/2,m=-s/2,v=o(n,c/i-l),y=o(s,u/r-h);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,l=0,h=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&&(l=e/2),"Max"===t.alignX&&(l=e),e=r-u/s,"Mid"===t.alignY&&(h=e/2),"Max"===t.alignY&&(h=e),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:l,cropY:h}}}),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 l,h,c={imageBuffer:a,destinationWidth:e,destinationHeight:t,targetCanvas:o};o.width=e,o.height=t,l=window.performance.now(),E.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),I.call(c,this.gl,c),h>window.performance.now()-l?(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 l={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},h=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,h),e.forEach((function(e){e&&e.applyTo(l)})),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)}(l),this.copyGLTo2D(a,l),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(l.sourceTexture),a.deleteTexture(l.targetTexture),a.deleteFramebuffer(h),n.getContext("2d").setTransform(1,0,0,1,0,0),l},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,l=this.matrix,h=this.colorsOnly;for(s=0;s=S||o<0||o>=y||(l=4*(a*y+o),h=p[f*m+d],t+=_[l]*h,i+=_[l+1]*h,r+=_[l+2]*h,C||(n+=_[l+3]*h));w[s]=t,w[s+1]=i,w[s+2]=r,w[s+3]=C?_[s+3]:n}e.imageData=b},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;th[0]&&n>h[1]&&s>h[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,l,h=e.imageData.data,c=h.length,u=1-this.alpha;i=(l=new t.Color(this.color).getSource())[0]*this.alpha,r=l[1]*this.alpha,n=l[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,l=o(s*i),h=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(e,s,a,l,h):"hermite"===this.resizeType?n=this.hermiteFastResize(e,s,a,l,h):"bilinear"===this.resizeType?n=this.bilinearFiltering(e,s,a,l,h):"lanczos"===this.resizeType&&(n=this.lanczosResize(e,s,a,l,h)),e.imageData=n},sliceByTwo:function(e,i,n,s,o){var a,l,h=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-b.x)),S[M]||(S[M]={});for(var F=w.y-y;F<=w.y+y;F++)F<0||F>=o||(L=r(1e3*s(F-b.y)),S[M][L]||(S[M][L]=f(n(i(M*p,2)+i(L*m,2))/1e3)),(T=S[M][L])>0&&(I+=T,O+=T*c[E=4*(F*t+x)],A+=T*c[E+1],R+=T*c[E+2],D+=T*c[E+3]))}d[E=4*(C*a+l)]=O/I,d[E+1]=A/I,d[E+2]=R/I,d[E+3]=D/I}return++l1&&L<-1||(y=2*L*L*L-3*L*L+1)>0&&(T+=y*f[3+(M=4*(D+I*t))],b+=y,f[M+3]<255&&(y=y*f[M+3]/250),w+=y*f[M],C+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=w/S,_[v+1]=C/S,_[v+2]=x/S,_[v+3]=T/b}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,l=e.fillStyle,h=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:l,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):{},l=this._measureChar(e,o,r,a),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),h+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:h,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[t][i-1];u.left=d.left+d.width+l.kernedWidth-l.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),h&&m&&(e.fillStyle=m,e.fillRect(I,c+w*r+o,d,this.fontSize/15)),u=f.left,d=f.width,h=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-b,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 l=0;l0?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,l=e.topOffset,h=this.getValueOfPropertyAt(r,n,"deltaY");l+=(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,l+e.top+h,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,l=o.lineIndex,h=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=l;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][h].left),u>=a&&u1)&&(g/=this.lineHeight);var v=e.left+f+_,y=p-_,S=g,b=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,b=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+b,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(),l={x:t.left+o,y:t.top+t.topOffset+s},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/h,d=c.height/h,f=u-s,g=d-s,_=c.clientWidth/u,p=c.clientHeight/d;return l=x.util.transformPoint(l,a),(l=x.util.transformPoint(l,this.canvas.viewportTransform)).x*=_,l.y*=p,l.x<0&&(l.x=0),l.x>f&&(l.x=f),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.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,l=s.lineIndex,h=s.charIndex;if(o!==l){if(this.styles[o])for(i=a;i=h&&(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 l in i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&(n=this.styles[e][0===t?t:t-1]),this.styles[e]){var h=parseInt(l,10);h>=t&&(o=!0,s[h-t]=this.styles[e][l],a&&0===t||delete this.styles[e][l])}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 l=n[t?t-1:1];l&&i--;)this.styles[e][t+i]=C(l)},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,l=0,h=this._textLines.length;l0&&(o+=this._textLines[l-1].length+this.missingNewlineOffset(l-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,l=this._text.length,h=a.length,c=h-l,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):h0&&(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),l=this._textLines[n].slice(0,s),h=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-l.length+(1-h)},_getIndexOnLine:function(e,t){for(var i,r,n=this._textLines[e],s=this._getLineLeftOffset(e),o=0,a=0,l=n.length;at){r=!0;var h=s-i,c=s,u=Math.abs(h-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,l,h=this.getHeightOfLine(t),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[t];r+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)l=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&&!l&&this._reSpaceAndTab.test(f[g])&&(l=!0),l||(n=n||this.getCompleteStyleDeclaration(t,g),s=this.getCompleteStyleDeclaration(t,g+1),l=this._hasStyleChangedForSvg(n,s)),l&&(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,l=0,h=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 l in i[a])if(l>=r&&(!n||lr&&!p?(a.push(l),l=[],s=f,p=!0):s+=m,p||o||l.push(d),l=l.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(l),_+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:()=>{}},Z={};function J(e){var t=Z[e];if(void 0!==t)return t.exports;var i=Z[e]={exports:{}};return z[e](i,i.exports,J),i.exports}J.d=(e,t)=>{for(var i in t)J.o(t,i)&&!J.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},J.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var K={};(()=>{let e;J.d(K,{R:()=>e}),e="undefined"!=typeof document&&"undefined"!=typeof window?J(653).fabric:{version:"5.2.1"}})();var q=K.R;class Q{get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}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}_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,l=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,h=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),c=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),u=h/c,d=a/l,f=this._drawingLayer._getObjectFit();let g,_,p,m,v=1;if("contain"===f)u0?i-1:r,te),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 q.Control({positionHandler:$,actionHandler:ie(r>0?r-1:i,te),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=q.util.transformPoint({x:r,y:n},t.calcTransformMatrix());e.push({x:s.x,y:s.y})}return e}}}const ne=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"===h?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}},q.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();q.util.addListener(q.document,"touchend",this._onTouchEnd,{passive:!1}),q.util.addListener(q.document,"touchmove",this._onMouseMove,{passive:!1}),q.util.removeListener(i,r+"down",this._onMouseDown)},q.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,l=[],h=[],c=a?q.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?(l.push(h),h=[],o=g,m=!0):o+=v,m||a||h.push(f),h=h.concat(u),_=a?0:this._measureWord([f],t,d),d++,m=!1,g>p&&(p=g);return y&&l.push(h),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),l});class oe{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 q.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 oe(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 le{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 ce;!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"}(ce||(ce={}));const ue=(e,t,i,r)=>{if(!i)return e;let n=t+Math.round((e-t)/i)*i;return r&&(n=Math.min(n,r)),n};class de{static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:G,worker:W,getUserMedia:H,camera:await Y(),browser:U.browser,version:U.version,OS:U.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");de._engineResourcePath=(e=>{if(null==e&&(e="./"),!k){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){de._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=de._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",de.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(){var e,t;let i,r,n;if(this._isSingleFrameModeEnabled()?(i=this._imgWidth,r=this._imgHeight,n="contain"):(i=null===(e=this._video)||void 0===e?void 0:e.videoWidth,r=null===(t=this._video)||void 0===t?void 0:t.videoHeight,n=this.getVideoFit()),!i||!r)throw new Error("Invalid content dimensions.");return{width:i,height:r,objectFit:n}}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;let t;try{t=this._calculateCvsSize()}catch(e){if("Invalid content dimensions."===(e.message||e))return;throw e}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,l=o.dHeight;e.width==a&&e.height==l||(e.width=a,e.height=l);const h=window.getComputedStyle(this._elContainer),c=parseFloat(h.width),u=parseFloat(h.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._isSingleFrameModeEnabled())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);if(!i)return;const 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,l=this._decoratorArea.width/100*r,h=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(l),Math.round(h)),s.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),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(l+s.lineWidth),Math.round(h+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(l),Math.round(h)),s.fillStyle=this._viewDecoratorInfo.focus.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),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 de;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,de.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{de.onWarning&&de.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((()=>{de.onWarning&&de.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),t._drawingLayerManager=new ae,t}static async playVideo(e,t,i){if(!e)throw new Error("Invalid 'videoEl'.");if(!t)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{e.removeEventListener("loadstart",c),e.removeEventListener("abort",u),e.removeEventListener("play",d),e.removeEventListener("error",f),e.removeEventListener("loadedmetadata",p)};let a=!1;const l=()=>{a=!0,s&&clearTimeout(s),o(),r(e)},h=e=>{s&&clearTimeout(s),o(),n(e)},c=()=>{e.addEventListener("abort",u,{once:!0})},u=()=>{const e=new Error("Video playing was interrupted.");e.name="AbortError",h(e)},d=()=>{l()},f=()=>{h(new Error(`Video error ${e.error.code}: ${e.error.message}.`))};let g;const _=new Promise((e=>{g=e})),p=()=>{g()};if(e.addEventListener("loadstart",c,{once:!0}),e.addEventListener("play",d,{once:!0}),e.addEventListener("error",f,{once:!0}),e.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,e.autoplay&&await new Promise((e=>{setTimeout(e,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i));try{e.src&&await e.load(),await e.play(),l()}catch(e){console.warn("1st play error: "+((null==e?void 0:e.message)||e))}if(!a){await _;try{await e.play(),l()}catch(e){console.warn("2rd play error: "+((null==e?void 0:e.message)||e)),h(e)}}}}))}static findBestRearCameraInIOS(e){if(!e||!e.length)return null;const t=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=e.filter((e=>{const i=e.label.toLowerCase();return t.some((e=>i.includes(e)))}));if(!n.length)return null;const s=n.find((e=>{const t=e.label.toLowerCase();return i.some((e=>t.includes(e)))}));if(s)return s.deviceId;const o=n.find((e=>{const t=e.label.toLowerCase();return r.some((e=>t.includes(e)))}));return o?o.deviceId:n[0].deviceId}static findBestRearCamera(e){if(!e||!e.length)return null;if(["iPhone","iPad","Mac"].includes(U.OS))return de.findBestRearCameraInIOS(e);const t=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];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(U.OS)?e[e.length-1].deviceId:null}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._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameInputContainer=null,this._clickIptSingleFrameMode=()=>{if(!this._isSingleFrameModeEnabled())return;if(this.getDrawingLayers().some((e=>"editor"==e.getMode())))return;let e;if(this._singleFrameInputContainer)e=this._singleFrameInputContainer.firstElementChild;else{e=document.createElement("input"),e.setAttribute("type","file"),"camera"===this.singleFrameMode?(e.setAttribute("capture",""),e.setAttribute("accept","image/*")):1!=this.singleFrameMode&&"image"!==this.singleFrameMode||(e.removeAttribute("capture"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),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.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),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()),l={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},h=this._getImageData(e,r,n,s,null,{pixelFormat:a});if(!h)return null;const c=Date.now();return de._onLog&&de._onLog("DCE: _getVideoData(region?) END: "+c),l.data=h.data,l.pixelFormat=l.colorMode=h.pixelFormat,l._bUseWebGL=h._bUseWebGL,l.timeSpent=c-t,l.timeStamp=c,h.pixelFormat===ce.GREY?l.stride=l.width:l.stride=4*l.width,l};(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="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent";const t=document.createElement("div");t.append(e),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.pointerEvents="none",this._elContainer.prepend(t),this._singleFrameInputContainer=t}null==e||e.click()},this.styleEls=[],this._framePixelFormat=void 0,this._defaultFramePixelFormat="rgba",this.mapPixelFormatString_Enum=new Map([["grey",ce.GREY],["grey32",ce.GREY32],["rgba",ce.RGBA],["rbga",ce.RBGA],["grba",ce.GRBA],["gbra",ce.GBRA],["brga",ce.BRGA],["bgra",ce.BGRA]]),this.shaderPixelFormat=ce.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._isSingleFrameModeEnabled())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,l=this._elContainer.getBoundingClientRect(),h=l.left,c=l.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-h)/p,n=(i-c-(f-d/_)/2)/p):(p=f/a,n=(i-c)/p,r=(t-h-(d-f*_)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");_>g?(p=f/a,n=(i-c)/p,r=(t-h+(f*_-d)/2)/p):(p=d/o,r=(t-h)/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.cameraOpenTimeout=4e3,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=()=>{this._isSingleFrameModeEnabled()||("visible"===document.visibilityState?(de._onLog&&de._onLog("DCE: document visible."),this._video&&this._bOpen&&(async()=>{let e=!1;if(this._video.paused){de._onLog&&de._onLog("document visible. Not auto resume. 1st resume start.");try{await this._video.play(),e=!0}catch(e){de._onLog&&de._onLog("document visible. 1st resume video failed, try open instead.")}e||await this.play()}if(await new Promise((e=>setTimeout(e,300))),this._video.paused){de._onLog&&de._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this._video.play(),e=!0}catch(e){de._onLog&&de._onLog("document visible. 2rd resume video failed, try open instead.")}e||await this.play()}})()):"hidden"===document.visibilityState&&(de._onLog&&de._onLog("DCE: document hidden."),this._video&&this._bOpen&&(this._video.paused||this.pause())))},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._windowResizeListener=()=>{this._windowWidth!==document.documentElement.clientWidth&&(this._windowWidth=document.documentElement.clientWidth,this._updateLayers())},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null,navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this._singleFrameMode=!1:this._singleFrameMode=!0}_isSingleFrameModeEnabled(){return 0!=this.singleFrameMode}async play(e,t,i,r){let n;if(this._video&&this.videoSrc){de._onLog&&(n=Date.now(),de._onLog("DCE: start loading static video: "+n));const e=await de.playVideo(this._video,this.videoSrc,this.cameraOpenTimeout);if(de._onLog&&de._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._isSingleFrameModeEnabled())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 n;try{this._video&&this._video.srcObject&&this.stop(),de._onLog&&de._onLog("DCE: ======before video========");const s=()=>{if(!this._video)throw l&&l.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},o=this.getVideoSettings();let a,l;if("boolean"==typeof o.video&&(o.video={}),e)delete o.video.facingMode,o.video.deviceId={exact:e};else if(o.video.deviceId);else if(this._lastDeviceId)delete o.video.facingMode,o.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&de.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete o.video.facingMode,o.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&&(o.video.width=e,o.video.height=t)}else if(this.ifSkipCameraInspection);else if(o.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=o.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){a=!0;const e=de.findBestRearCamera(this._allCameras);e&&(delete o.video.facingMode,o.video.deviceId={exact:e})}}t&&(o.video.width={ideal:t}),i&&(o.video.height={ideal:i}),de._onLog&&de._onLog("======try getUserMedia========");let h=[0,500,1e3,2e3],c=null;const u=async e=>{for(let t of h){t&&(await new Promise((e=>setTimeout(e,t))),s());try{de._onLog&&de._onLog("ask "+JSON.stringify(e)),l=await navigator.mediaDevices.getUserMedia(e),s();break}catch(e){if("NotFoundError"===e.name||"NotAllowedError"===e.name||"AbortError"===e.name||"OverconstrainedError"===e.name)throw e;c=e,de._onLog&&de._onLog(e.message||e)}}};try{if(await u(o),l||"object"!=typeof o.video||(o.video.deviceId&&(delete o.video.deviceId,await u(o)),!l&&o.video.facingMode&&(delete o.video.facingMode,await u(o)),l||!o.video.width&&!o.video.height||(delete o.video.width,delete o.video.height,await u(o))),!l)throw c}catch(e){throw null==l||l.getTracks().forEach((e=>{e.stop()})),"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}const d=()=>{const e=l.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),s(),a&&!this.ifSkipCameraInspection){d();const e=de.findBestRearCamera(this._allCameras),t=null===(n=this._currentCamera)||void 0===n?void 0:n.deviceId;e&&e!=t&&(l.getTracks().forEach((e=>{e.stop()})),o.video.deviceId={exact:e},await u(o))}de._onLog&&de._onLog("DCE: ======play video========"),s(),await de.playVideo(this._video,l,this.cameraOpenTimeout),s(),de._onLog&&de._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f="got "+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")),de._onLog&&de._onLog("DCE: got "+f),d(),this._renderSelCameraInfo();const g={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(g.deviceId&&(this._lastDeviceId=g.deviceId,this.ifSaveLastUsedCamera&&de.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),o.video.width&&o.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(o.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(o.video.height))))),!r||!r.notTriggerPlayedEvent){const e=this.mapCameraEvents.get("played");for(let t of e){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(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}})(),de._onLog&&(n=Date.now(),de._onLog("DCE: start opening camera: "+n));const o=await this.promisePlay;return de._onLog&&de._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()}isPaused(){var e;return!this._isSingleFrameModeEnabled()&&!0===(null===(e=this._video)||void 0===e?void 0:e.paused)}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t=17&&e.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),this._video=e;const i=document.createElement("div");i.append(e),i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.width="100%",i.style.height="100%",i.style.overflow="hidden",this._videoContainer=i,t.prepend(i)}else!this._divScanArea&&t.classList.contains("dce-scanarea")?this._divScanArea=t:!this._divScanLight&&t.classList.contains("dce-scanlight")?this._divScanLight=t:!this._bgLoading&&t.classList.contains("dce-bg-loading")?this._bgLoading=t:!this._bgCamera&&t.classList.contains("dce-bg-camera")?this._bgCamera=t:!this._selCam&&t.classList.contains("dce-sel-camera")?this._selCam=t:!this._selRsl&&t.classList.contains("dce-sel-resolution")?(this._selRsl=t,this.videoSrc||this._isSingleFrameModeEnabled()||this._selRsl.options.length||(this._selRsl.innerHTML=[this._optGotRsl?"":'','','',''].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._isSingleFrameModeEnabled()||this.videoSrc?(this._isSingleFrameModeEnabled()&&(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(U.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)),this._windowWidth=document.documentElement.clientWidth,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){this._isSingleFrameModeEnabled()?(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._drawingLayerManager.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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=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._windowResizeListener)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}async open(e){this.UIElement||await this.setUIElement(de.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._isSingleFrameModeEnabled()&&(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&&(de._onLog&&de._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&&(de._onLog&&de._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){var t,i;let r="";const n=(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},s=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 o=null===(i=null===(t=this.videoSettings)||void 0===t?void 0:t.video)||void 0===i?void 0:i.deviceId;if(!o)return null;if(r=o.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:o.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!r)return null;let a=this._mapCameraResolutions.get(r);if(a&&!e)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),a=this._mapCameraResolutions.get(r);for(let e of this._predefinedResolutions){const t=await s(r,e.width,e.height);t&&!n(r,t)&&a.push([t.width,t.height])}return a}if(this._currentCamera){r=this._currentCamera.deviceId;let t=this._mapCameraResolutions.get(r);if(t&&!e)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),t=this._mapCameraResolutions.get(r);let i=this._videoTrack;for(let e of this._predefinedResolutions){await i.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const s=i.getSettings(),o={width:s.width,height:s.height};n(r,o)||t.push([o.width,o.height])}return this._video.srcObject.getTracks().forEach((e=>{e.stop()})),await this.play(r,null,null,{notTriggerPlayedEvent:!0}),t}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._isSingleFrameModeEnabled())throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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=ue(e,t.min,t.step,t.max),await this._videoTrack.applyConstraints({advanced:[{zoom:e}]}),e}_getHardwareScale(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(e,t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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}this._scaleCenter={x:r,y:n}}_resetScaleCenter(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(e,t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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=ue(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._isSingleFrameModeEnabled())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=ue(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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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=ue(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 l=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:n,sy:s,sWidth:o,sHeight:a,dWidth:o,dHeight:a},null,{pixelFormat:ce.RGBA});if(!l)return this._setFocusAndGetContract(e,t);const h=l.data;let c=0;for(let e=0,t=h.length-8;eo&&oc)return await this._doFocusDetail(e,s,o,r,n,h,c)}else{let a=await this._setFocusAndGetContract(e,h);if(o>a)return await this._doFocusDetail(e,s,o,r,n,h,a);if(o==a)return await this._doFocusDetail(e,s,o,h,a);let c=await this._setFocusAndGetContract(e,l);if(c>o&&o{try{(null==t||tthis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let r=ue(Math.sqrt(i*(t||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=ue(Math.sqrt((t||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=ue(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),l=await this._setFocusAndGetContract(e,r);if(a>l&&lo&&a>o){let t=await this._setFocusAndGetContract(e,i);const n=await this._doFocusDetail(e,r,l,i,t,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==l&&ll){const t=await this._doFocusDetail(e,r,l,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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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=h*(1-1/e)*(i/2-this._scaleCenter.x),u=h*(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,l=e,h=t;const c={regionLeft:0,regionTop:0,regionRight:l,regionBottom:h,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*l/100,c.regionTop=i.regionTop*h/100,c.regionRight=i.regionRight*l/100,c.regionBottom=i.regionBottom*h/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),l=Math.round(c.regionRight-c.regionLeft),h=Math.round(c.regionBottom-c.regionTop)):(n=0,s=0,l=Math.round(l),h=Math.round(h));const u=Math.max(l,h);if(r&&r>0&&u>r){const e=r/u;l>h?(o=r,a=Math.round(h*e)):(o=Math.round(l*e),a=r)}else o=l,a=h;return o<=0||a<=0?null:{sx:n,sy:s,sWidth:l,sHeight:h,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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;de._onLog&&(a=Date.now(),de._onLog("DCE: _drawImage(), START: "+a));let l=0,h=0,c=i,u=r,d=0,f=0,g=i,_=r;n&&(n.sx&&(l=Math.round(n.sx)),n.sy&&(h=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=ce.RGBA;o&&o.pixelFormat&&(p=o.pixelFormat);const m=e;if(!o||!o.bUseWebGL){de._onLog&&de._onLog("DCE: _drawImage() in context2d."),m.ctx2d||(m.ctx2d=m.getContext("2d",{willReadFrequently:!0}));const e=m.ctx2d;if(!e)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(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 `,l=r(e,[n(e,e.VERTEX_SHADER,s),n(e,e.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:l,attribLocations:{vertexPosition:e.getAttribLocation(l,"a_position"),texPosition:e.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:e.getUniformLocation(l,"u_image"),uColorFactor:e.getUniformLocation(l,"uColorFactor"),uMatrix:e.getUniformLocation(l,"u_matrix"),uTextureMatrix:e.getUniformLocation(l,"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,[ce.GREY,ce.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(),l/i,h/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;de._onLog&&(o=Date.now(),de._onLog("DCE: _getImageData(), START: "+o));const a=Math.round(r.sx),l=Math.round(r.sy),h=Math.round(r.sWidth),c=Math.round(r.sHeight),u=Math.round(r.dWidth),d=Math.round(r.dHeight);let f=ce.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(de._onLog&&de._onLog("DCE: _getImageData() in WebGL."),n)if(f===ce.GREY){if(p=new Uint8Array(u*d*4),_=this._drawImage(g,e,t,i,{sx:a,sy:l,sWidth:h,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=()=>{de._onLog&&de._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(de._onLog&&de._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t),de._onLog&&de._onLog("DCE: finish fetching a frame into buffer: "+Date.now());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()?(de._onLog&&de._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):0===this.refreshInterval&&t()),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._isSingleFrameModeEnabled())throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,de._onLog&&de._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(de._onLog&&de._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._drawingLayerManager.getSelectedDrawingItems()}createDrawingStyle(e){return this._drawingLayerManager.createDrawingStyle(e)}getDrawingStyle(e){return this._drawingLayerManager.getDrawingStyle(e)}getDrawingStyles(){return this._drawingLayerManager.getDrawingStyles()}updateDrawingStyle(e,t){return this._drawingLayerManager.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 se(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 le(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._isSingleFrameModeEnabled()&&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)}transformCoord(e){if(!this.isOpen())throw new Error("Unavailable when the camera is not open.");if(this._isSingleFrameModeEnabled()&&!this._cvsSingleFrameMode)throw new Error("No image is selected. ");const t=this._elContainer.getBoundingClientRect();let i,r,n,s,o,a=t.left,l=t.top,h=a+window.scrollX,c=l+window.scrollY;this._isSingleFrameModeEnabled()?(i=this._cvsSingleFrameMode.width,r=this._cvsSingleFrameMode.height,n=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).width),s=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,r=this.video.videoHeight,n=parseFloat(window.getComputedStyle(this._elContainer).width),s=parseFloat(window.getComputedStyle(this._elContainer).height),o=this.videoFit);const u=n/s,d=i/r;let f,g,_,p,m=1;if("contain"===o)u({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 q.Control({positionHandler:$,actionHandler:ie(i>0?i-1:r,te),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=q.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 q.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 ge(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 _e(e){return Math.abs(e)<1e-6?0:e<0?-1:1}function pe(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))}var me,ve,ye,Se,be,we,Ce,xe,Te,Ee,Ie,Oe,Ae,Re,De,Me,Le,Fe,Pe,ke,Be,Ne,je,Ve,Ue,Ge,We;class He extends P{static set _onLog(e){!function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?n.call(e,i):n?n.value=i:t.set(e,i)}(He,me,e,"f",ve),de._onLog=e}static get _onLog(){return function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)}(He,me,"f",ve)}static get version(){return this._version+`(DCE ${de.getVersion()})`}static _fireHTTPSWarnning(){He.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{He.onWarning&&He.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return de.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){if("boolean"!=typeof e&&!["image","camera"].includes(e))throw new Error("Invalid value.");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 cameraOpenTimeout(e){this.dce&&(this.dce.cameraOpenTimeout=e)}get cameraOpenTimeout(){return this.dce&&this.dce.cameraOpenTimeout}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||(P._onLog&&P._onLog("createDCEInstance()"),de.defaultUIElementURL=null,this.dce=await de.createInstance(),this.dce.cameraOpenTimeout<15e3&&(this.dce.cameraOpenTimeout=15e3),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=fe,["iPhone","iPad","Android","HarmonyOS"].includes(P.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:l,pixelFormat:h,timeStamp:c,_sWidth:u,_sHeight:d}=t,f={timeStamp:c};if("grey"===h)i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_GrayScaled,0,f);else if("rgba"===h)i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_ABGR_8888,0,f);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_ARGB_8888,0,f)}if(await this.clearMapDecodeRecord(),P.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}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._onPlayed=null}static async createInstance(e){const t=new He;t._instanceID=await He.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(He.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),He._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(!P._bUseFullFeature){if(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=P._nextTaskID++;P._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)}})),P._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 P._onLog&&P._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));P._onLog&&P._onLog("======= once read ======="),P._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return P._onLog&&P._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:l,pixelFormat:h,timeStamp:c,_sWidth:u,_sHeight:d}=t,f={timeStamp:c};if("grey"===h)i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_GrayScaled,0,f);else if("rgba"===h)i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_ABGR_8888,0,f);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);i=await this._decodeBuffer_Uint8Array(r,o,a,l,e.EnumImagePixelFormat.IPF_ARGB_8888,0,f)}if(P.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=async()=>new Promise(((e,t)=>{let i=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!1}})})),i=await t(),r=(e,t,i,r,n,s,o)=>{let a=s/r,l=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/l+i,e.y2=e.y2/l+i,e.y3=e.y3/l+i,e.y4=e.y4/l+i},l=t=>{if(!t)return null;const i={};let l,h,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!=_e(a.y-i)>0&&_e(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)=>!!(pe([e[0],e[1]],[e[2],e[3]],[t.x1,t.y1],[t.x2,t.y2])||pe([e[0],e[1]],[e[2],e[3]],[t.x2,t.y2],[t.x3,t.y3])||pe([e[0],e[1]],[e[2],e[3]],[t.x3,t.y3],[t.x4,t.y4])||pe([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 i of t){if(i.resultType!==e.EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE)continue;const t=i.scaleDownRatio;for(let e of i.results){if(!e)continue;const i={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};r(i,n,s,u,d,o,a),_(g,i)&&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 i=h.x1/u,l=(u-h.x3)/u,c=h.y1/d,f=(d-h.y3)/d;if(i>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-i),(.5-t)/(.5-l),(.5-t)/(.5-c),(.5-t)/(.5-f)].filter((e=>e>0)),r=Math.min(...e,this.autoZoomInIdealModuleSize/h.result.moduleSize),n=this.dce.getZoomSettings().factor;let s=Math.max(Math.pow(n*r,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);s=Math.min(s,r);const o=n*s;try{await this.setZoom({factor:o})}catch(e){const t=e.message||e;console.warn(t)}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){r(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){const t=e.message||e;console.warn(t)}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-i),(.5-t)/(.5-l),(.5-t)/(.5-c),(.5-t)/(.5-f)].filter((e=>e>0));let r=Math.min(...e)*this.dce.getZoomSettings().factor;try{await this.setZoom({factor:r})}catch(e){const t=e.message||e;console.warn(t)}this.dce.clearFrameBuffer(),this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((()=>{})))}}}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{r(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){const t=e.message||e;console.warn(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 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);try{await this.setZoom({factor:i})}catch(e){const t=e.message||e;console.warn(t)}this.dce.clearFrameBuffer()}}this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((()=>{})))}else this.autoFocus&&(this.autoFocusFrameArray.length=0,this.setFocus({mode:"continuous"}).catch((()=>{})))}return i})().then((e=>{if(P._onLog&&P._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,P._onLog&&P._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&&(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){P._onLog&&P._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 P._onLog&&P._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._drawResults(null),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()}convertToPageCoordinates(e){return this.dce.convertToPageCoordinates(e)}convertToClientCoordinates(e){return this.dce.convertToClientCoordinates(e)}destroyContext(){this.close(),this.dce&&this.dce.dispose(!1),this.bDestroyed||super.destroyContext()}}me=He,ve={value:void 0},e.EnumBarcodeColourMode=void 0,(ye=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[ye.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",ye[ye.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",ye[ye.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",ye[ye.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",ye[ye.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",ye[ye.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",ye[ye.BICM_SKIP=0]="BICM_SKIP",ye[ye.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(Se=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[Se.BCM_AUTO=1]="BCM_AUTO",Se[Se.BCM_GENERAL=2]="BCM_GENERAL",Se[Se.BCM_SKIP=0]="BCM_SKIP",Se[Se.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(be=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[be.BF2_NULL=0]="BF2_NULL",be[be.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",be[be.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",be[be.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",be[be.BF2_POSTNET=2097152]="BF2_POSTNET",be[be.BF2_PLANET=4194304]="BF2_PLANET",be[be.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",be[be.BF2_RM4SCC=16777216]="BF2_RM4SCC",be[be.BF2_DOTCODE=2]="BF2_DOTCODE",be[be.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",be[be.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",be[be.BF2_PHARMACODE=12]="BF2_PHARMACODE",be[be.BF2_ALL=-1]="BF2_ALL",e.EnumBinarizationMode=void 0,(we=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[we.BM_AUTO=1]="BM_AUTO",we[we.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",we[we.BM_SKIP=0]="BM_SKIP",we[we.BM_THRESHOLD=4]="BM_THRESHOLD",we[we.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(Ce=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[Ce.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(xe=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[xe.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(Te=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[Te.CCM_AUTO=1]="CCM_AUTO",Te[Te.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",Te[Te.CCM_SKIP=0]="CCM_SKIP",Te[Te.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(Ee=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[Ee.CICM_GENERAL=1]="CICM_GENERAL",Ee[Ee.CICM_SKIP=0]="CICM_SKIP",Ee[Ee.CICM_REV=2147483648]="CICM_REV",e.EnumConflictMode=void 0,(Ie=e.EnumConflictMode||(e.EnumConflictMode={}))[Ie.CM_IGNORE=1]="CM_IGNORE",Ie[Ie.CM_OVERWRITE=2]="CM_OVERWRITE",e.EnumDeblurMode=void 0,(Oe=e.EnumDeblurMode||(e.EnumDeblurMode={}))[Oe.DM_SKIP=0]="DM_SKIP",Oe[Oe.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",Oe[Oe.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",Oe[Oe.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",Oe[Oe.DM_SMOOTHING=8]="DM_SMOOTHING",Oe[Oe.DM_MORPHING=16]="DM_MORPHING",Oe[Oe.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",Oe[Oe.DM_SHARPENING=64]="DM_SHARPENING",Oe[Oe.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",Oe[Oe.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(Ae=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[Ae.DRM_AUTO=1]="DRM_AUTO",Ae[Ae.DRM_GENERAL=2]="DRM_GENERAL",Ae[Ae.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",Ae[Ae.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",Ae[Ae.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",Ae[Ae.DRM_SKIP=0]="DRM_SKIP",Ae[Ae.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(Re=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[Re.DPMCRM_AUTO=1]="DPMCRM_AUTO",Re[Re.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",Re[Re.DPMCRM_SKIP=0]="DPMCRM_SKIP",Re[Re.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(De=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[De.GTM_INVERTED=1]="GTM_INVERTED",De[De.GTM_ORIGINAL=2]="GTM_ORIGINAL",De[De.GTM_SKIP=0]="GTM_SKIP",De[De.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(Me=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[Me.IPM_AUTO=1]="IPM_AUTO",Me[Me.IPM_GENERAL=2]="IPM_GENERAL",Me[Me.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",Me[Me.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",Me[Me.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",Me[Me.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",Me[Me.IPM_SKIP=0]="IPM_SKIP",Me[Me.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(Le=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[Le.IRSM_MEMORY=1]="IRSM_MEMORY",Le[Le.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",Le[Le.IRSM_BOTH=4]="IRSM_BOTH",e.EnumLocalizationMode=void 0,(Fe=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[Fe.LM_SKIP=0]="LM_SKIP",Fe[Fe.LM_AUTO=1]="LM_AUTO",Fe[Fe.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",Fe[Fe.LM_LINES=8]="LM_LINES",Fe[Fe.LM_STATISTICS=4]="LM_STATISTICS",Fe[Fe.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",Fe[Fe.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",Fe[Fe.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",Fe[Fe.LM_CENTRE=128]="LM_CENTRE",Fe[Fe.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",Fe[Fe.LM_REV=2147483648]="LM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,(Pe=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[Pe.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",Pe[Pe.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",Pe[Pe.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",Pe[Pe.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,(ke=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[ke.RPM_AUTO=1]="RPM_AUTO",ke[ke.RPM_GENERAL=2]="RPM_GENERAL",ke[ke.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",ke[ke.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",ke[ke.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",ke[ke.RPM_SKIP=0]="RPM_SKIP",ke[ke.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(Be=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[Be.RCT_PIXEL=1]="RCT_PIXEL",Be[Be.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,(Ne=e.EnumResultType||(e.EnumResultType={}))[Ne.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",Ne[Ne.RT_RAW_TEXT=1]="RT_RAW_TEXT",Ne[Ne.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",Ne[Ne.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(je=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[je.SUM_AUTO=1]="SUM_AUTO",je[je.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",je[je.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",je[je.SUM_SKIP=0]="SUM_SKIP",je[je.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(Ve=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[Ve.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",Ve[Ve.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",Ve[Ve.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",Ve[Ve.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",Ve[Ve.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",Ve[Ve.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(Ue=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[Ue.TFM_AUTO=1]="TFM_AUTO",Ue[Ue.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",Ue[Ue.TFM_SKIP=0]="TFM_SKIP",Ue[Ue.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(Ge=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[Ge.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",Ge[Ge.TROM_POSITION=2]="TROM_POSITION",Ge[Ge.TROM_FORMAT=4]="TROM_FORMAT",Ge[Ge.TROM_SKIP=0]="TROM_SKIP",Ge[Ge.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(We=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[We.TDM_AUTO=1]="TDM_AUTO",We[We.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",We[We.TDM_SKIP=0]="TDM_SKIP",We[We.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=P,e.BarcodeScanner=He})); diff --git a/dist/dbr.mjs b/dist/dbr.mjs index fa05d4b..f782305 100644 --- a/dist/dbr.mjs +++ b/dist/dbr.mjs @@ -2,20 +2,21 @@ * Dynamsoft JavaScript Library * @product Dynamsoft Barcode Reader JS Edition * @website http://www.dynamsoft.com - * @copyright Copyright 2023, Dynamsoft Corporation + * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft - * @version 9.6.32 (js 20231027) + * @version 9.6.42 (js 20240426) * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ */ -const e="undefined"==typeof self,t=e?{}:self;let i,r,n,s,o;if("undefined"!=typeof navigator&&(i=navigator,r=i.userAgent,n=i.platform,s=i.mediaDevices),!e){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}}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=!(!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(!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"./"})(),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;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&&(b(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,b(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 C=function(){this.init()};C.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 E&&n&&delete E[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 I=function(e){this._parent=e,this.init()};I.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 E={},O=function(e){var t=e._src;if(E[t])return e._duration=E[t].duration,void R(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(E[t._src]=e,R(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)},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())},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}`)}})}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})(F,e)}static get productKeys(){return this._license}static set productKeys(e){F.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){F.license=e}static get organizationID(){return this._license}static set organizationID(e){F.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+d);i._sessionPassword=t})(F,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(t){if(!this._pLoad.isEmpty)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` or `loadWasm` is called.");F._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`"+d);i._licenseServer=_(t)})(F,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||""})(F,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.");F.__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=F._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",F.engineResourcePath)}static set defaultUIElementURL(e){F._defaultUIElementURL=e}static _fireHTTPSWarnning(){F.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{F.onWarning&&F.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;F._onLog&&F._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))}))),F.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&&(F._onLog&&F._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(!F.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:i,ls:r,sp:n,rmk:s}=(e=>{const i=e;if(i._pLoad.isEmpty){let e,r,n=i._license||"",s=JSON.parse(JSON.stringify(i._licenseServer)),o=i._sessionPassword,a=0;if(n.startsWith("t")||n.startsWith("f"))a=0;else if(0===n.length||n.startsWith("P")||n.startsWith("L")||n.startsWith("Y")||n.startsWith("A"))a=1;else{a=2;const t=n.indexOf(":");if(-1!=t&&(n=n.substring(t+1)),n.startsWith("DLS2")){let t;try{let e=n.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(n=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof n&&(n=JSON.stringify(n)),0===s.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),s=_(e)}!o&&t.sessionPassword&&(o=t.sessionPassword),e=t.remark}("200001"===n||n.startsWith("200001-"))&&(s&&s.length||(n="")),n||(a=1)}if(a&&(t.crypto||(r="Please upgrade your browser to support online key."),t.crypto.subtle||(r="Require https to use online key in this browser.")),r){if(1!==a)throw new Error(r);a=0,console.warn(r),i._lastErrorCode=-1,i._lastErrorString=r}return 1===a&&(n="",console.warn("Applying for a public trial license ...")),{lt:a,l:n,ls:s,sp:o,rmk:e}}throw new Error("Can't preprocess license again"+d)})(F);this._pLoad.task=async(t,a)=>{let h=F.engineResourcePath+F._workerName;F.engineResourcePath.startsWith(location.origin)||(h=await fetch(h).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),F._dbrWorker=new Worker(h),F._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},F._dbrWorker.onmessage=async i=>{let r=i.data?i.data:i;switch(r.type){case"log":F._onLog&&F._onLog(r.message);break;case"load":{r.message&&(r.message=r.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let i,n=!1;1===e&&(n=!0,r.message||(r.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),r.success?(F._dbrWorker.onerror=null,F._version=r.version+"(JS "+F._jsVersion+"."+F._jsEditVersion+")",F._onLog&&F._onLog("load dbr worker success"),r.message&&console.warn(r.message)):(i=new Error(r.message),i.stack=r.stack+"\n"+i.stack,i.ltsErrorCode=r.ltsErrorCode,n||111==r.ltsErrorCode&&-1!=r.message.toLowerCase().indexOf("trial license")&&(n=!0)),n&&F.showDialog(r.success?"warn":"error",r.message),r.success?t():a(i);break}case"task":{let e=r.id,t=r.body;try{F._taskCallbackMap.get(e)(t),F._taskCallbackMap.delete(e)}catch(t){throw F._taskCallbackMap.delete(e),t}break}default:F._onLog&&F._onLog(i)}},F._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:F.engineResourcePath,bUseFullFeature:F._bUseFullFeature,bd:F._bWasmDebug,v:F._jsVersion,brtk:!!e,bptk:1===e,l:i,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:o,cv:F.authCacheVersion,fn:F.deviceFriendlyName,ls:r,sp:n,rmk:s})}}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 F.loadWasm(),await new Promise(((t,i)=>{let r=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){const e=new F;return e._instanceID=await F.createInstanceInWorker(),F._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){F._onLog&&F._onLog("decode(source: any)"),F._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):F.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):F.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=F._nextTaskID++;F._taskCallbackMap.set(l,(e=>{if(e.success){let t,i=F._onLog?Date.now():0;F._onLog&&F._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return h(e)}if(F._onLog){let e=Date.now();F._onLog("DBR getting message from worker timestamp: "+i),F._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),F._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),F._onLog("Handling results from DBR worker costs: "+(e-i)),F._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(),F._onLog&&F._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),F._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]),F._onLog&&o&&o.timeStamp&&F._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s,o){F._onLog&&F._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 F._onLog&&F._onLog("decodeBuffer(buffer,width,height,stride,format)"),F._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=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._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(!F._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.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|=S.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,i)=>{let r=F._nextTaskID++;F._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)}})),F._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=L,await new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=L,await new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!F._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=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!F._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=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){F._onLog&&F._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){F._onLog&&F._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}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl);let h=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return F.recalculateResultLocation(h,0,0,n,s,i,r),h}async _decode_Canvas(e,t){if(F._onLog&&F._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,p.IPF_ABGR_8888,0,t)}async _decode_Video(e,t){if(F._onLog&&F._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}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r);let h=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return F.recalculateResultLocation(h,0,0,n,s,i,r),h}async _decode_DCEFrame(e,t){if(F._onLog&&F._onLog("_decode_DCEFrame(dceFrame)"),!F.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,p.IPF_GrayScaled,0,c);else if("rgba"===o)i=await this._decodeBuffer_Uint8Array(l,r,n,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,n,a,p.IPF_ARGB_8888,0,c)}else if("grey"===s)i=await this._decodeBuffer_Uint8Array(l,r,n,r,p.IPF_GrayScaled,0,c);else if("rgba"===s)i=await this._decodeBuffer_Uint8Array(l,r,n,4*r,p.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,p.IPF_ARGB_8888,0,c)}return i}async _decode_DSImage(e,t){if(F._onLog&&F._onLog("_decode_DSImage(dsImage)"),!F.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 F._onLog&&F._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),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}static BarcodeReaderException(e,t){let i,r=m.DBR_UNKNOWN;return"number"==typeof e?(r=e,i=new Error(t)):i=new Error(e),i.code=r,i}_handleRetJsonString(e){let t=m;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&&!F._setWarnnedEx.has(e.description)&&(F._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw F.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=F._nextTaskID++;F._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)}})),F._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=F._nextTaskID++;F._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)}})),F._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=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!0}})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let i of e)if(i.dataType==v.IMRDT_IMAGE)for(let e of i.results){const i=e.bytes;let r;switch(F._onLog&&F._onLog(" "+i.length+" "+i.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case p.IPF_ABGR_8888:r=new Uint8ClampedArray(i);break;case p.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=F._nextTaskID++;F._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)}})),F._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(!F._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|=S.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=F._nextTaskID++;F._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,i(e)}})),F._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 F._onLog&&F._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));F._onLog&&F._onLog("======= once read ======="),F._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(),!F.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return F._onLog&&F._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))}))),F.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(F._onLog&&F._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&&(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"),F._onLog&&F._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(F._onLog&&F._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 F._onLog&&F._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.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(F._onLog&&F._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||this._promiseStartScan)&&this.stopScanning(),this.setImageSource(null);let e=F._nextTaskID++;F._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),F._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}F._jsVersion="9.6.32",F._jsEditVersion="20231027",F._version=`loading...(JS ${F._jsVersion}.${F._jsEditVersion})`,F._license=f,F._sessionPassword=g,F.browserInfo=o,F._workerName=`dbr-${F._jsVersion}.browser.worker.js`,F._engineResourcePath=u,F._licenseServer=[],F._deviceFriendlyName="",F._isShowRelDecodeTimeInResults=!1,F._bWasmDebug=!1,F._bNeverShowDialog=!1,F.__bUseFullFeature=!0,F._nextTaskID=0,F._taskCallbackMap=new Map,F._pLoad=new w,F._lastErrorCode=0,F._lastErrorString="",F._setWarnnedEx=new Set,F._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,b,w,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 E(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=_*_,b=m*v-m*y-v*S,w=0;if(b<0){var C=Math.sqrt(1-b/(m*v));i*=C,s*=C}else w=(o===a?-1:1)*Math.sqrt(b/(m*y+v*S));var T=w*i*p/s,I=-w*s*_/i,E=d*T-u*I+.5*e,O=u*T+d*I+.5*t,A=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=A+L,k=0;kw)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,b=Math.abs,w=[],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),b(c)<1e-12){if(b(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,A=w.length,D=A;A--;)I=(O=1-(f=w[A]))*O*O*t+3*O*O*f*r+3*O*f*f*s+f*f*f*a,C[0][A]=I,E=O*O*O*i+3*O*O*f*n+3*O*f*f*o+f*f*f*h,C[1][A]=E;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),b=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=b,s.durationRate=n,!o){if(!f(S,b,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,b,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,b={},w="",C=0,x=0;if(b.width=0,b.height=0,b.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 b;if(m)return b.width=s(d),b.height=s(f),b;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),b.minX=i,b.minY=r,b.viewBoxWidth=n,b.viewBoxHeight=o,y?(b.width=n,b.height=o):(b.width=s(d),b.height=s(f),c=b.width/n,u=b.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=b.width-n*c,x=b.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 b;if((g||_)&&"#document"!==e.parentNode.nodeName&&(w=" translate("+s(g)+" "+s(_)+") "),a=w+" 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),b}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 b(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 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=b(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),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=b(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),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),w=m(f,y,S),C=t.gestureScale;if(w)return!1;if(C)o=t.scaleX*C,a=t.scaleY*C;else{if(s=b(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 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}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=b(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=b,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,b=l>y||c>S;v=b||(l<.9*y||c<.9*S)&&y>h&&S>h,b&&!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,b={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=b[t]:t-=.5,"string"==typeof r?r=b[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?b[this.originX]:this.originX-.5,i="string"==typeof e?b[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=E);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(),E.call(c,this.gl,c),l>window.performance.now()-h?(this.imageBuffer=a,this.copyGLTo2D=E):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));w[s]=t,w[s+1]=i,w[s+2]=r,w[s+3]=C?_[s+3]:n}e.imageData=b},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-b.x)),S[M]||(S[M]={});for(var F=w.y-y;F<=w.y+y;F++)F<0||F>=o||(L=r(1e3*s(F-b.y)),S[M][L]||(S[M][L]=f(n(i(M*p,2)+i(L*m,2))/1e3)),(T=S[M][L])>0&&(E+=T,O+=T*c[I=4*(F*t+x)],A+=T*c[I+1],D+=T*c[I+2],R+=T*c[I+3]))}d[I=4*(C*a+h)]=O/E,d[I+1]=A/E,d[I+2]=D/E,d[I+3]=R/E}return++h1&&L<-1||(y=2*L*L*L-3*L*L+1)>0&&(T+=y*f[3+(M=4*(R+E*t))],b+=y,f[M+3]<255&&(y=y*f[M+3]/250),w+=y*f[M],C+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=w/S,_[v+1]=C/S,_[v+2]=x/S,_[v+3]=T/b}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 E=v+s+u;"rtl"===this.direction&&(E=this.width-E-d),l&&m&&(e.fillStyle=m,e.fillRect(E,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;E=v+s+u,"rtl"===this.direction&&(E=this.width-E-d),e.fillStyle=p,g&&p&&e.fillRect(E,c+w*r+o,d-b,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,b=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,b=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+b,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:()=>{}},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; +const e="undefined"==typeof self,t=e?{}:self;let i,r,n,s,o;"undefined"!=typeof navigator&&(i=navigator,r=i.userAgent,n=i.platform,s=i.mediaDevices),function(){if(!e){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,l="unknownOS";for(let t in e){const i=e[t]||{};let n=i.str||r,o=i.search||t,l=i.verStr||r,h=i.verSearch||t;if(h instanceof Array||(h=[h]),-1!=n.indexOf(o)){s=t;for(let e of h){let t=l.indexOf(e);if(-1!=t){a=parseFloat(l.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)){l=e;break}}"Linux"==l&&-1!=r.indexOf("Windows NT")&&(l="HarmonyOS"),o={browser:s,version:a,OS:l}}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)),l=!("undefined"==typeof Worker),h=!(!s||!s.getUserMedia),c=async()=>{let e=!1;if(h)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(!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"./"})(),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;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&&(b(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,b(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 C=function(){this.init()};C.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\/(.*?) /),l=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:!(l||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(l||!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),h=Math.max(0,(i._sprite[e][0]+i._sprite[e][1])/1e3-l),c=1e3*h/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=l,o._start=u,o._stop=d,o._loop=!(!o._loop&&!i._sprite[e][2])};if(!(l>=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,l,86400):g.bufferSource.noteGrainOn(0,l,h):o._loop?g.bufferSource.start(0,l,86400):g.bufferSource.start(0,l,h),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=l,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]):n.length>=2&&(e=parseFloat(n[0]),t=parseInt(n[1],10)),!(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 s=0;s0?r/h:r),u=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var n=(Date.now()-u)/r;u=Date.now(),a+=l*n,a=Math.round(100*a)/100,a=l<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 s=0;s=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 n=i._soundById(t);if(n){if(!("number"==typeof e&&e>=0)){if(i._webAudio){var s=i.playing(t)?x.ctx.currentTime-n._playStart:0,o=n._rateSeek?n._rateSeek-n._seek:0;return n._seek+(o+s*Math.abs(n._rate))}return n._node.currentTime}var a=i.playing(t);a&&i.pause(t,!0),n._seek=e,n._ended=!1,i._clearTimer(t),i._webAudio||!n._node||isNaN(n._node.duration)||(n._node.currentTime=e);var l=function(){a&&i.play(t,!0),i._emit("seek",t)};if(a&&!i._webAudio){var h=function(){i._playLock?setTimeout(h,0):l()};setTimeout(h,0)}else l()}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 E&&n&&delete E[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 I=function(e){this._parent=e,this.init()};I.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 E={},O=function(e){var t=e._src;if(E[t])return e._duration=E[t].duration,void R(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),r=new Uint8Array(i.length),n=0;n0?(E[t._src]=e,R(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)},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())},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 l=a._orientation;return i="number"!=typeof i?l[1]:i,r="number"!=typeof r?l[2]:r,n="number"!=typeof n?l[3]:n,s="number"!=typeof s?l[4]:s,o="number"!=typeof o?l[5]:o,"number"!=typeof e?l:(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{const i=e;if(!i._pLoad.isEmpty)throw new Error("`license`"+d);i._license=t})(F,e)}static get productKeys(){return this._license}static set productKeys(e){F.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){F.license=e}static get organizationID(){return this._license}static set organizationID(e){F.license=e}static set sessionPassword(e){((e,t)=>{const i=e;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+d);i._sessionPassword=t})(F,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:a,worker:l,getUserMedia:h,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.");F._engineResourcePath=(t=>{if(null==t&&(t="./"),e);else{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`"+d);i._licenseServer=_(t)})(F,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||""})(F,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.");F.__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=F._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",F.engineResourcePath)}static set defaultUIElementURL(e){F._defaultUIElementURL=e}static _fireHTTPSWarnning(){F.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{F.onWarning&&F.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;F._onLog&&F._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:l}=e;i=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),F.recalculateResultLocation(i,r,n,a,l,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&&(F._onLog&&F._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(!F.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:i,ls:r,sp:n,rmk:s}=((e,i=!1)=>{const r=e;if(r._pLoad.isEmpty){let e,n,s,o=r._license||"",a=JSON.parse(JSON.stringify(r._licenseServer)),l=r._sessionPassword,h=0;if(o.startsWith("t")||o.startsWith("f"))h=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))h=1;else{h=2;const t=o.indexOf(":");-1!=t&&(o=o.substring(t+1));const i=o.indexOf("?");if(-1!=i&&(n=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))h=0;else{if(o.startsWith("DLS2")){let t;try{let e=o.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(o=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===a.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),a=_(e)}!l&&t.sessionPassword&&(l=t.sessionPassword),e=t.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(h=1)}}if(h&&(i||(t.crypto||(s="Please upgrade your browser to support online key."),t.crypto.subtle||(s="Require https to use online key in this browser."))),s){if(1!==h)throw new Error(s);h=0,console.warn(s),r._lastErrorCode=-1,r._lastErrorString=s}return 1===h&&(o="",console.warn("Applying for a public trial license ...")),{lt:h,l:o,ls:a,sp:l,rmk:e,cv:n}}throw new Error("Can't preprocess license again"+d)})(F);this._pLoad.task=async(t,a)=>{let l=F.engineResourcePath+F._workerName;F.engineResourcePath.startsWith(location.origin)||(l=await fetch(l).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),F._dbrWorker=new Worker(l),URL.revokeObjectURL(l),F._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},F._dbrWorker.onmessage=async i=>{let r=i.data?i.data:i;switch(r.type){case"log":F._onLog&&F._onLog(r.message);break;case"load":{r.message&&(r.message=r.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let i,n=!1;1===e&&(n=!0,r.message||(r.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),r.success?(F._dbrWorker.onerror=null,F._version=r.version+"(JS "+F._jsVersion+"."+F._jsEditVersion+")",F._onLog&&F._onLog("load dbr worker success"),r.message&&console.warn(r.message)):(i=new Error(r.message),i.stack=r.stack+"\n"+i.stack,i.ltsErrorCode=r.ltsErrorCode,n||111==r.ltsErrorCode&&-1!=r.message.toLowerCase().indexOf("trial license")&&(n=!0)),n&&F.showDialog(r.success?"warn":"error",r.message),r.success?t():a(i);break}case"task":{let e=r.id,t=r.body;try{F._taskCallbackMap.get(e)(t),F._taskCallbackMap.delete(e)}catch(t){throw F._taskCallbackMap.delete(e),t}break}default:F._onLog&&F._onLog(i)}},F._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:F.engineResourcePath,bUseFullFeature:F._bUseFullFeature,bd:F._bWasmDebug,v:F._jsVersion,brtk:!!e,bptk:1===e,l:i,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:o,cv:F.authCacheVersion,fn:F.deviceFriendlyName,ls:r,sp:n,rmk:s})}}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(!h&&e.classList.contains("dls-license-icon-close"))h=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 l=t.substring(n+1,s);o.setAttribute("href",l),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 F.loadWasm(),await new Promise(((t,i)=>{let r=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}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.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=L,this._promiseStartScan=null,this.beepSound=new T({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}static async createInstance(){const e=new F;return e._instanceID=await F.createInstanceInWorker(),F._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(e){F._onLog&&F._onLog("decode(source: any)"),F._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):F.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):F.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,l)=>{let h=F._nextTaskID++;F._taskCallbackMap.set(h,(e=>{if(e.success){let t,i=F._onLog?Date.now():0;F._onLog&&F._onLog("worker return result: "+i),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return l(e)}if(F._onLog){let e=Date.now();F._onLog("DBR getting message from worker timestamp: "+i),F._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),F._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),F._onLog("Handling results from DBR worker costs: "+(e-i)),F._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,l(t)}})),this._timeEnterInnerDBR=Date.now(),F._onLog&&F._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),F._dbrWorker.postMessage({type:"decodeBuffer",id:h,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:r,format:n,orientation:s,config:o}},[e.buffer]),F._onLog&&o&&o.timeStamp&&F._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(e,t,i,r,n,s,o){F._onLog&&F._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 F._onLog&&F._onLog("decodeBuffer(buffer,width,height,stride,format)"),F._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=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._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(!F._bUseFullFeature){if(t.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.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|=S.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,i)=>{let r=F._nextTaskID++;F._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)}})),F._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=L,await new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=L,await new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!F._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=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!F._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof 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=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){F._onLog&&F._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.src=r,n.onload=()=>{URL.revokeObjectURL(n.src),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){F._onLog&&F._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}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r);let l=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return F.recalculateResultLocation(l,0,0,n,s,i,r),l}async _decode_Canvas(e,t){if(F._onLog&&F._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,p.IPF_ABGR_8888,0,t)}async _decode_Video(e,t){if(F._onLog&&F._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}));a.ctx2d.drawImage(e,0,0,n,s,0,0,i,r);let l=await this._decode_Canvas(a,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return F.recalculateResultLocation(l,0,0,n,s,i,r),l}async _decode_DCEFrame(e,t){if(F._onLog&&F._onLog("_decode_DCEFrame(dceFrame)"),!F.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:l}=e;let h;h=t&&t.bCopyData?new Uint8Array(e.data):e.data;let c=null;if(t?(c=JSON.parse(JSON.stringify(t)),c.timeStamp=l):c={timeStamp:l},o&&a)if("grey"===o)i=await this._decodeBuffer_Uint8Array(h,r,n,a,p.IPF_GrayScaled,0,c);else if("rgba"===o)i=await this._decodeBuffer_Uint8Array(h,r,n,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(h,r,n,a,p.IPF_ARGB_8888,0,c)}else if("grey"===s)i=await this._decodeBuffer_Uint8Array(h,r,n,r,p.IPF_GrayScaled,0,c);else if("rgba"===s)i=await this._decodeBuffer_Uint8Array(h,r,n,4*r,p.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(h,r,n,4*r,p.IPF_ARGB_8888,0,c)}return i}async _decode_DSImage(e,t){if(F._onLog&&F._onLog("_decode_DSImage(dsImage)"),!F.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)}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 l=s/r,h=o/n;e.x1=e.x1/l+t,e.x2=e.x2/l+t,e.x3=e.x3/l+t,e.x4=e.x4/l+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,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),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}static BarcodeReaderException(e,t){let i,r=m.DBR_UNKNOWN;return"number"==typeof e?(r=e,i=new Error(t)):i=new Error(e),i.code=r,i}_handleRetJsonString(e){let t=m;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&&!F._setWarnnedEx.has(e.description)&&(F._setWarnnedEx.add(e.description),console.warn(e.description)),e.textResults}if(e.exception==t.DBR_SUCCESS)return e.data;throw F.BarcodeReaderException(e.exception,e.description)}async setModeArgument(e,t,i,r){return await new Promise(((n,s)=>{let o=F._nextTaskID++;F._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)}})),F._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=F._nextTaskID++;F._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)}})),F._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=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!0}})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let i of e)if(i.dataType==v.IMRDT_IMAGE)for(let e of i.results){const i=e.bytes;let r;switch(F._onLog&&F._onLog(" "+i.length+" "+i.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case p.IPF_ABGR_8888:r=new Uint8ClampedArray(i);break;case p.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=F._nextTaskID++;F._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)}})),F._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(!F._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|=S.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=F._nextTaskID++;F._taskCallbackMap.set(r,(t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack+="\n"+t.stack,i(e)}})),F._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 F._onLog&&F._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));F._onLog&&F._onLog("======= once read ======="),F._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(),!F.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return F._onLog&&F._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:l}=e;t=i.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),F.recalculateResultLocation(t,r,n,a,l,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(F._onLog&&F._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&&(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"),F._onLog&&F._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(F._onLog&&F._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 F._onLog&&F._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;const t=e=>this.dce.getDrawingLayers().some((t=>t.getId()===e));if(!t(3)&&!(null==e?void 0:e.length))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.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(F._onLog&&F._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||this._promiseStartScan)&&this.stopScanning(),this.setImageSource(null);let e=F._nextTaskID++;F._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),F._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}F._jsVersion="9.6.42",F._jsEditVersion="20240426",F._version=`loading...(JS ${F._jsVersion}.${F._jsEditVersion})`,F._license=f,F._sessionPassword=g,F.browserInfo=o,F._workerName=`dbr-${F._jsVersion}.browser.worker.js`,F._engineResourcePath=u,F._licenseServer=[],F._deviceFriendlyName="",F._isShowRelDecodeTimeInResults=!1,F._bWasmDebug=!1,F._bNeverShowDialog=!1,F.__bUseFullFeature=!0,F._nextTaskID=0,F._taskCallbackMap=new Map,F._pLoad=new w,F._lastErrorCode=0,F._lastErrorString="",F._setWarnnedEx=new Set,F._defaultUIElementURL="@engineResourcePath/dbr.ui.html","function"==typeof SuppressedError&&SuppressedError; /*! * Dynamsoft JavaScript Library * @product Dynamsoft Camera Enhancer JS Edition * @website https://www.dynamsoft.com - * @copyright Copyright 2023, Dynamsoft Corporation + * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft - * @version 3.3.9 (js 20231205) + * @version 3.3.10 (js 20240130) * @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),J=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 K=(()=>{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)=>{if(!i)return e;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._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameInputContainer=null,this._clickIptSingleFrameMode=()=>{if(!this._isSingleFrameModeEnabled())return;if(this.getDrawingLayers().some((e=>"editor"==e.getMode())))return;let e;if(this._singleFrameInputContainer)e=this._singleFrameInputContainer.firstElementChild;else{e=document.createElement("input"),e.setAttribute("type","file"),"camera"===this.singleFrameMode?(e.setAttribute("capture",""),e.setAttribute("accept","image/*")):1!=this.singleFrameMode&&"image"!==this.singleFrameMode||(e.removeAttribute("capture"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),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 ue._onLog&&ue._onLog("DCE: _getVideoData(region?) END: "+c),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="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent";const t=document.createElement("div");t.append(e),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.pointerEvents="none",this._elContainer.prepend(t),this._singleFrameInputContainer=t}null==e||e.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._isSingleFrameModeEnabled())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.cameraOpenTimeout=4e3,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._isSingleFrameModeEnabled())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];if(this._video.srcObject.active&&e)if(e.muted&&["iPhone","iPad","Mac"].includes(Y.OS)){if(Y.version>=17)return;this.play()}else this._video.play();else this.play()}}else if("hidden"===document.visibilityState)if(ue._onLog&&ue._onLog("DCE: document hidden."),["iPhone","iPad","Mac"].includes(Y.OS)){if(this._vc_bPlayingVideoBeforeHide=!0,Y.version>=17)return;this._video&&this._video.pause()}else 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._windowResizeListener=()=>{this._windowWidth!==document.documentElement.clientWidth&&(this._windowWidth=document.documentElement.clientWidth,this._updateLayers())},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null,navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this._singleFrameMode=!1:this._singleFrameMode=!0}static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:X,worker:z,getUserMedia:Z,camera:await J(),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(){var e,t;let i,r,n;if(this._isSingleFrameModeEnabled()?(i=this._imgWidth,r=this._imgHeight,n="contain"):(i=null===(e=this._video)||void 0===e?void 0:e.videoWidth,r=null===(t=this._video)||void 0===t?void 0:t.videoHeight,n=this.getVideoFit()),!i||!r)throw new Error("Invalid content dimensions.");return{width:i,height:r,objectFit:n}}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;let t;try{t=this._calculateCvsSize()}catch(e){if("Invalid content dimensions."===(e.message||e))return;throw e}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._isSingleFrameModeEnabled())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);if(!i)return;const 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){if(!e)throw new Error("Invalid 'videoEl'.");if(!t)throw new Error("Invalid 'source'.");return"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,new Promise(((t,r)=>{let n;const s=()=>{e.removeEventListener("loadstart",h),e.removeEventListener("abort",l),e.removeEventListener("play",c),e.removeEventListener("error",u)},o=()=>{n&&clearTimeout(n),s(),t(e)},a=e=>{n&&clearTimeout(n),s(),r(e)},h=()=>{e.addEventListener("abort",l,{once:!0})},l=()=>{const e=new Error("Video playing was interrupted.");e.name="AbortError",a(e)},c=()=>{o()},u=()=>{a(new Error(`Video error ${e.error.code}: ${e.error.message}.`))};e.addEventListener("loadstart",h,{once:!0}),e.autoplay?(e.addEventListener("play",c,{once:!0}),e.addEventListener("error",u,{once:!0})):(e.load(),e.play().then((()=>{o()})).catch((e=>{a(e)}))),i&&(n=setTimeout((()=>{s(),r(new Error("Failed to play video. Timeout."))}),i))}))}static findBestRearCameraInIOS(e){if(!e||!e.length)return null;const t=["back","baksidan","bakre","bak","後置","后置","背面","خلفية","задна","posteriore","posterior","zadní","bagside","rück","πίσω","trasera","taka","arrière","אחורית","बैक","stražnja","hátsó","belakang","aртқы","후면","achterzijde","tylny","traseira","spate","задняя","задней","zadná","านหลัง","arka","sau"],i=["triple","三镜头","三鏡頭","トリプル","ثلاثية","тройна","trojný","τριπλή","kolmois","משולשת","ट्रिपल","trostruka","tiga","tripla","үштік","트리플","trippelt","trippel","trójobiektywowy","triplă","тройная","trojitá","สาม","üçlü","потроєна","ba camera"],r=["dual wide","dual-weitwinkel","dual con gran angular","dual","doble","double","双广角","雙廣角","デュアル広角","مزدوجة عريضة","двойна широкоъгълна","duální širokoúhlý","διπλή ευρεία","laajakulmainen kaksois","כפולה רחבה","ड्युअल वाइड","dvostruka široka","kettős, széles látószögű","ganda","doppia con grandangolo","қос кең бұрышты","듀얼 와이드","dwikamera","dobbelt vidvinkelkamera","dwuobiektywowy","dupla grande-angular","grande angular dupla","dublă","двойная широкоугольная","duálna širokouhlá","dubbel vidvinkel","คู่ด้านหลังมุมกว้าง","çift geniş","здвоєна ширококутна","kép rộng mặt sau"],n=e.filter((e=>{const i=e.label.toLowerCase();return t.some((e=>i.includes(e)))}));if(!n.length)return null;const s=n.find((e=>{const t=e.label.toLowerCase();return i.some((e=>t.includes(e)))}));if(s)return s.deviceId;const o=n.find((e=>{const t=e.label.toLowerCase();return r.some((e=>t.includes(e)))}));return o?o.deviceId:n[0].deviceId}static findBestRearCamera(e){if(!e||!e.length)return null;if(["iPhone","iPad","Mac"].includes(Y.OS))return ue.findBestRearCameraInIOS(e);const t=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","posterior","后面","後面","背面","后置","後置","背置","задней","خلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","taka","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक","задна","aртқы","задняя","bakre","านหลัง"];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}_isSingleFrameModeEnabled(){return 0!=this.singleFrameMode}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,this.cameraOpenTimeout);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._isSingleFrameModeEnabled())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 n;try{this._video&&this._video.srcObject&&this.stop(),ue._onLog&&ue._onLog("DCE: ======before video========");const s=()=>{if(!this._video)throw h&&h.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},o=this.getVideoSettings();let a,h;if("boolean"==typeof o.video&&(o.video={}),e)delete o.video.facingMode,o.video.deviceId={exact:e};else if(o.video.deviceId);else if(this._lastDeviceId)delete o.video.facingMode,o.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&ue.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete o.video.facingMode,o.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&&(o.video.width=e,o.video.height=t)}else if(this.ifSkipCameraInspection);else if(o.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=o.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){a=!0;const e=ue.findBestRearCamera(this._allCameras);e&&(delete o.video.facingMode,o.video.deviceId={exact:e})}}t&&(o.video.width={ideal:t}),i&&(o.video.height={ideal:i}),ue._onLog&&ue._onLog("DCE: ======try getUserMedia========");let l=[0,500],c=null;const u=async e=>{for(let t of l){t&&await new Promise((e=>setTimeout(e,t))),s();try{ue._onLog&&ue._onLog("DCE: ask "+JSON.stringify(e)),h=await navigator.mediaDevices.getUserMedia(e);break}catch(e){if(s(),"NotFoundError"===e.name||"NotAllowedError"===e.name)throw e;c=e,ue._onLog&&ue._onLog("DCE: "+e.message||e)}}s()};let d;if(await u(o),h||(ue._onLog&&ue._onLog("DCE: ======try getUserMedia again========"),d=JSON.parse(JSON.stringify(o)),"object"==typeof d.video&&(["iPhone","iPad"].includes(Y.OS)?(t>=1280||i>=1280?d.video.width=1280:t>=640||i>=640?d.video.width=640:(t<640||i<640)&&(d.video.width=320),delete d.video.height):a&&!o.video.deviceId?(delete d.video.facingMode,this._allCameras.length&&(d.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):d.video=!0),ue._onLog&&ue._onLog("DCE: "+d),await u(d)),h||(l=[1e3,2e3],await u(o)),h||await u(d),!h)throw c;const f=()=>{const e=h.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),s(),a&&!this.ifSkipCameraInspection){f();const e=ue.findBestRearCamera(this._allCameras),t=null===(n=this._currentCamera)||void 0===n?void 0:n.deviceId;e&&e!=t&&(h.getTracks().forEach((e=>{e.stop()})),l=[0,500,1e3,2e3],o.video.deviceId={exact:e},await u(o))}ue._onLog&&ue._onLog("DCE: ======play video========"),s(),await ue.playVideo(this._video,h,this.cameraOpenTimeout),s(),ue._onLog&&ue._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const g="got "+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=g,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),ue._onLog&&ue._onLog("DCE: got "+g),f(),this._renderSelCameraInfo();const _={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(_.deviceId&&(this._lastDeviceId=_.deviceId,this.ifSaveLastUsedCamera&&ue.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),o.video.width&&o.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(o.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(o.video.height))))),!r||!r.notTriggerPlayedEvent){const e=this.mapCameraEvents.get("played");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(_));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return this.promisePlay=null,_}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()}isPaused(){var e;return!this._isSingleFrameModeEnabled()&&!0===(null===(e=this._video)||void 0===e?void 0:e.paused)}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t=17&&e.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),this._video=e;const i=document.createElement("div");i.append(e),i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.width="100%",i.style.height="100%",i.style.overflow="hidden",this._videoContainer=i,t.prepend(i)}else!this._divScanArea&&t.classList.contains("dce-scanarea")?this._divScanArea=t:!this._divScanLight&&t.classList.contains("dce-scanlight")?this._divScanLight=t:!this._bgLoading&&t.classList.contains("dce-bg-loading")?this._bgLoading=t:!this._bgCamera&&t.classList.contains("dce-bg-camera")?this._bgCamera=t:!this._selCam&&t.classList.contains("dce-sel-camera")?this._selCam=t:!this._selRsl&&t.classList.contains("dce-sel-resolution")?(this._selRsl=t,this.videoSrc||this._isSingleFrameModeEnabled()||this._selRsl.options.length||(this._selRsl.innerHTML=[this._optGotRsl?"":'','','',''].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._isSingleFrameModeEnabled()||this.videoSrc?(this._isSingleFrameModeEnabled()&&(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)),this._windowWidth=document.documentElement.clientWidth,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){this._isSingleFrameModeEnabled()?(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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=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._windowResizeListener)}_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._isSingleFrameModeEnabled()&&(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){var t,i;let r="";const n=(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},s=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 o=null===(i=null===(t=this.videoSettings)||void 0===t?void 0:t.video)||void 0===i?void 0:i.deviceId;if(!o)return null;if(r=o.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:o.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!r)return null;let a=this._mapCameraResolutions.get(r);if(a&&!e)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),a=this._mapCameraResolutions.get(r);for(let e of this._predefinedResolutions){const t=await s(r,e.width,e.height);t&&!n(r,t)&&a.push([t.width,t.height])}return a}if(this._currentCamera){r=this._currentCamera.deviceId;let t=this._mapCameraResolutions.get(r);if(t&&!e)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),t=this._mapCameraResolutions.get(r);let i=this._videoTrack;for(let e of this._predefinedResolutions){await i.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const s=i.getSettings(),o={width:s.width,height:s.height};n(r,o)||t.push([o.width,o.height])}return this._video.srcObject.getTracks().forEach((e=>{e.stop()})),await this.play(r,null,null,{notTriggerPlayedEvent:!0}),t}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._isSingleFrameModeEnabled())throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(e,t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(e,t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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 context2d."),m.ctx2d||(m.ctx2d=m.getContext("2d",{willReadFrequently:!0}));const e=m.ctx2d;if(!e)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(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&&ue._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t),ue._onLog&&ue._onLog("DCE: finish fetching a frame into buffer: "+Date.now());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()?(ue._onLog&&ue._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):0===this.refreshInterval&&t()),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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled()&&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)}transformCoord(e){if(!this.isOpen())throw new Error("Unavailable when the camera is not open.");if(this._isSingleFrameModeEnabled()&&!this._cvsSingleFrameMode)throw new Error("No image is selected. ");const t=this._elContainer.getBoundingClientRect();let i,r,n,s,o,a=t.left,h=t.top,l=a+window.scrollX,c=h+window.scrollY;this._isSingleFrameModeEnabled()?(i=this._cvsSingleFrameMode.width,r=this._cvsSingleFrameMode.height,n=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).width),s=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,r=this.video.videoHeight,n=parseFloat(window.getComputedStyle(this._elContainer).width),s=parseFloat(window.getComputedStyle(this._elContainer).height),o=this.videoFit);const u=n/s,d=i/r;let f,g,_,p,m=1;if("contain"===o)u({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))}var pe,me,ve,ye,Se,be,we,Ce,xe,Te,Ie,Ee,Oe,Ae,De,Re,Me,Le,Fe,Pe,ke,Be,Ne,je,Ve,Ue,Ge,We;class He extends F{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._onPlayed=null}static set _onLog(e){!function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?n.call(e,i):n?n.value=i:t.set(e,i)}(He,pe,e,"f",me),ue._onLog=e}static get _onLog(){return function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)}(He,pe,"f",me)}static get version(){return this._version+`(DCE ${ue.getVersion()})`}static _fireHTTPSWarnning(){He.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{He.onWarning&&He.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){if("boolean"!=typeof e&&!["image","camera"].includes(e))throw new Error("Invalid value.");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||(F._onLog&&F._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(F.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,p.IPF_GrayScaled,0,d);else if("rgba"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,p.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,p.IPF_ARGB_8888,0,d)}if(await this.clearMapDecodeRecord(),F.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){const t=new He;t._instanceID=await He.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(He.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),He._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(!F._bUseFullFeature){if(0!=(t.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.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=F._nextTaskID++;F._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)}})),F._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 F._onLog&&F._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));F._onLog&&F._onLog("======= once read ======="),F._onLog&&(this._timeStartDecode=Date.now());const e=this._getVideoFrame();if(!e)return F._onLog&&F._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,p.IPF_GrayScaled,0,d);else if("rgba"===h)t=await this._decodeBuffer_Uint8Array(i,s,o,a,p.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,p.IPF_ARGB_8888,0,d)}if(F.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=async()=>new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!1}})})),t=await e(),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},a=e=>{if(!e)return null;const t={};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!=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)))},_=[];for(let t of e){if(t.resultType!==S.IRT_TYPED_BARCODE_ZONE)continue;const e=t.scaleDownRatio;for(let a of t.results){if(!a)continue;const t={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};i(t,r,n,c,u,s,o),g(f,t)&&_.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==y.BF_QR_CODE||e.barcodeFormat==y.BF_DATAMATRIX));if(r.length||(r=e.filter((e=>e.barcodeFormat==y.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=h.x3-h.x1,t=h.y3-h.y1;h.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 t=(1-this.autoZoomTargetBorder)/2;const a=h.x1/c,l=(c-h.x3)/c,d=h.y1/u,f=(u-h.y3)/u;if(a>e&&l>e&&d>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-a),(.5-t)/(.5-l),(.5-t)/(.5-d),(.5-t)/(.5-f)].filter((e=>e>0)),i=Math.min(...e,this.autoZoomInIdealModuleSize/h.result.moduleSize),r=this.dce.getZoomSettings().factor;let n=Math.max(Math.pow(r*i,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);n=Math.min(n,i);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){i(h,r,n,c,u,s,o);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-a),(.5-t)/(.5-l),(.5-t)/(.5-d),(.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,r,n,c,u,s,o),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 t})().then((e=>{if(F._onLog&&F._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,F._onLog&&F._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&&(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){F._onLog&&F._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 F._onLog&&F._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._drawResults(null),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()}convertToPageCoordinates(e){return this.dce.convertToPageCoordinates(e)}convertToClientCoordinates(e){return this.dce.convertToClientCoordinates(e)}destroyContext(){this.close(),this.dce&&this.dce.dispose(!1),this.bDestroyed||super.destroyContext()}}pe=He,me={value:void 0},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"}(ve||(ve={})),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"}(ye||(ye={})),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=-1]="BF2_ALL"}(Se||(Se={})),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"}(be||(be={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(we||(we={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(Ce||(Ce={})),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"}(xe||(xe={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(Te||(Te={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(Ie||(Ie={})),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"}(Ee||(Ee={})),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"}(Oe||(Oe={})),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"}(De||(De={})),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"}(Re||(Re={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(Me||(Me={})),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"}(Le||(Le={})),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"}(Fe||(Fe={})),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"}(Pe||(Pe={})),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"}(ke||(ke={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(Be||(Be={})),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"}(Ne||(Ne={})),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"}(je||(je={})),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"}(Ve||(Ve={})),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"}(Ue||(Ue={})),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"}(Ge||(Ge={})),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"}(We||(We={}));export{F as BarcodeReader,He as BarcodeScanner,ve as EnumBarcodeColourMode,ye as EnumBarcodeComplementMode,y as EnumBarcodeFormat,Se as EnumBarcodeFormat_2,be as EnumBinarizationMode,we as EnumClarityCalculationMethod,Ce as EnumClarityFilterMode,xe as EnumColourClusteringMode,Te as EnumColourConversionMode,Ie as EnumConflictMode,Ae as EnumDPMCodeReadingMode,Ee as EnumDeblurMode,Oe as EnumDeformationResistingMode,m as EnumErrorCode,De as EnumGrayscaleTransformationMode,v as EnumIMResultDataType,p as EnumImagePixelFormat,Re as EnumImagePreprocessingMode,Me as EnumIntermediateResultSavingMode,S as EnumIntermediateResultType,Le as EnumLocalizationMode,Fe as EnumPDFReadingMode,Pe as EnumQRCodeErrorCorrectionLevel,ke as EnumRegionPredetectionMode,Be as EnumResultCoordinateType,Ne as EnumResultType,je as EnumScaleUpMode,Ve as EnumTerminatePhase,Ue as EnumTextFilterMode,Ge as EnumTextResultOrderMode,We as EnumTextureDetectionMode}; + */ +const P="undefined"==typeof self;let k,B,N,j,V;if("undefined"!=typeof navigator&&(k=navigator,B=k.userAgent,N=k.platform,j=k.mediaDevices),!P){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:k.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 i="unknownBrowser",r=0,n="unknownOS";for(let t in e){const n=e[t]||{};let s=n.str||B,o=n.search||t,a=n.verStr||B,l=n.verSearch||t;if(l instanceof Array||(l=[l]),-1!=s.indexOf(o)){i=t;for(let e of l){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||B,s=i.search||e;if(-1!=r.indexOf(s)){n=e;break}}"Linux"==n&&-1!=B.indexOf("Windows NT")&&(n="HarmonyOS"),V={browser:i,version:r,OS:n}}P&&(V={browser:"ssr",version:0,OS:"ssr"});const U="undefined"!=typeof WebAssembly&&B&&!(/Safari/.test(B)&&!/Chrome/.test(B)&&/\(.+\s11_2_([2-6]).*\)/.test(B)),G=!("undefined"==typeof Worker),W=!(!j||!j.getUserMedia),H=async()=>{let e=!1;if(W)try{(await j.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===V.browser&&V.version>66||"Safari"===V.browser&&V.version>13||"OPR"===V.browser&&V.version>43||"Edge"===V.browser&&V.version;const Y=(()=>{if(!P&&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"./"})();var X={653:(e,t,i)=>{var r,n,s,o,a,l,h,c,u,d,f,g,_,p,m,v,y,S,b,w,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 E(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 l=new ImageData(a,r,n);i.putImageData(l,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,l=Math.PI/2,x.util={cos:function(e){if(0===e)return 1;switch(e<0&&(e=-e),e/l){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/l){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,l){var h,c,u=new x.Point(a.x,a.y);0===l?(c=e[l+1],h=i?o(x.util.createVector(c,u)).addEquals(u):e[e.length-1]):l===e.length-1?(h=e[l-1],c=i?o(x.util.createVector(h,u)).addEquals(u):e[0]):(h=e[l-1],c=e[l+1]);var d,f,g=x.util.getBisector(u,h,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],l=i[4],h=i[5],c=function(e,t,i,s,o,a,l){var h=Math.PI,c=l*h/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=_*_,b=m*v-m*y-v*S,w=0;if(b<0){var C=Math.sqrt(1-b/(m*v));i*=C,s*=C}else w=(o===a?-1:1)*Math.sqrt(b/(m*y+v*S));var T=w*i*p/s,I=-w*s*_/i,E=d*T-u*I+.5*e,O=u*T+d*I+.5*t,A=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*h:1===a&&D<0&&(D+=2*h);for(var R=Math.ceil(Math.abs(D/h*2)),M=[],L=D/R,F=8/3*Math.sin(L/4)*Math.sin(L/4)/Math.sin(L/2),P=A+L,k=0;kw)for(var T=1,I=_.length;T2;for(t=t||0,h&&(a=e[2].xe[i-2].x?1:n.x===e[i-2].x?0:-1,l=n.y>e[i-2].y?1:n.y===e[i-2].y?0:-1),r.push(["L",n.x+a*t,n.y+l*t]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(t,i,r,n,s,o,a,l){var h;if(x.cachesBoundsOfCurve&&(h=e.call(arguments),x.boundsOfCurveCache[h]))return x.boundsOfCurveCache[h];var c,u,d,f,g,_,p,m,v=Math.sqrt,y=Math.min,S=Math.max,b=Math.abs,w=[],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*l,d=3*n-3*i),b(c)<1e-12){if(b(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,A=w.length,D=A;A--;)I=(O=1-(f=w[A]))*O*O*t+3*O*O*f*r+3*O*f*f*s+f*f*f*a,C[0][A]=I,E=O*O*O*i+3*O*O*f*n+3*O*f*f*o+f*f*f*l,C[1][A]=E;C[0][D]=t,C[1][D]=i,C[0][D+1]=a,C[1][D+1]=l;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[h]=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=l(s),n=s,(r=o(h.x,h.y,i.x,i.y))+a>t?(s-=c,c/=2):(h=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 l=0,h=o.length;l-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},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!n)return o;for(var h in l)o[l[h]]+=parseInt(t(e,h),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,l=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,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(s),a((function(e){var t,h=e||+new Date,c=i.duration||500,u=h+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-h,n=r/c,S=p?m.map((function(e,t){return _(r,m[t],y[t],c)})):_(r,m,y,c),b=p?Math.abs((S[0]-m[0])/y[0]):Math.abs((S-m)/y);if(s.currentValue=p?S.slice():S,s.completionRate=b,s.durationRate=n,!o){if(!f(S,b,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 l()):(d(S,b,n),void a(e));l()}}(h)})),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,l=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(l){if(Array.isArray(t))return l(e(t,t,0),i,r);l(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=l?i.map(s):s(i,n)}}else i="";return!l&&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;)l.shift(),h=t.util.multiplyTransformMatrices(h,l[0]);return h}}();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,l,h=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=!h||!(h=h.match(v)),y=!d||!f||"100%"===d||"100%"===f,S=m&&y,b={},w="",C=0,x=0;if(b.width=0,b.height=0,b.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 b;if(m)return b.width=s(d),b.height=s(f),b;if(i=-parseFloat(h[1]),r=-parseFloat(h[2]),n=parseFloat(h[3]),o=parseFloat(h[4]),b.minX=i,b.minY=r,b.viewBoxWidth=n,b.viewBoxHeight=o,y?(b.width=n,b.height=o):(b.width=s(d),b.height=s(f),c=b.width/n,u=b.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=b.width-n*c,x=b.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 b;if((g||_)&&"#document"!==e.parentNode.nodeName&&(w=" translate("+s(g)+" "+s(_)+") "),a=w+" matrix("+c+" 0 0 "+u+" "+(i*c+C)+" "+(r*u+x)+") ","svg"===e.nodeName){for(l=e.ownerDocument.createElementNS(t.svgNS,"g");e.firstChild;)l.appendChild(e.firstChild);e.appendChild(l)}else(l=e).removeAttribute("x"),l.removeAttribute("y"),a=l.getAttribute("transform")+a;return l.setAttribute("transform",a),b}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),l=(r.x-e.x)*(e.y-n.y)-(r.y-e.y)*(e.x-n.x),h=(s.y-n.y)*(r.x-e.x)-(s.x-n.x)*(r.y-e.y);if(0!==h){var c=a/h,u=l/h;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===l?"Coincident":"Parallel");return o},t.Intersection.intersectLinePolygon=function(e,t,r){var n,s,o,a,l=new i,h=r.length;for(a=0;a0&&(l.status="Intersection"),l},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),l=new t.Point(s.x,o.y),h=i.intersectLinePolygon(s,a,e),c=i.intersectLinePolygon(a,o,e),u=i.intersectLinePolygon(o,l,e),d=i.intersectLinePolygon(l,s,e),f=new i;return f.appendPoints(h.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]),l=t.util.array.min([e,i,r]);if(o=(a+l)/2,a===l)n=s=0;else{var h=a-l;switch(s=o>.5?h/(2-a-l):h/(a+l),a){case e:n=(i-r)/h+(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===h&&e.originY===h}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),l=e(t,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),l}}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 b(e,i,r,n,s){var o=e.target,a=o.controls[e.corner],l=o.canvas.getZoom(),h=o.padding/l,c=o.toLocalPoint(new t.Point(n,s),i,r);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=a.offsetX,c.y-=a.offsetY,c}function w(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,h=t.target,c=h._getTransformedDimensions(0,h.skewY),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.x)-c.x,g=h.skewX;f<2?n=0:(n=u(Math.atan2(f/h.scaleX,c.y/h.scaleY)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().y;h.set("skewX",n),C(h,"skewY","scaleY","y",p)}return _}function T(e,t,i,r){var n,h=t.target,c=h._getTransformedDimensions(h.skewX,0),d=b(t,t.originX,t.originY,i,r),f=Math.abs(2*d.y)-c.y,g=h.skewY;f<2?n=0:(n=u(Math.atan2(f/h.scaleY,c.x/h.scaleX)),t.originX===s&&t.originY===l&&(n=-n),t.originX===a&&t.originY===o&&(n=-n),w(h)&&(n=-n));var _=g!==n;if(_){var p=h._getTransformedDimensions().x;h.set("skewY",n),C(h,"skewX","scaleX","x",p)}return _}function I(e,t,i,r,n){n=n||{};var s,o,a,l,h,u,f=t.target,g=f.lockScalingX,v=f.lockScalingY,y=n.by,S=_(e,f),w=m(f,y,S),C=t.gestureScale;if(w)return!1;if(C)o=t.scaleX*C,a=t.scaleY*C;else{if(s=b(t,t.originX,t.originY,i,r),h="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,t.signX||(t.signX=h),t.signY||(t.signY=u),f.lockScalingFlip&&(t.signX!==h||t.signY!==u))return!1;if(l=f._getTransformedDimensions(),S&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=t.original,I=x/(Math.abs(l.x*T.scaleX/f.scaleX)+Math.abs(l.y*T.scaleY/f.scaleY));o=T.scaleX*I,a=T.scaleY*I}else o=Math.abs(s.x*f.scaleX/l.x),a=Math.abs(s.y*f.scaleY/l.y);p(t)&&(o*=2,a*=2),t.signX!==h&&"y"!==y&&(t.originX=c[t.originX],o*=-1,t.signX=h),t.signY!==u&&"x"!==y&&(t.originY=c[t.originY],a*=-1,t.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}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,l=Math.atan2(n.ey-o.y,n.ex-o.x),h=Math.atan2(r-o.y,i-o.x),c=u(h-l+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(l)&&(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=b(t,h,h,i,r).y>0?o:l:(c>0&&(n=u===s?o:l),c<0&&(n=u===s?l:o),w(a)&&(n=n===o?l: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,l=!n.get("lockMovementY")&&n.top!==o;return a&&n.set("left",s),l&&n.set("top",o),(a||l)&&g("moving",v(e,t,i,r)),a||l},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=b,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,l=void 0!==r.transparentCorners?r.transparentCorners:n.transparentCorners,h=l?"stroke":"fill",c=!l&&(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[h](),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,l=void 0!==n.transparentCorners?n.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(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[h+"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,l,h,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),l=f*t.util.cos(_),h=f*t.util.sin(_)}else f=.7071067812*(c&&u?c:i),g=t.util.degreesToRadians(45-e),o=l=f*t.util.cos(g),a=h=f*t.util.sin(g);return{tl:{x:r-h,y:n-l},tr:{x:r+o,y:n-a},bl:{x:r-o,y:n+a},br:{x:r+h,y:n+l}}},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 l=o.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),s=l.length;s--;){var h=l[s].split(/\s*:\s*/),c=h[0].trim(),u=h[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),l=(i=i||{},t(this.colorStops,!0)),h=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(l.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(h)for((l=l.concat()).reverse(),r=0,n=l.length;r0){var p=_/Math.max(a.r1,a.r2);for(r=0,n=l.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,l,h,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)),l=c.length;l--;)f.push(e(c[l],s));return h=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:h,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,l=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 l;if(e.style||(e.style={}),void 0===e.getContext)throw l;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,l="",h={},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",l,"","\n"].join("")),l},_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+h&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),h++;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,l=this._activeObject,h=0;if(e===l&&"activeSelection"===e.type)for(r=(a=l._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,l=this.viewportTransform;return e.selectionBackgroundColor="",this.clearContext(o),o.save(),o.transform(l[0],l[1],l[2],l[3],l[4],l[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,l=this._getActionFromCorner(r,s,e,i),h=this._getOriginFromCorner(i,s),c=e[this.centeredKey],u={target:i,action:l,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:h.x,originY:h.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,l,c)&&(u.originX="center",u.originY="center"),u.original.originX=h.x,u.original.originY=h.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),l=Math.max(r.x,s.x),h=Math.max(r.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(o,a,l-o,h-a)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,o+=c,a+=c,l-=c,h-=c,x.Object.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(o,a,l-o,h-a))},findTarget:function(e,t){if(!this.skipTargetFind){var r,n,s=this.getPointer(e,!0),o=this._activeObject,a=this.getActiveObjects(),l=i(e),h=a.length>1&&!t||1===a.length;if(this.targets=[],h&&o._findTargetCorner(s,l))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,l=o.height||0;a&&l||("top"in o&&"bottom"in o&&(l=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 h=this.getRetinaScaling();return 1!==h&&(n.x/=h,n.y/=h),r=0===a||0===l?{width:1,height:1}:{width:s.width/a,height:s.height/l},{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 l,h;if(t){if(l=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[l],u=c&&c.getMouseUpHandler(e,t,c);u&&u(e,i,(h=this.getPointer(e)).x,h.y)}t.isMoving=!1}if(i&&(i.target!==t||i.corner!==l)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(e,t,c);h=h||this.getPointer(e),f&&f(e,i,h.x,h.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)),l=new x.Point(y(r,s),y(n,o)),h=!this.selectionFullyContained,c=r===s&&n===o,u=this._objects.length;u--&&!((t=this._objects[u])&&t.selectable&&t.visible&&(h&&t.intersectsWithRect(a,l,!0)||t.isContainedWithinRect(a,l,!0)||h&&t.containsPoint(a,null,!0)||h&&t.containsPoint(l,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,l=this.viewportTransform,h=(l[4]-(t.left||0))*e,c=(l[5]-(t.top||0))*e,u=this.interactive,d=[a,0,0,a,h,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=l,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()),l=t.minCacheSideLimit,h=a.width,c=a.height,u=a.zoomX,d=a.zoomY,f=h!==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,b=h>y||c>S;v=b||(h<.9*y||c<.9*S)&&y>l&&S>l,b&&!a.capped&&(h>l||c>l)&&(p=.1*h,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(h+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=h,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(),l=this.calcTransformMatrix();n=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,l=t.util.multiplyTransformMatrices(a,l),r=t.util.qrDecompose(l),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,l=n.y/this.scaleY/o;s.width=a,s.height=l,(r=s.getContext("2d")).beginPath(),r.moveTo(0,0),r.lineTo(a,0),r.lineTo(a,l),r.lineTo(0,l),r.closePath(),r.translate(a/2,l/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 l,h,c,u,d=t.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,_={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),_.x=2*Math.round(o(g.offsetX)+h)*o(l.scaleX),_.y=2*Math.round(o(g.offsetY)+h)*o(l.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,b={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,l=e.x,h=e.y;return"string"==typeof t?t=b[t]:t-=.5,"string"==typeof r?r=b[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(),l=e.x+s*a.x,h=e.y+o*a.y),new x.Point(l,h)},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?b[this.originX]:this.originX-.5,i="string"==typeof e?b[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()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],_=e.indexOf("COMMON_PARTS"),p=t.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+x.Object.__uid++,r='\n'+l.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,h,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)),l&&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;l--)if(n=a[l],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,l=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,-l/2,a,l),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 l={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(l.startValue,l.endValue,l.duration,l):x.util.animate(l)}}),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,l=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 l: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,l=.4477152502;e.beginPath(),e.moveTo(s+t,o),e.lineTo(s+r-t,o),a&&e.bezierCurveTo(s+r-l*t,o,s+r,o+l*i,s+r,o+i),e.lineTo(s+r,o+n-i),a&&e.bezierCurveTo(s+r,o+n-l*i,s+r-l*t,o+n,s+r-t,o+n),e.lineTo(s+t,o+n),a&&e.bezierCurveTo(s+l*t,o+n,s,o+n-l*i,s,o+n-i),e.lineTo(s,o+i),a&&e.bezierCurveTo(s,o+l*i,s+l*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,l=0,h=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_'+l+')" '}if(this.imageSmoothing||(a='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,e=["\t\n'],this.fill=h}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,l=s.width,h=s.height;o.width=l,o.height=h,this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=n,x.filterBackend.applyFilters([e],s,l,h,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,l=a(this.cropX,0),h=a(this.cropY,0),c=t.naturalWidth||t.width,u=t.naturalHeight||t.height,d=l*i,f=h*r,g=o(n*i,c-d),_=o(s*r,u-f),p=-n/2,m=-s/2,v=o(n,c/i-l),y=o(s,u/r-h);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,l=0,h=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&&(l=e/2),"Max"===t.alignX&&(l=e),e=r-u/s,"Mid"===t.alignY&&(h=e/2),"Max"===t.alignY&&(h=e),i=c/n,r=u/s)),{width:i,height:r,scaleX:n,scaleY:s,offsetLeft:o,offsetTop:a,cropX:l,cropY:h}}}),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=E);var l,h,c={imageBuffer:a,destinationWidth:e,destinationHeight:t,targetCanvas:o};o.width=e,o.height=t,l=window.performance.now(),I.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),E.call(c,this.gl,c),h>window.performance.now()-l?(this.imageBuffer=a,this.copyGLTo2D=E):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 l={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},h=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,h),e.forEach((function(e){e&&e.applyTo(l)})),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)}(l),this.copyGLTo2D(a,l),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(l.sourceTexture),a.deleteTexture(l.targetTexture),a.deleteFramebuffer(h),n.getContext("2d").setTransform(1,0,0,1,0,0),l},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,l=this.matrix,h=this.colorsOnly;for(s=0;s=S||o<0||o>=y||(l=4*(a*y+o),h=p[f*m+d],t+=_[l]*h,i+=_[l+1]*h,r+=_[l+2]*h,C||(n+=_[l+3]*h));w[s]=t,w[s+1]=i,w[s+2]=r,w[s+3]=C?_[s+3]:n}e.imageData=b},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;th[0]&&n>h[1]&&s>h[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,l,h=e.imageData.data,c=h.length,u=1-this.alpha;i=(l=new t.Color(this.color).getSource())[0]*this.alpha,r=l[1]*this.alpha,n=l[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,l=o(s*i),h=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(e,s,a,l,h):"hermite"===this.resizeType?n=this.hermiteFastResize(e,s,a,l,h):"bilinear"===this.resizeType?n=this.bilinearFiltering(e,s,a,l,h):"lanczos"===this.resizeType&&(n=this.lanczosResize(e,s,a,l,h)),e.imageData=n},sliceByTwo:function(e,i,n,s,o){var a,l,h=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-b.x)),S[M]||(S[M]={});for(var F=w.y-y;F<=w.y+y;F++)F<0||F>=o||(L=r(1e3*s(F-b.y)),S[M][L]||(S[M][L]=f(n(i(M*p,2)+i(L*m,2))/1e3)),(T=S[M][L])>0&&(E+=T,O+=T*c[I=4*(F*t+x)],A+=T*c[I+1],D+=T*c[I+2],R+=T*c[I+3]))}d[I=4*(C*a+l)]=O/E,d[I+1]=A/E,d[I+2]=D/E,d[I+3]=R/E}return++l1&&L<-1||(y=2*L*L*L-3*L*L+1)>0&&(T+=y*f[3+(M=4*(R+E*t))],b+=y,f[M+3]<255&&(y=y*f[M+3]/250),w+=y*f[M],C+=y*f[M+1],x+=y*f[M+2],S+=y)}_[v]=w/S,_[v+1]=C/S,_[v+2]=x/S,_[v+3]=T/b}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,l=e.fillStyle,h=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:l,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):{},l=this._measureChar(e,o,r,a),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),h+=s);var u={width:c,left:0,height:o.fontSize,kernedWidth:h,deltaY:o.deltaY};if(i>0&&!n){var d=this.__charBounds[t][i-1];u.left=d.left+d.width+l.kernedWidth-l.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 E=v+s+u;"rtl"===this.direction&&(E=this.width-E-d),h&&m&&(e.fillStyle=m,e.fillRect(E,c+w*r+o,d,this.fontSize/15)),u=f.left,d=f.width,h=g,m=p,r=n,o=a}else d+=f.kernedWidth;E=v+s+u,"rtl"===this.direction&&(E=this.width-E-d),e.fillStyle=p,g&&p&&e.fillRect(E,c+w*r+o,d-b,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 l=0;l0?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,l=e.topOffset,h=this.getValueOfPropertyAt(r,n,"deltaY");l+=(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,l+e.top+h,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,l=o.lineIndex,h=s.charIndex<0?0:s.charIndex,c=o.charIndex<0?0:o.charIndex,u=a;u<=l;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),_=0,p=0;if(u===a&&(_=this.__charBounds[a][h].left),u>=a&&u1)&&(g/=this.lineHeight);var v=e.left+f+_,y=p-_,S=g,b=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,b=g):t.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),t.fillRect(v,e.top+e.topOffset+b,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(),l={x:t.left+o,y:t.top+t.topOffset+s},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/h,d=c.height/h,f=u-s,g=d-s,_=c.clientWidth/u,p=c.clientHeight/d;return l=x.util.transformPoint(l,a),(l=x.util.transformPoint(l,this.canvas.viewportTransform)).x*=_,l.y*=p,l.x<0&&(l.x=0),l.x>f&&(l.x=f),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.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,l=s.lineIndex,h=s.charIndex;if(o!==l){if(this.styles[o])for(i=a;i=h&&(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 l in i||(i=1),this.shiftLineStyles(e,i),this.styles[e]&&(n=this.styles[e][0===t?t:t-1]),this.styles[e]){var h=parseInt(l,10);h>=t&&(o=!0,s[h-t]=this.styles[e][l],a&&0===t||delete this.styles[e][l])}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 l=n[t?t-1:1];l&&i--;)this.styles[e][t+i]=C(l)},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,l=0,h=this._textLines.length;l0&&(o+=this._textLines[l-1].length+this.missingNewlineOffset(l-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,l=this._text.length,h=a.length,c=h-l,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):h0&&(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),l=this._textLines[n].slice(0,s),h=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-l.length+(1-h)},_getIndexOnLine:function(e,t){for(var i,r,n=this._textLines[e],s=this._getLineLeftOffset(e),o=0,a=0,l=n.length;at){r=!0;var h=s-i,c=s,u=Math.abs(h-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,l,h=this.getHeightOfLine(t),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[t];r+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,_=f.length-1;g<=_;g++)l=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&&!l&&this._reSpaceAndTab.test(f[g])&&(l=!0),l||(n=n||this.getCompleteStyleDeclaration(t,g),s=this.getCompleteStyleDeclaration(t,g+1),l=this._hasStyleChangedForSvg(n,s)),l&&(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,l=0,h=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 l in i[a])if(l>=r&&(!n||lr&&!p?(a.push(l),l=[],s=f,p=!0):s+=m,p||o||l.push(d),l=l.concat(c),g=o?0:this._measureWord([d],i,u),u++,p=!1,f>_&&(_=f);return v&&a.push(l),_+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:()=>{}},z={};function Z(e){var t=z[e];if(void 0!==t)return t.exports;var i=z[e]={exports:{}};return X[e](i,i.exports,Z),i.exports}Z.d=(e,t)=>{for(var i in t)Z.o(t,i)&&!Z.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},Z.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var J={};(()=>{let e;Z.d(J,{R:()=>e}),e="undefined"!=typeof document&&"undefined"!=typeof window?Z(653).fabric:{version:"5.2.1"}})();var K=J.R;class q{get mediaType(){return this._mediaType}get drawingLayerId(){return this._drawingLayerId}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}_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,l=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,h=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),c=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),u=h/c,d=a/l,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 K.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=K.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"===h?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}},K.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();K.util.addListener(K.document,"touchend",this._onTouchEnd,{passive:!1}),K.util.addListener(K.document,"touchmove",this._onMouseMove,{passive:!1}),K.util.removeListener(i,r+"down",this._onMouseDown)},K.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,l=[],h=[],c=a?K.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?(l.push(h),h=[],o=g,m=!0):o+=v,m||a||h.push(f),h=h.concat(u),_=a?0:this._measureWord([f],t,d),d++,m=!1,g>p&&(p=g);return y&&l.push(h),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),l});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 K.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 le{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 le.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 le.multiply(e,[i,-r,0,r,i,0,0,0,1])}static scale(e,t,i){return le.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 ce=(e,t,i,r)=>{if(!i)return e;let n=t+Math.round((e-t)/i)*i;return r&&(n=Math.min(n,r)),n};class ue{static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:U,worker:G,getUserMedia:W,camera:await H(),browser:V.browser,version:V.version,OS:V.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="./"),!P){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(){var e,t;let i,r,n;if(this._isSingleFrameModeEnabled()?(i=this._imgWidth,r=this._imgHeight,n="contain"):(i=null===(e=this._video)||void 0===e?void 0:e.videoWidth,r=null===(t=this._video)||void 0===t?void 0:t.videoHeight,n=this.getVideoFit()),!i||!r)throw new Error("Invalid content dimensions.");return{width:i,height:r,objectFit:n}}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;let t;try{t=this._calculateCvsSize()}catch(e){if("Invalid content dimensions."===(e.message||e))return;throw e}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,l=o.dHeight;e.width==a&&e.height==l||(e.width=a,e.height=l);const h=window.getComputedStyle(this._elContainer),c=parseFloat(h.width),u=parseFloat(h.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._isSingleFrameModeEnabled())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);if(!i)return;const 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,l=this._decoratorArea.width/100*r,h=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(l),Math.round(h)),s.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),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(l+s.lineWidth),Math.round(h+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(l),Math.round(h)),s.fillStyle=this._viewDecoratorInfo.focus.fillStyle,s.fillRect(Math.round(o),Math.round(a),Math.round(l),Math.round(h)),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._drawingLayerManager=new oe,t}static async playVideo(e,t,i){if(!e)throw new Error("Invalid 'videoEl'.");if(!t)throw new Error("Invalid 'source'.");return new Promise((async(r,n)=>{let s;const o=()=>{e.removeEventListener("loadstart",c),e.removeEventListener("abort",u),e.removeEventListener("play",d),e.removeEventListener("error",f),e.removeEventListener("loadedmetadata",p)};let a=!1;const l=()=>{a=!0,s&&clearTimeout(s),o(),r(e)},h=e=>{s&&clearTimeout(s),o(),n(e)},c=()=>{e.addEventListener("abort",u,{once:!0})},u=()=>{const e=new Error("Video playing was interrupted.");e.name="AbortError",h(e)},d=()=>{l()},f=()=>{h(new Error(`Video error ${e.error.code}: ${e.error.message}.`))};let g;const _=new Promise((e=>{g=e})),p=()=>{g()};if(e.addEventListener("loadstart",c,{once:!0}),e.addEventListener("play",d,{once:!0}),e.addEventListener("error",f,{once:!0}),e.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,e.autoplay&&await new Promise((e=>{setTimeout(e,1e3)})),!a){i&&(s=setTimeout((()=>{o(),n(new Error("Failed to play video. Timeout."))}),i));try{e.src&&await e.load(),await e.play(),l()}catch(e){console.warn("1st play error: "+((null==e?void 0:e.message)||e))}if(!a){await _;try{await e.play(),l()}catch(e){console.warn("2rd play error: "+((null==e?void 0:e.message)||e)),h(e)}}}}))}static findBestRearCameraInIOS(e){if(!e||!e.length)return null;const t=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],r=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],n=e.filter((e=>{const i=e.label.toLowerCase();return t.some((e=>i.includes(e)))}));if(!n.length)return null;const s=n.find((e=>{const t=e.label.toLowerCase();return i.some((e=>t.includes(e)))}));if(s)return s.deviceId;const o=n.find((e=>{const t=e.label.toLowerCase();return r.some((e=>t.includes(e)))}));return o?o.deviceId:n[0].deviceId}static findBestRearCamera(e){if(!e||!e.length)return null;if(["iPhone","iPad","Mac"].includes(V.OS))return ue.findBestRearCameraInIOS(e);const t=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];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(V.OS)?e[e.length-1].deviceId:null}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._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameInputContainer=null,this._clickIptSingleFrameMode=()=>{if(!this._isSingleFrameModeEnabled())return;if(this.getDrawingLayers().some((e=>"editor"==e.getMode())))return;let e;if(this._singleFrameInputContainer)e=this._singleFrameInputContainer.firstElementChild;else{e=document.createElement("input"),e.setAttribute("type","file"),"camera"===this.singleFrameMode?(e.setAttribute("capture",""),e.setAttribute("accept","image/*")):1!=this.singleFrameMode&&"image"!==this.singleFrameMode||(e.removeAttribute("capture"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),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.src=i,n.onload=()=>{URL.revokeObjectURL(n.src),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()),l={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},h=this._getImageData(e,r,n,s,null,{pixelFormat:a});if(!h)return null;const c=Date.now();return ue._onLog&&ue._onLog("DCE: _getVideoData(region?) END: "+c),l.data=h.data,l.pixelFormat=l.colorMode=h.pixelFormat,l._bUseWebGL=h._bUseWebGL,l.timeSpent=c-t,l.timeStamp=c,h.pixelFormat===he.GREY?l.stride=l.width:l.stride=4*l.width,l};(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="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent";const t=document.createElement("div");t.append(e),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.pointerEvents="none",this._elContainer.prepend(t),this._singleFrameInputContainer=t}null==e||e.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._isSingleFrameModeEnabled())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,l=this._elContainer.getBoundingClientRect(),h=l.left,c=l.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-h)/p,n=(i-c-(f-d/_)/2)/p):(p=f/a,n=(i-c)/p,r=(t-h-(d-f*_)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");_>g?(p=f/a,n=(i-c)/p,r=(t-h+(f*_-d)/2)/p):(p=d/o,r=(t-h)/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.cameraOpenTimeout=4e3,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=()=>{this._isSingleFrameModeEnabled()||("visible"===document.visibilityState?(ue._onLog&&ue._onLog("DCE: document visible."),this._video&&this._bOpen&&(async()=>{let e=!1;if(this._video.paused){ue._onLog&&ue._onLog("document visible. Not auto resume. 1st resume start.");try{await this._video.play(),e=!0}catch(e){ue._onLog&&ue._onLog("document visible. 1st resume video failed, try open instead.")}e||await this.play()}if(await new Promise((e=>setTimeout(e,300))),this._video.paused){ue._onLog&&ue._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this._video.play(),e=!0}catch(e){ue._onLog&&ue._onLog("document visible. 2rd resume video failed, try open instead.")}e||await this.play()}})()):"hidden"===document.visibilityState&&(ue._onLog&&ue._onLog("DCE: document hidden."),this._video&&this._bOpen&&(this._video.paused||this.pause())))},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._windowResizeListener=()=>{this._windowWidth!==document.documentElement.clientWidth&&(this._windowWidth=document.documentElement.clientWidth,this._updateLayers())},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null,navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this._singleFrameMode=!1:this._singleFrameMode=!0}_isSingleFrameModeEnabled(){return 0!=this.singleFrameMode}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,this.cameraOpenTimeout);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._isSingleFrameModeEnabled())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 n;try{this._video&&this._video.srcObject&&this.stop(),ue._onLog&&ue._onLog("DCE: ======before video========");const s=()=>{if(!this._video)throw l&&l.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},o=this.getVideoSettings();let a,l;if("boolean"==typeof o.video&&(o.video={}),e)delete o.video.facingMode,o.video.deviceId={exact:e};else if(o.video.deviceId);else if(this._lastDeviceId)delete o.video.facingMode,o.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&ue.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete o.video.facingMode,o.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&&(o.video.width=e,o.video.height=t)}else if(this.ifSkipCameraInspection);else if(o.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=o.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){a=!0;const e=ue.findBestRearCamera(this._allCameras);e&&(delete o.video.facingMode,o.video.deviceId={exact:e})}}t&&(o.video.width={ideal:t}),i&&(o.video.height={ideal:i}),ue._onLog&&ue._onLog("======try getUserMedia========");let h=[0,500,1e3,2e3],c=null;const u=async e=>{for(let t of h){t&&(await new Promise((e=>setTimeout(e,t))),s());try{ue._onLog&&ue._onLog("ask "+JSON.stringify(e)),l=await navigator.mediaDevices.getUserMedia(e),s();break}catch(e){if("NotFoundError"===e.name||"NotAllowedError"===e.name||"AbortError"===e.name||"OverconstrainedError"===e.name)throw e;c=e,ue._onLog&&ue._onLog(e.message||e)}}};try{if(await u(o),l||"object"!=typeof o.video||(o.video.deviceId&&(delete o.video.deviceId,await u(o)),!l&&o.video.facingMode&&(delete o.video.facingMode,await u(o)),l||!o.video.width&&!o.video.height||(delete o.video.width,delete o.video.height,await u(o))),!l)throw c}catch(e){throw null==l||l.getTracks().forEach((e=>{e.stop()})),"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}const d=()=>{const e=l.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),s(),a&&!this.ifSkipCameraInspection){d();const e=ue.findBestRearCamera(this._allCameras),t=null===(n=this._currentCamera)||void 0===n?void 0:n.deviceId;e&&e!=t&&(l.getTracks().forEach((e=>{e.stop()})),o.video.deviceId={exact:e},await u(o))}ue._onLog&&ue._onLog("DCE: ======play video========"),s(),await ue.playVideo(this._video,l,this.cameraOpenTimeout),s(),ue._onLog&&ue._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f="got "+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};if(g.deviceId&&(this._lastDeviceId=g.deviceId,this.ifSaveLastUsedCamera&&ue.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),o.video.width&&o.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(o.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(o.video.height))))),!r||!r.notTriggerPlayedEvent){const e=this.mapCameraEvents.get("played");for(let t of e){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(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()}isPaused(){var e;return!this._isSingleFrameModeEnabled()&&!0===(null===(e=this._video)||void 0===e?void 0:e.paused)}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const e=[this.UIElement];for(let t=0;t=17&&e.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),this._video=e;const i=document.createElement("div");i.append(e),i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.width="100%",i.style.height="100%",i.style.overflow="hidden",this._videoContainer=i,t.prepend(i)}else!this._divScanArea&&t.classList.contains("dce-scanarea")?this._divScanArea=t:!this._divScanLight&&t.classList.contains("dce-scanlight")?this._divScanLight=t:!this._bgLoading&&t.classList.contains("dce-bg-loading")?this._bgLoading=t:!this._bgCamera&&t.classList.contains("dce-bg-camera")?this._bgCamera=t:!this._selCam&&t.classList.contains("dce-sel-camera")?this._selCam=t:!this._selRsl&&t.classList.contains("dce-sel-resolution")?(this._selRsl=t,this.videoSrc||this._isSingleFrameModeEnabled()||this._selRsl.options.length||(this._selRsl.innerHTML=[this._optGotRsl?"":'','','',''].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._isSingleFrameModeEnabled()||this.videoSrc?(this._isSingleFrameModeEnabled()&&(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(V.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)),this._windowWidth=document.documentElement.clientWidth,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){this._isSingleFrameModeEnabled()?(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._drawingLayerManager.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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=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._windowResizeListener)}_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._isSingleFrameModeEnabled()&&(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){var t,i;let r="";const n=(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},s=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 o=null===(i=null===(t=this.videoSettings)||void 0===t?void 0:t.video)||void 0===i?void 0:i.deviceId;if(!o)return null;if(r=o.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:o.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!r)return null;let a=this._mapCameraResolutions.get(r);if(a&&!e)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),a=this._mapCameraResolutions.get(r);for(let e of this._predefinedResolutions){const t=await s(r,e.width,e.height);t&&!n(r,t)&&a.push([t.width,t.height])}return a}if(this._currentCamera){r=this._currentCamera.deviceId;let t=this._mapCameraResolutions.get(r);if(t&&!e)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),t=this._mapCameraResolutions.get(r);let i=this._videoTrack;for(let e of this._predefinedResolutions){await i.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const s=i.getSettings(),o={width:s.width,height:s.height};n(r,o)||t.push([o.width,o.height])}return this._video.srcObject.getTracks().forEach((e=>{e.stop()})),await this.play(r,null,null,{notTriggerPlayedEvent:!0}),t}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._isSingleFrameModeEnabled())throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(e,t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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}this._scaleCenter={x:r,y:n}}_resetScaleCenter(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(e,t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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 l=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(!l)return this._setFocusAndGetContract(e,t);const h=l.data;let c=0;for(let e=0,t=h.length-8;eo&&oc)return await this._doFocusDetail(e,s,o,r,n,h,c)}else{let a=await this._setFocusAndGetContract(e,h);if(o>a)return await this._doFocusDetail(e,s,o,r,n,h,a);if(o==a)return await this._doFocusDetail(e,s,o,h,a);let c=await this._setFocusAndGetContract(e,l);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),l=await this._setFocusAndGetContract(e,r);if(a>l&&lo&&a>o){let t=await this._setFocusAndGetContract(e,i);const n=await this._doFocusDetail(e,r,l,i,t,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==l&&ll){const t=await this._doFocusDetail(e,r,l,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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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=h*(1-1/e)*(i/2-this._scaleCenter.x),u=h*(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,l=e,h=t;const c={regionLeft:0,regionTop:0,regionRight:l,regionBottom:h,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(c.regionLeft=i.regionLeft*l/100,c.regionTop=i.regionTop*h/100,c.regionRight=i.regionRight*l/100,c.regionBottom=i.regionBottom*h/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),l=Math.round(c.regionRight-c.regionLeft),h=Math.round(c.regionBottom-c.regionTop)):(n=0,s=0,l=Math.round(l),h=Math.round(h));const u=Math.max(l,h);if(r&&r>0&&u>r){const e=r/u;l>h?(o=r,a=Math.round(h*e)):(o=Math.round(l*e),a=r)}else o=l,a=h;return o<=0||a<=0?null:{sx:n,sy:s,sWidth:l,sHeight:h,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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 l=0,h=0,c=i,u=r,d=0,f=0,g=i,_=r;n&&(n.sx&&(l=Math.round(n.sx)),n.sy&&(h=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){ue._onLog&&ue._onLog("DCE: _drawImage() in context2d."),m.ctx2d||(m.ctx2d=m.getContext("2d",{willReadFrequently:!0}));const e=m.ctx2d;if(!e)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(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 `,l=r(e,[n(e,e.VERTEX_SHADER,s),n(e,e.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:l,attribLocations:{vertexPosition:e.getAttribLocation(l,"a_position"),texPosition:e.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:e.getUniformLocation(l,"u_image"),uColorFactor:e.getUniformLocation(l,"uColorFactor"),uMatrix:e.getUniformLocation(l,"u_matrix"),uTextureMatrix:e.getUniformLocation(l,"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=le.translate(le.identity(),-1,-1);v=le.scale(v,2,2),v=le.scale(v,1/e.canvas.width,1/e.canvas.height),a=le.translate(v,d,f),a=le.scale(a,g,_),e.uniformMatrix3fv(t.uniformLocations.uMatrix,!1,a),m=le.translate(le.identity(),l/i,h/r),m=le.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),l=Math.round(r.sy),h=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(ue._onLog&&ue._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:l,sWidth:h,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&&ue._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(t),ue._onLog&&ue._onLog("DCE: finish fetching a frame into buffer: "+Date.now());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()?(ue._onLog&&ue._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):0===this.refreshInterval&&t()),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._isSingleFrameModeEnabled())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._drawingLayerManager.getSelectedDrawingItems()}createDrawingStyle(e){return this._drawingLayerManager.createDrawingStyle(e)}getDrawingStyle(e){return this._drawingLayerManager.getDrawingStyle(e)}getDrawingStyles(){return this._drawingLayerManager.getDrawingStyles()}updateDrawingStyle(e,t){return this._drawingLayerManager.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._isSingleFrameModeEnabled()&&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)}transformCoord(e){if(!this.isOpen())throw new Error("Unavailable when the camera is not open.");if(this._isSingleFrameModeEnabled()&&!this._cvsSingleFrameMode)throw new Error("No image is selected. ");const t=this._elContainer.getBoundingClientRect();let i,r,n,s,o,a=t.left,l=t.top,h=a+window.scrollX,c=l+window.scrollY;this._isSingleFrameModeEnabled()?(i=this._cvsSingleFrameMode.width,r=this._cvsSingleFrameMode.height,n=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).width),s=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,r=this.video.videoHeight,n=parseFloat(window.getComputedStyle(this._elContainer).width),s=parseFloat(window.getComputedStyle(this._elContainer).height),o=this.videoFit);const u=n/s,d=i/r;let f,g,_,p,m=1;if("contain"===o)u({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 K.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=K.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 K.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))}var pe,me,ve,ye,Se,be,we,Ce,xe,Te,Ie,Ee,Oe,Ae,De,Re,Me,Le,Fe,Pe,ke,Be,Ne,je,Ve,Ue,Ge;class We extends F{static set _onLog(e){!function(e,t,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?n.call(e,i):n?n.value=i:t.set(e,i)}(We,pe,e,"f",me),ue._onLog=e}static get _onLog(){return function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)}(We,pe,"f",me)}static get version(){return this._version+`(DCE ${ue.getVersion()})`}static _fireHTTPSWarnning(){We.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{We.onWarning&&We.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){if("boolean"!=typeof e&&!["image","camera"].includes(e))throw new Error("Invalid value.");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 cameraOpenTimeout(e){this.dce&&(this.dce.cameraOpenTimeout=e)}get cameraOpenTimeout(){return this.dce&&this.dce.cameraOpenTimeout}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||(F._onLog&&F._onLog("createDCEInstance()"),ue.defaultUIElementURL=null,this.dce=await ue.createInstance(),this.dce.cameraOpenTimeout<15e3&&(this.dce.cameraOpenTimeout=15e3),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=de,["iPhone","iPad","Android","HarmonyOS"].includes(F.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:l,timeStamp:h,_sWidth:c,_sHeight:u}=e,d={timeStamp:h};if("grey"===l)t=await this._decodeBuffer_Uint8Array(i,s,o,a,p.IPF_GrayScaled,0,d);else if("rgba"===l)t=await this._decodeBuffer_Uint8Array(i,s,o,a,p.IPF_ABGR_8888,0,d);else{if("bgra"!==l)throw new Error(`Pixel format '${l}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,o,a,p.IPF_ARGB_8888,0,d)}if(await this.clearMapDecodeRecord(),F.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}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._onPlayed=null}static async createInstance(e){const t=new We;t._instanceID=await We.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(We.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),We._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(!F._bUseFullFeature){if(t.barcodeFormatIds&~(y.BF_ONED|y.BF_QR_CODE|y.BF_PDF417|y.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=F._nextTaskID++;F._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)}})),F._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 F._onLog&&F._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));F._onLog&&F._onLog("======= once read ======="),F._onLog&&(this._timeStartDecode=Date.now());const e=this._getVideoFrame();if(!e)return F._onLog&&F._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:l,timeStamp:h,_sWidth:c,_sHeight:u}=e,d={timeStamp:h};if("grey"===l)t=await this._decodeBuffer_Uint8Array(i,s,o,a,p.IPF_GrayScaled,0,d);else if("rgba"===l)t=await this._decodeBuffer_Uint8Array(i,s,o,a,p.IPF_ABGR_8888,0,d);else{if("bgra"!==l)throw new Error(`Pixel format '${l}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,s,o,a,p.IPF_ARGB_8888,0,d)}if(F.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=async()=>new Promise(((e,t)=>{let i=F._nextTaskID++;F._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)}})),F._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!1}})})),t=await e(),i=(e,t,i,r,n,s,o)=>{let a=s/r,l=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/l+i,e.y2=e.y2/l+i,e.y3=e.y3/l+i,e.y4=e.y4/l+i},a=e=>{if(!e)return null;const t={};let a,l,h,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!=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)))},_=[];for(let t of e){if(t.resultType!==S.IRT_TYPED_BARCODE_ZONE)continue;const e=t.scaleDownRatio;for(let a of t.results){if(!a)continue;const t={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};i(t,r,n,c,u,s,o),g(f,t)&&_.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==y.BF_QR_CODE||e.barcodeFormat==y.BF_DATAMATRIX));if(r.length||(r=e.filter((e=>e.barcodeFormat==y.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=l.x3-l.x1,t=l.y3-l.y1;l.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 t=(1-this.autoZoomTargetBorder)/2;const a=l.x1/c,h=(c-l.x3)/c,d=l.y1/u,f=(u-l.y3)/u;if(a>e&&h>e&&d>e&&f>e&&l.result.moduleSize{}))),this.autoZoomInFrameArray.filter((e=>!0===e)).length>=this.autoZoomInFrameLimit[1]){this.autoZoomInFrameArray.length=0;const e=[(.5-t)/(.5-a),(.5-t)/(.5-h),(.5-t)/(.5-d),(.5-t)/(.5-f)].filter((e=>e>0)),i=Math.min(...e,this.autoZoomInIdealModuleSize/l.result.moduleSize),r=this.dce.getZoomSettings().factor;let n=Math.max(Math.pow(r*i,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);n=Math.min(n,i);const s=r*n;try{await this.setZoom({factor:s})}catch(e){const t=e.message||e;console.warn(t)}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(l,r,n,c,u,s,o);try{await this.setFocus({mode:"manual",area:{centerPoint:{x:(l.x1+l.x3)/2+"px",y:(l.y1+l.y3)/2+"px"},width:l.x3-l.x1+"px",height:l.y3-l.y1+"px"}})}catch(e){const t=e.message||e;console.warn(t)}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-a),(.5-t)/(.5-h),(.5-t)/(.5-d),(.5-t)/(.5-f)].filter((e=>e>0));let i=Math.min(...e)*this.dce.getZoomSettings().factor;try{await this.setZoom({factor:i})}catch(e){const t=e.message||e;console.warn(t)}this.dce.clearFrameBuffer(),this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((()=>{})))}}}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(l,r,n,c,u,s,o),await this.setFocus({mode:"manual",area:{centerPoint:{x:(l.x1+l.x3)/2+"px",y:(l.y1+l.y3)/2+"px"},width:l.x3-l.x1+"px",height:l.y3-l.y1+"px"}})}catch(e){const t=e.message||e;console.warn(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 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);try{await this.setZoom({factor:i})}catch(e){const t=e.message||e;console.warn(t)}this.dce.clearFrameBuffer()}}this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((()=>{})))}else this.autoFocus&&(this.autoFocusFrameArray.length=0,this.setFocus({mode:"continuous"}).catch((()=>{})))}return t})().then((e=>{if(F._onLog&&F._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,F._onLog&&F._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&&(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){F._onLog&&F._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 F._onLog&&F._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._drawResults(null),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()}convertToPageCoordinates(e){return this.dce.convertToPageCoordinates(e)}convertToClientCoordinates(e){return this.dce.convertToClientCoordinates(e)}destroyContext(){this.close(),this.dce&&this.dce.dispose(!1),this.bDestroyed||super.destroyContext()}}pe=We,me={value:void 0},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"}(ve||(ve={})),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"}(ye||(ye={})),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=-1]="BF2_ALL"}(Se||(Se={})),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"}(be||(be={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(we||(we={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(Ce||(Ce={})),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"}(xe||(xe={})),function(e){e[e.CICM_GENERAL=1]="CICM_GENERAL",e[e.CICM_SKIP=0]="CICM_SKIP",e[e.CICM_REV=2147483648]="CICM_REV"}(Te||(Te={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(Ie||(Ie={})),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"}(Ee||(Ee={})),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"}(Oe||(Oe={})),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"}(De||(De={})),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"}(Re||(Re={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(Me||(Me={})),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"}(Le||(Le={})),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"}(Fe||(Fe={})),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"}(Pe||(Pe={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(ke||(ke={})),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"}(Be||(Be={})),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"}(Ne||(Ne={})),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"}(je||(je={})),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"}(Ve||(Ve={})),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"}(Ue||(Ue={})),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"}(Ge||(Ge={}));export{F as BarcodeReader,We as BarcodeScanner,ve as EnumBarcodeColourMode,ye as EnumBarcodeComplementMode,y as EnumBarcodeFormat,Se as EnumBarcodeFormat_2,be as EnumBinarizationMode,we as EnumClarityCalculationMethod,Ce as EnumClarityFilterMode,xe as EnumColourClusteringMode,Te as EnumColourConversionMode,Ie as EnumConflictMode,Ae as EnumDPMCodeReadingMode,Ee as EnumDeblurMode,Oe as EnumDeformationResistingMode,m as EnumErrorCode,De as EnumGrayscaleTransformationMode,v as EnumIMResultDataType,p as EnumImagePixelFormat,Re as EnumImagePreprocessingMode,Me as EnumIntermediateResultSavingMode,S as EnumIntermediateResultType,Le as EnumLocalizationMode,Fe as EnumQRCodeErrorCorrectionLevel,Pe as EnumRegionPredetectionMode,ke as EnumResultCoordinateType,Be as EnumResultType,Ne as EnumScaleUpMode,je as EnumTerminatePhase,Ve as EnumTextFilterMode,Ue as EnumTextResultOrderMode,Ge as EnumTextureDetectionMode}; diff --git a/dist/dbr.pure.esm.js b/dist/dbr.pure.esm.js index 25ebb65..c3b0db5 100644 --- a/dist/dbr.pure.esm.js +++ b/dist/dbr.pure.esm.js @@ -2,20 +2,10 @@ * Dynamsoft JavaScript Library * @product Dynamsoft Barcode Reader JS Edition * @website http://www.dynamsoft.com - * @copyright Copyright 2023, Dynamsoft Corporation + * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft - * @version 9.6.32 (js 20231027) + * @version 9.6.42 (js 20240426) * @fileoverview Dynamsoft JavaScript Library for Barcode Reader * More info on DBR JS: https://www.dynamsoft.com/barcode-reader/sdk-javascript/ */ -import{Howl as t}from"dm-howler";const e="undefined"==typeof self,i=e?{}:self;let r,n,s,o,a;if("undefined"!=typeof navigator&&(r=navigator,n=r.userAgent,s=r.platform,o=r.mediaDevices),!e){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:r.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 i="unknownBrowser",o=0,h="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||n,a=r.search||e,h=r.verStr||n,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=h.indexOf(t);if(-1!=e){o=parseFloat(h.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let r=i.str||n,s=i.search||t;if(-1!=r.indexOf(s)){h=t;break}}"Linux"==h&&-1!=n.indexOf("Windows NT")&&(h="HarmonyOS"),a={browser:i,version:o,OS:h}}e&&(a={browser:"ssr",version:0,OS:"ssr"});const h="undefined"!=typeof WebAssembly&&n&&!(/Safari/.test(n)&&!/Chrome/.test(n)&&/\(.+\s11_2_([2-6]).*\)/.test(n)),l=!("undefined"==typeof Worker),c=!(!o||!o.getUserMedia),u=async()=>{let t=!1;if(c)try{(await o.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===a.browser&&a.version>66||"Safari"===a.browser&&a.version>13||"OPR"===a.browser&&a.version>43||"Edge"===a.browser&&a.version;const d=(()=>{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"./"})(),f=" is not allowed to change after `createInstance` or `loadWasm` is called.",g=!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"))||"",_=!e&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",p=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 b extends Promise{constructor(t){let e,i;super(((t,r)=>{e=t,i=r})),this._s="pending",this.resolve=t=>{this.isPending&&(w(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,w(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 x=["iPhone","iPad","Android","HarmonyOS"].includes(a.OS)?2048:4096;class T{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.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=x,this._promiseStartScan=null,this.beepSound=new t({src:[this._soundSource],onplayerror:(t,e)=>{console.warn(`Sound '${t}' playback failure: ${e}`)}})}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`"+f);i._license=e})(T,t)}static get productKeys(){return this._license}static set productKeys(t){T.license=t}static get handshakeCode(){return this._license}static set handshakeCode(t){T.license=t}static get organizationID(){return this._license}static set organizationID(t){T.license=t}static set sessionPassword(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`sessionPassword`"+f);i._sessionPassword=e})(T,t)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:h,worker:l,getUserMedia:c,camera:await u(),browser:a.browser,version:a.version,OS:a.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.");T._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`"+f);i._licenseServer=p(e)})(T,t)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(t){((t,e)=>{const i=t;if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+f);i._deviceFriendlyName=e||""})(T,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.");T.__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=T._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",T.engineResourcePath)}static set defaultUIElementURL(t){T._defaultUIElementURL=t}static _fireHTTPSWarnning(){T.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{T.onWarning&&T.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;T._onLog&&T._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:n,width:s,height:o,_sWidth:a,_sHeight:h}=t;i=e.map((t=>({localizationResult:JSON.parse(JSON.stringify(t.localizationResult))}))),T.recalculateResultLocation(i,r,n,a,h,s,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&&(T._onLog&&T._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(!T.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:r,sp:n,rmk:s}=(t=>{const e=t;if(e._pLoad.isEmpty){let t,r,n=e._license||"",s=JSON.parse(JSON.stringify(e._licenseServer)),o=e._sessionPassword,a=0;if(n.startsWith("t")||n.startsWith("f"))a=0;else if(0===n.length||n.startsWith("P")||n.startsWith("L")||n.startsWith("Y")||n.startsWith("A"))a=1;else{a=2;const e=n.indexOf(":");if(-1!=e&&(n=n.substring(e+1)),n.startsWith("DLS2")){let e;try{let t=n.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(n=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof n&&(n=JSON.stringify(n)),0===s.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),s=p(t)}!o&&e.sessionPassword&&(o=e.sessionPassword),t=e.remark}("200001"===n||n.startsWith("200001-"))&&(s&&s.length||(n="")),n||(a=1)}if(a&&(i.crypto||(r="Please upgrade your browser to support online key."),i.crypto.subtle||(r="Require https to use online key in this browser.")),r){if(1!==a)throw new Error(r);a=0,console.warn(r),e._lastErrorCode=-1,e._lastErrorString=r}return 1===a&&(n="",console.warn("Applying for a public trial license ...")),{lt:a,l:n,ls:s,sp:o,rmk:t}}throw new Error("Can't preprocess license again"+f)})(T);this._pLoad.task=async(i,o)=>{let h=T.engineResourcePath+T._workerName;T.engineResourcePath.startsWith(location.origin)||(h=await fetch(h).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),T._dbrWorker=new Worker(h),T._dbrWorker.onerror=t=>{let e=new Error(t.message);o(e)},T._dbrWorker.onmessage=async e=>{let r=e.data?e.data:e;switch(r.type){case"log":T._onLog&&T._onLog(r.message);break;case"load":{r.message&&(r.message=r.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let e,n=!1;1===t&&(n=!0,r.message||(r.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),r.success?(T._dbrWorker.onerror=null,T._version=r.version+"(JS "+T._jsVersion+"."+T._jsEditVersion+")",T._onLog&&T._onLog("load dbr worker success"),r.message&&console.warn(r.message)):(e=new Error(r.message),e.stack=r.stack+"\n"+e.stack,e.ltsErrorCode=r.ltsErrorCode,n||111==r.ltsErrorCode&&-1!=r.message.toLowerCase().indexOf("trial license")&&(n=!0)),n&&T.showDialog(r.success?"warn":"error",r.message),r.success?i():o(e);break}case"task":{let t=r.id,e=r.body;try{T._taskCallbackMap.get(t)(e),T._taskCallbackMap.delete(t)}catch(e){throw T._taskCallbackMap.delete(t),e}break}default:T._onLog&&T._onLog(e)}},T._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:T.engineResourcePath,bUseFullFeature:T._bUseFullFeature,bd:T._bWasmDebug,v:T._jsVersion,brtk:!!t,bptk:1===t,l:e,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:a,cv:T.authCacheVersion,fn:T.deviceFriendlyName,ls:r,sp:n,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 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 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),n=e.indexOf("(",r),s=e.indexOf(")",n);if(-1==i||-1==r||-1==n||-1==s){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(n+1,s);o.setAttribute("href",h),o.setAttribute("target","_blank"),t.appendChild(o),e=e.substring(s+1)}}document.body.appendChild(a)}catch(e){t._onLog&&t._onLog(e.message||e)}})(this,t,e)}static async createInstanceInWorker(t=!1){return await T.loadWasm(),await new Promise(((e,i)=>{let r=T._nextTaskID++;T._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)}})),T._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:t})}))}static async createInstance(){const t=new T;return t._instanceID=await T.createInstanceInWorker(),T._fireHTTPSWarnning(),t}async clearMapDecodeRecord(){return await new Promise(((t,e)=>{let i=T._nextTaskID++;T._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)}})),T._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:i,instanceID:this._instanceID})}))}async decode(t){T._onLog&&T._onLog("decode(source: any)"),T._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):T.isDCEFrame(t)?(e.bCopyData=!0,await this._decode_DCEFrame(t,e)):T.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,n,s,o){return await new Promise(((a,h)=>{let l=T._nextTaskID++;T._taskCallbackMap.set(l,(t=>{if(t.success){let e,i=T._onLog?Date.now():0;T._onLog&&T._onLog("worker return result: "+i),this._lastInnerDecodeDuration=t.duration;try{e=this._handleRetJsonString(t.decodeReturn)}catch(t){return h(t)}if(T._onLog){let t=Date.now();T._onLog("DBR getting message from worker timestamp: "+i),T._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),T._onLog("From DBR entering worker to returning message from worker costs: "+(i-this._timeEnterInnerDBR)),T._onLog("Handling results from DBR worker costs: "+(t-i)),T._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(),T._onLog&&T._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),T._dbrWorker.postMessage({type:"decodeBuffer",id:l,instanceID:this._instanceID,body:{buffer:t,width:e,height:i,stride:r,format:n,orientation:s,config:o}},[t.buffer]),T._onLog&&o&&o.timeStamp&&T._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-o.timeStamp))}))}async _decodeBuffer_Blob(t,e,i,r,n,s,o){T._onLog&&T._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,n,s,o)}async decodeBuffer(t,e,i,r,n,s,o){let a;return T._onLog&&T._onLog("decodeBuffer(buffer,width,height,stride,format)"),T._onLog&&(this._timeStartDecode=Date.now()),t instanceof Uint8Array||t instanceof Uint8ClampedArray?a=await this._decodeBuffer_Uint8Array(t,e,i,r,n,s,o):t instanceof ArrayBuffer?a=await this._decodeBuffer_Uint8Array(new Uint8Array(t),e,i,r,n,s,o):t instanceof Blob&&(a=await this._decodeBuffer_Blob(t,e,i,r,n,s,o)),a}async _decodeFileInMemory_Uint8Array(t){return await new Promise(((e,i)=>{let r=T._nextTaskID++;T._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)}})),T._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:t}})}))}async getRuntimeSettings(){return await new Promise(((t,e)=>{let i=T._nextTaskID++;T._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)}})),T._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(!T._bUseFullFeature){if(0!=(e.barcodeFormatIds&~(S.BF_ONED|S.BF_QR_CODE|S.BF_PDF417|S.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|=C.IRT_TYPED_BARCODE_ZONE),await new Promise(((t,i)=>{let r=T._nextTaskID++;T._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)}})),T._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=x,await new Promise(((t,e)=>{let i=T._nextTaskID++;T._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)}})),T._dbrWorker.postMessage({type:"resetRuntimeSettings",id:i,instanceID:this._instanceID})}))}async _resetRuntimeSettingsToCppDefault(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=x,await new Promise(((t,e)=>{let i=T._nextTaskID++;T._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)}})),T._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:i,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!T._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=T._nextTaskID++;T._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)}})),T._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:i,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(t){if(!T._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=T._nextTaskID++;T._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)}})),T._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:t}})}))}async _decode_Blob(t,e){T._onLog&&T._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),n=new Image;n.dbrObjUrl=r,n.src=r,n.onload=()=>{e(n)},n.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let n=await this._decode_Image(i||r,e);return i&&i.close(),n}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){T._onLog&&T._onLog("_decode_Image(image: HTMLImageElement|ImageBitmap)"),e=e||{};let i,r,n=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,o=Math.max(n,s);if(o>this._maxCvsSideLength){let t=this._maxCvsSideLength/o;i=Math.round(n*t),r=Math.round(s*t)}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}));a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl);let h=await this._decode_Canvas(a,e);if(this.ifSaveOriginalImageInACanvas){const e=document.createElement("canvas");e.width=t.width,e.height=t.height;e.getContext("2d").drawImage(t,0,0),this.oriCanvas=e,this.oriCanvasData=null}return T.recalculateResultLocation(h,0,0,n,s,i,r),h}async _decode_Canvas(t,e){if(T._onLog&&T._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,m.IPF_ABGR_8888,0,e)}async _decode_Video(t,e){if(T._onLog&&T._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,n=t.videoWidth,s=t.videoHeight,o=Math.max(n,s);if(o>this._maxCvsSideLength){let t=this._maxCvsSideLength/o;i=Math.round(n*t),r=Math.round(s*t)}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}));a.ctx2d.drawImage(t,0,0,n,s,0,0,i,r);let h=await this._decode_Canvas(a,e);if(this.ifSaveOriginalImageInACanvas){const e=document.createElement("canvas");e.width=t.videoWidth,e.height=t.videoHeight;e.getContext("2d").drawImage(t,0,0),this.oriCanvas=e,this.oriCanvasData=null}return T.recalculateResultLocation(h,0,0,n,s,i,r),h}async _decode_DCEFrame(t,e){if(T._onLog&&T._onLog("_decode_DCEFrame(dceFrame)"),!T.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:n,colorMode:s,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,n,a,m.IPF_GrayScaled,0,c);else if("rgba"===o)i=await this._decodeBuffer_Uint8Array(l,r,n,a,m.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,m.IPF_ARGB_8888,0,c)}else if("grey"===s)i=await this._decodeBuffer_Uint8Array(l,r,n,r,m.IPF_GrayScaled,0,c);else if("rgba"===s)i=await this._decodeBuffer_Uint8Array(l,r,n,4*r,m.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,m.IPF_ARGB_8888,0,c)}return i}async _decode_DSImage(t,e){if(T._onLog&&T._onLog("_decode_DSImage(dsImage)"),!T.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 T._onLog&&T._onLog("_decode_FilePath(path)"),Error("'_decode_FilePath(path, config)': The method is only supported in node environment.")}static recalculateResultLocation(t,e,i,r,n,s,o){if(t.length>0)for(let a of t){let t=a.localizationResult;2==t.resultCoordinateType&&(t.x1*=.01*s,t.x2*=.01*s,t.x3*=.01*s,t.x4*=.01*s,t.y1*=.01*o,t.y2*=.01*o,t.y3*=.01*o,t.y4*=.01*o);let h=s/r,l=o/n;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/n,t.y2*=100/n,t.y3*=100/n,t.y4*=100/n),t.x1=Math.round(t.x1),t.x2=Math.round(t.x2),t.x3=Math.round(t.x3),t.x4=Math.round(t.x4),t.y1=Math.round(t.y1),t.y2=Math.round(t.y2),t.y3=Math.round(t.y3),t.y4=Math.round(t.y4)}}static BarcodeReaderException(t,e){let i,r=v.DBR_UNKNOWN;return"number"==typeof t?(r=t,i=new Error(e)):i=new Error(t),i.code=r,i}_handleRetJsonString(t){let e=v;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&&!T._setWarnnedEx.has(t.description)&&(T._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==e.DBR_SUCCESS)return t.data;throw T.BarcodeReaderException(t.exception,t.description)}async setModeArgument(t,e,i,r){return await new Promise(((n,s)=>{let o=T._nextTaskID++;T._taskCallbackMap.set(o,(t=>{if(t.success){try{this._handleRetJsonString(t.setReturn)}catch(t){return s(t)}return n()}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,s(e)}})),T._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,n)=>{let s=T._nextTaskID++;T._taskCallbackMap.set(s,(t=>{if(t.success){let e;try{e=this._handleRetJsonString(t.getReturn)}catch(t){return n(t)}return r(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}})),T._dbrWorker.postMessage({type:"getModeArgument",id:s,instanceID:this._instanceID,body:{modeName:t,index:e,argumentName:i}})}))}async getIntermediateResults(){return await new Promise(((t,e)=>{let i=T._nextTaskID++;T._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)}})),T._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!0}})}))}async getIntermediateCanvas(){let t=await this.getIntermediateResults(),e=[];for(let i of t)if(i.dataType==y.IMRDT_IMAGE)for(let t of i.results){const i=t.bytes;let r;switch(T._onLog&&T._onLog(" "+i.length+" "+i.byteLength+" "+t.width+" "+t.height+" "+t.stride+" "+t.format),t.format){case m.IPF_ABGR_8888:r=new Uint8ClampedArray(i);break;case m.IPF_RGB_888:{const t=i.length/3;r=new Uint8ClampedArray(4*t);for(let e=0;e=n)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 n=new ImageData(r,t.width,t.height),s=document.createElement("canvas");s.width=t.width,s.height=t.height,s.getContext("2d").putImageData(n,0,0),e.push(s)}return e}async getScanSettings(){return await new Promise(((t,e)=>{let i=T._nextTaskID++;T._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)}})),T._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(!T._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|=C.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=T._nextTaskID++;T._taskCallbackMap.set(r,(e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack+="\n"+e.stack,i(t)}})),T._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 T._onLog&&T._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));T._onLog&&T._onLog("======= once read ======="),T._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(),!T.isDSImage(e)))throw new Error("Invalid DSImage.");if(!t&&!e)return T._onLog&&T._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:n,width:s,height:o,_sWidth:a,_sHeight:h}=t;e=i.map((t=>({resultState:t.resultState,localizationResult:JSON.parse(JSON.stringify(t.localizationResult))}))),T.recalculateResultLocation(e,r,n,a,h,s,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(T._onLog&&T._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),n=Math.max(...e);r&&n&&(i=r-n)}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&&(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"),T._onLog&&T._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(T._onLog&&T._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 T._onLog&&T._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 n=0;n{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.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(T._onLog&&T._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||this._promiseStartScan)&&this.stopScanning(),this.setImageSource(null);let t=T._nextTaskID++;T._taskCallbackMap.set(t,(t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}})),T._dbrWorker.postMessage({type:"destroyContext",id:t,instanceID:this._instanceID})}}T._jsVersion="9.6.32",T._jsEditVersion="20231027",T._version=`loading...(JS ${T._jsVersion}.${T._jsEditVersion})`,T._license=g,T._sessionPassword=_,T.browserInfo=a,T._workerName=`dbr-${T._jsVersion}.browser.worker.js`,T._engineResourcePath=d,T._licenseServer=[],T._deviceFriendlyName="",T._isShowRelDecodeTimeInResults=!1,T._bWasmDebug=!1,T._bNeverShowDialog=!1,T.__bUseFullFeature=!0,T._nextTaskID=0,T._taskCallbackMap=new Map,T._pLoad=new b,T._lastErrorCode=0,T._lastErrorString="",T._setWarnnedEx=new Set,T._defaultUIElementURL="@engineResourcePath/dbr.ui.html";var E={653:(t,e,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(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 E(t,e){var i=t.canvas,r=e.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(t,e){var i=e.targetCanvas.getContext("2d"),r=e.destinationWidth,n=e.destinationHeight,s=r*n*4,o=new Uint8Array(this.imageBuffer,0,s),a=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,r,n,t.RGBA,t.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 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,n=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,n=Math.sqrt,s=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),n=x.util.rotateVector(r,i);return new x.Point(n.x,n.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),n=x.util.createVector(t,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(t,e,i){var r=[],n=e.strokeWidth/2,s=e.strokeUniform?new x.Point(1/e.scaleX,1/e.scaleY):new x.Point(1,1),o=function(t){var e=n/Math.hypot(t.x,t.y);return new x.Point(t.x*e*s.x,t.y*e*s.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=-n/Math.sin(p/2),f=new x.Point(_.x*d*s.x,_.y*d*s.y),Math.hypot(f.x,f.y)/n<=e.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(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 n,s=!0,o=t.getImageData(e,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(t,e,i){for(var s=i[1],o=i[2],a=i[3],h=i[4],l=i[5],c=function(t,e,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*t*.5-u*e*.5,p=-d*e*.5+u*t*.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*t,O=u*T+d*E+.5*e,R=n(1,0,(_-T)/i,(p-E)/s),D=n((_-T)/i,(p-E)/s,(-_-T)/i,(-p-E)/s);0===a&&D>0?D-=2*l:1===a&&D<0&&(D+=2*l);for(var A=Math.ceil(Math.abs(D/l*2)),M=[],L=D/A,F=8/3*Math.sin(L/4)*Math.sin(L/4)/Math.sin(L/2),P=R+L,k=0;kw)for(var T=1,E=_.length;T2;for(e=e||0,l&&(a=t[2].xt[i-2].x?1:n.x===t[i-2].x?0:-1,h=n.y>t[i-2].y?1:n.y===t[i-2].y?0:-1),r.push(["L",n.x+a*e,n.y+h*e]),r},x.util.getPathSegmentsInfo=d,x.util.getBoundsOfCurve=function(e,i,r,n,s,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*s,c=-3*e+9*r-9*s+3*a,d=3*r-3*e;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,O,R=w.length,D=R;R--;)E=(O=1-(f=w[R]))*O*O*e+3*O*O*f*r+3*O*f*f*s+f*f*f*a,b[0][R]=E,I=O*O*O*i+3*O*O*f*n+3*O*f*f*o+f*f*f*h,b[1][R]=I;b[0][D]=e,b[1][D]=i,b[0][D+1]=a,b[1][D+1]=h;var A=[{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]=A),A},x.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var r=0;e-i[r].length>0&&r1e-4;)i=h(s),n=s,(r=o(l.x,l.y,i.x,i.y))+a>e?(s-=c,c/=2):(l=i,s+=c,a+=r);return i.angle=u(n),i}(s,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={},n=1;n=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 n=0,s=i.length;n57343)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 n=t.charCodeAt(e-1);if(55296>n||n>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,n=[];for(r=0;r-1?t.prototype[n]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=r;var n=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return n}}(n):t.prototype[n]=e[n],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function n(){}function s(e){for(var i=null,r=this;r.constructor.superclass;){var n=r.constructor.superclass.prototype[e];if(r[e]!==n){i=n;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&&(n.prototype=i.prototype,a.prototype=new n,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,n=Array.prototype.slice,s=function(t){return n.call(t,0)};try{t=s(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,n=x.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===x.document?(e=n.scrollLeft||r.scrollLeft||0,i=n.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||(s=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=s,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,n=t&&t.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(e(t,l),10)||0;return i=n.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),r=a(t),{left:s.left+r.left-(i.clientLeft||0)+o.left,top:s.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",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=t)},"GET"===r&&(o=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(r,e,!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 t=x.util.object.extend,e=x.util.object.clone,i=[];function r(){return!1}function n(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 s=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 s.apply(x.window,arguments)}x.util.animate=function(i){i||(i={});var s,o=!1,h=function(){var t=x.runningAnimations.indexOf(s);return t>-1&&x.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return o=!0,h()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),x.runningAnimations.push(s),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||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(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,n=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(s.currentValue=p?S.slice():S,s.completionRate=C,s.durationRate=n,!o){if(!f(S,C,n))return e>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(t));h()}}(l)})),s.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,n){var s=new x.Color(e).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(e,i,r,s){return t(i,r,n.colorEasing?n.colorEasing(e,s):1-Math.cos(e/s*(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(s):s(i,n)}}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,n,s,o=[];for(n=0,s=e.length;n1;)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,n,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("+s(g)+" "+s(_)+") ",a=(t.getAttribute("transform")||"")+w,t.setAttribute("transform",a),t.removeAttribute("x"),t.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=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-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"!==t.parentNode.nodeName&&(w=" translate("+s(g)+" "+s(_)+") "),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 n=r.cloneNode(!0);n.firstChild;)e.appendChild(n.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,n,s){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,n,s){var o,a=(s.x-n.x)*(t.y-n.y)-(s.y-n.y)*(t.x-n.x),h=(r.x-t.x)*(t.y-n.y)-(r.y-t.y)*(t.x-n.x),l=(s.y-n.y)*(r.x-t.x)-(s.x-n.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 n,s,o,a,h=new i,l=r.length;for(a=0;a0&&(h.status="Intersection"),h},e.Intersection.intersectPolygonPolygon=function(t,e){var r,n=new i,s=t.length;for(r=0;r0&&(n.status="Intersection"),n},e.Intersection.intersectPolygonRectangle=function(t,r,n){var s=r.min(n),o=r.max(n),a=new e.Point(o.x,s.y),h=new e.Point(s.x,o.y),l=i.intersectLinePolygon(s,a,t),c=i.intersectLinePolygon(a,o,t),u=i.intersectLinePolygon(o,h,t),d=i.intersectLinePolygon(h,s,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 n,s,o,a=e.util.array.max([t,i,r]),h=e.util.array.min([t,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 t:n=(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,n=r.canvas,s=e.util.object.clone(i);s.target=r,n&&n.fire("object:"+t,s),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,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"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,n){var s=i.target,o=s.getCenterPoint(),a=s.translateToOriginPoint(o,i.originX,i.originY),h=t(e,i,r,n);return s.setPositionByOrigin(a,i.originX,i.originY),h}}function S(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,v(i,r,n,s)),o}}function C(t,i,r,n,s){var o=t.target,a=o.controls[t.corner],h=o.canvas.getZoom(),l=o.padding/h,c=o.toLocalPoint(new e.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(t){return t.flipX!==t.flipY}function b(t,e,i,r,n){if(0!==t[e]){var s=n/t._getTransformedDimensions()[r]*t[i];t.set(i,s)}}function x(t,e,i,r){var n,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?n=0:(n=u(Math.atan2(f/l.scaleX,c.y/l.scaleY)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.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(t,e,i,r){var n,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?n=0:(n=u(Math.atan2(f/l.scaleY,c.x/l.scaleX)),e.originX===s&&e.originY===h&&(n=-n),e.originX===a&&e.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(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=n.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(s=C(e,e.originX,e.originY,i,r),l="y"!==y?d(s.x):1,u="x"!==y?d(s.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(s.x)+Math.abs(s.y),T=e.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(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 I=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)),I!==f.scaleX||O!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=_(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),m(r,s,n))return"not-allowed";var o=f(r,e);return i[o]+"-resize"},n.skewCursorStyleHandler=function(t,e,i){var n="not-allowed";if(0!==e.x&&i.lockSkewingY)return n;if(0!==e.y&&i.lockSkewingX)return n;var s=f(i,e)%4;return r[s]+"-resize"},n.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?n.skewCursorStyleHandler(t,e,i):n.scaleCursorStyleHandler(t,e,i)},n.rotationWithSnapping=S("rotating",y((function(t,e,i,r){var n=e,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)),e.originX=n,S("skewing",y(x))(t,e,i,r))},n.skewHandlerY=function(t,e,i,r){var n,a=e.target,c=a.skewY,u=e.originX;return!a.lockSkewingY&&(0===c?n=C(e,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)),e.originY=n,S("skewing",y(T))(t,e,i,r))},n.dragHandler=function(t,e,i,r){var n=e.target,s=i-e.offsetX,o=r-e.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(t,e,i,r)),a||h},n.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},n.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},n.fireEvent=g,n.wrapWithFixedAnchor=y,n.wrapWithFireEvent=S,n.getLocalPoint=C,e.controlsUtils=n}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,r=e.controlsUtils;r.renderCircleControl=function(t,e,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=e,d=i;t.save(),t.fillStyle=r.cornerColor||n.cornerColor,t.strokeStyle=r.cornerStrokeColor||n.cornerStrokeColor,o>a?(s=o,t.scale(1,a/o),d=i*o/a):a>o?(s=a,t.scale(o/a,1),u=e*a/o):s=o,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[l](),c&&t.stroke(),t.restore()},r.renderSquareControl=function(t,e,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;t.save(),t.fillStyle=n.cornerColor||s.cornerColor,t.strokeStyle=n.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,r),t.rotate(i(s.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,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-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: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(t,i,r,n,s){"circle"===((n=n||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,r,n,s):e.controlsUtils.renderSquareControl.call(this,t,i,r,n,s)}}}(e),function(){function t(t,e){var i,r,n,s,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(),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=t.getAttribute("stop-color")||"rgb(0,0,0)"),n||(n=t.getAttribute("stop-opacity")),r=(i=new x.Color(i)).getAlpha(),n=isNaN(parseFloat(n))?1:parseFloat(n),n*=r*e,{offset:a,color:i.toRgb(),opacity:n}}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,n,s,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?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(t){var e,i,r,n=x.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(n.x1,n.y1,n.x2,n.y2):"radial"===this.type&&(e=t.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=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],s));return l=x.parseTransformAttribute(d),function(t,e,i,r){var n,s;Object.keys(e).forEach((function(t){"Infinity"===(n=e[t])?s=1:"-Infinity"===n?s=0:(s=parseFloat(e[t],10),"string"==typeof n&&/^(\d+\.\d+)%|(\d+)%$/.test(n)&&(s*=.01,"pixels"===r&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,a,n,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,n=this.offsetX/t.width,s=this.offsetY/t.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))),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,n=40,s=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,s)+20,n=100*i((Math.abs(o.y)+this.blur)/t.height,s)+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,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(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,n){if(e){var s=new x.Image(e,r);this[t]=s,s.canvas=this}i&&i(e,n)}),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,n=this._activeObject,s=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,n=e.width||this.width,s=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"],n=t.viewportTransform,s={width:t.width/(r?n[0]:1),height:t.height/(r?n[3]:1)};return i.toSVG(s,{additionalTransform:r?x.util.matrixToSVG(n):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,r,n,s,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,n,s=this._objects;for(r=0,n=s.length;r\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,r,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(n=s._objects).length;e--;)r=n[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,n,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(n=s._objects,e=0;e0+l&&(o=s-1,i(this._objects,n),this._objects.splice(o,0,n)),l++;else 0!==(s=this._objects.indexOf(t))&&(o=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(o,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var r,n;if(i){for(r=e,n=e-1;n>=0;--n)if(t.intersectsWithObject(this._objects[n])||t.isContainedWithinObject(this._objects[n])||this._objects[n].isContainedWithinObject(t)){r=n;break}}else r=e-1;return r},bringForward:function(t,e){if(!t)return this;var r,n,s,o,a,h=this._activeObject,l=0;if(t===h&&"activeSelection"===t.type)for(r=(a=h._objects).length;r--;)n=a[r],(s=this._objects.indexOf(n))"}}),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,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(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],n=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.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(t.moveTo(r.x,r.y),e=1,i=this._points.length;e=n&&(o=t[i],a.push(o));return a.push(t[s]),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 n=0,s=this._objects.length;n1&&(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),n=this.restorePointerVpt(e);return x.util.transformPoint(n,r)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var r=this._normalizePointer(t,{x:e,y:i}),n=Math.max(t.cacheTranslationX+r.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+r.y*t.zoomY,0);return x.util.isTransparent(t._cacheContext,Math.round(n),Math.round(s),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 n=r.controls[e];return n.getActionName(i,n,r)},_setupCurrentTransform:function(t,i,r){if(i){var n=this.getPointer(t),s=i.__corner,o=i.controls[s],a=r&&s?o.getActionHandler(t,i,o):x.controlsUtils.dragHandler,h=this._getActionFromCorner(r,s,t,i),l=this._getOriginFromCorner(i,s),c=t[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: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),n=new x.Point(e.ex+e.left,e.ey+e.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&&(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,n,s=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(s,h))return o;if(a.length>1&&!e&&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 t[this.altSelectionKey]&&c&&r&&c!==r&&(c=r,this.targets=n),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,n=t.length;n--;){var s=t[n],o=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(o,s,e)){(i=t[n]).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,n=t(e),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 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(),n=[],s=[];t.forEach((function(t){-1===r.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e,selected:n}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},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),n=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,r),n},_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,n=this._getEventPrefix();t(x.window,"resize",this._onResize),t(r,n+"down",this._onMouseDown),t(r,n+"move",this._onMouseMove,i),t(r,n+"out",this._onMouseOut),t(r,n+"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 n=this.upperCanvasEl,s=this._getEventPrefix();t(x.document,"touchend",this._onTouchEnd,i),t(x.document,"touchmove",this._onMouseMove,i),e(n,s+"down",this._onMouseDown)},_onMouseDown:function(r){this.__onMouseDown(r),this._resetTransformEventData();var n=this.upperCanvasEl,s=this._getEventPrefix();e(n,s+"move",this._onMouseMove,i),t(x.document,s+"up",this._onMouseUp),t(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();e(x.document,"touchend",this._onTouchEnd,i),e(x.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(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)&&(e(x.document,s+"up",this._onMouseUp),e(x.document,s+"move",this._onMouseMove,i),t(n,s+"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,n=this._groupSelector,s=!1,o=!n||0===n.left&&0===n.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),s=i.actionPerformed),!o){var a=e===this._activeObject;this._maybeGroupObjects(t),s||(s=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),s=!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),s?this.requestRenderAll():o||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),r=this.targets,n={e,target:i,subTargets:r};if(this.fire(t,n),i&&i.fire(t,n),!r)return i;for(var s=0;s1&&(e=new x.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,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--&&!((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),n=this.toCanvasElement(r,t);return x.util.toDataURL(n,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,r=(e.height||this.height)*t,n=this.getZoom(),s=this.width,o=this.height,a=n*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=s,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),n=this,s=r.clipPath,o=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete r.clipPath,this._enlivenObjects(r.objects,(function(t){n.clear(),n._setBgOverlay(r,(function(){s?n._enlivenObjects([s],(function(i){n.clipPath=i[0],n.__setupCanvas.call(n,r,t,o,e)})):n.__setupCanvas.call(n,r,t,o,e)}))}),i),this}},__setupCanvas:function(t,e,i,r){var n=this;e.forEach((function(t,e){n.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 n=this;if(!e)return i[t]=!0,void(r&&r());"backgroundImage"===t||"overlayImage"===t?x.util.enlivenObjects([e],(function(e){n[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,n=e.util.toFixed,s=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,n=t.height,s=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(r<=s&&n<=s&&r*n<=i)return rc&&(t.zoomX/=r/c,t.width=c,t.capped=!0),n>u&&(t.zoomY/=n/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 n,s,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)),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(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: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(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(),n=this.canvas.getRetinaScaling();e*=r*n,i*=r*n}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,n=this[t]!==i,s=!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,n&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&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,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=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?n&&this.drawBordersInGroup(t,r,i):n&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){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*=e.devicePixelRatio,o*=e.devicePixelRatio),t.shadowColor=r.color,t.shadowBlur=r.blur*e.browserShadowBlurConstant*(s+o)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=r.offsetX*s*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,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,r,n):t.transform(1,0,0,1,r,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:r,offsetY:n}},_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,n=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.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(t),r.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(o*this.scaleX/n.zoomX,o*this.scaleY/n.zoomY),t.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 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),n=this.group,s=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=s,this.set("canvas",m),n&&(this.group=n),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),n=this._getLeftTopCoords();return this.angle&&(r=e.util.rotatePoint(r,n,o(-this.angle))),{x:r.x-n.x,y:r.y-n.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,n,s){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=s?new o(i[s],i):new o(i);n&&n(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,n){var s,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 n?n=w[n]:n-=.5,o=n-i,((s=r-e)||o)&&(a=this._getTransformedDimensions(),h=t.x+s*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,n,s=this.getCenterPoint();return r=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new x.Point(this.left,this.top),n=new x.Point(t.x,t.y),this.angle&&(n=x.util.rotatePoint(n,s,-S(this.angle))),n.subtractEquals(r)},setPositionByOrigin:function(t,e,i){var r=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(r,this.originX,this.originY);this.set("left",n.x),this.set("top",n.y)},adjustPosition:function(t){var e,i,r=S(this.angle),n=this.getScaledWidth(),s=x.util.cos(r)*n,o=x.util.sin(r)*n;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(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 n=this.getCoords(i,r);return"Intersection"===x.Intersection.intersectPolygonRectangle(n,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),n=e?t.aCoords:t.lineCoords,s=0,o=t._getImageLines(n);s<4;s++)if(!t.containsPoint(r[s],o))return!1;return!0},isContainedWithinRect:function(t,e,i,r){var n=this.getBoundingRect(i,r);return n.left>=t.x&&n.left+n.width<=e.x&&n.top>=t.y&&n.top+n.height<=e.y},containsPoint:function(t,e,i,r){var n=this._getCoords(i,r),s=(e=e||this._getImageLines(n),this._findCrossPoints(t,e));return 0!==s&&s%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,n,s=0;for(var o in e)if(!((n=e[o]).o.y=t.y&&n.d.y>=t.y||(n.o.x===n.d.x&&n.o.x>=t.x?r=n.o.x:(i=(n.d.y-n.o.y)/(n.d.x-n.o.x),r=-(t.y-0*t.x-(n.o.y-i*n.o.x))/(0-i)),r>=t.x&&(s+=1),2!==s)))break;return s},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||"",n=[this.getSvgTransform(!0,r),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=n,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,r,n=(e=e||{}).noStyle,s=e.reviver,o=n?"":'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(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[o,l,n?"":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"),s?s(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 n={};r.forEach((function(t){n[t]=e[t]})),t(e[i],n,!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 n=0,s=t.length;n=0;h--)if(n=a[h],this.isControlVisible(n)&&(r=this._getImageLines(e?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(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(),n=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/n[0],1/n[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,n=i.x+r,s=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(-n/2,-s/2,n,s),o&&(t.beginPath(),this.forEachControl((function(e,i,r){e.withConnection&&e.getVisibility(r,i)&&(a=!0,t.moveTo(e.x*n,e.y*s),t.lineTo(e.x*n+e.offsetX,e.y*s+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),n=this.strokeWidth,s=this.strokeUniform,o=this.borderScaleFactor,a=r.x+n*(s?this.canvas.getZoom():e.scaleX)+o,h=r.y+n*(s?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,n=this.canvas.getRetinaScaling();return t.setTransform(n,0,0,n,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(n,s,o){r=o.oCoords[s],n.getVisibility(o,s)&&(i&&(r=x.util.transformPoint(r,i)),n.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,n=e.onChange||i,s=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),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxCenterObjectV:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=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),s.requestRenderAll(),n()},onComplete:function(){t.setCoords(),r()}})},fxRemove:function(t,e){var i=function(){},r=(e=e||{}).onComplete||i,n=e.onChange||i,s=this;return x.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),n()},onComplete:function(){s.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 n=0,s=i.length;n-1||n&&s.colorProperties.indexOf(n[1])>-1,a=n?this.get(n[0])[n[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(s,t,e,r)},onChange:function(e,o,a){n?s[n[0]][n[1]]=e:s.set(t,e),r||i.onChange&&i.onChange(e,o,a)},onComplete:function(t,e,n){r||(s.setCoords(),i.onComplete&&i.onComplete(t,e,n))}};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,n={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,r=t.axis1,n=t.axis2,s=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(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))}}}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!==n[t]&&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(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,n){n=n||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),o=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];r(new e.Line(o,i(s,n)))},e.Line.fromObject=function(t,i){var n=r(t,!0);n.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",n,(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 n=i(this.startAngle),s=i(this.endAngle),o=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*o+" "+e.util.sin(s)*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,n=e.parseAttributes(t,e.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 e.Circle(n))},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,n=this.height,s=-this.width/2,o=-this.height/2,a=0!==e||0!==i,h=.4477152502;t.beginPath(),t.moveTo(s+e,o),t.lineTo(s+r-e,o),a&&t.bezierCurveTo(s+r-h*e,o,s+r,o+h*i,s+r,o+i),t.lineTo(s+r,o+n-i),a&&t.bezierCurveTo(s+r,o+n-h*i,s+r-h*e,o+n,s+r-e,o+n),t.lineTo(s+e,o+n),a&&t.bezierCurveTo(s+h*e,o+n,s,o+n-h*i,s,o+n-i),t.lineTo(s,o+i),a&&t.bezierCurveTo(s,o+h*i,s+h*e,o,s+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,n){if(!t)return r(null);n=n||{};var s=e.parseAttributes(t,e.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 e.Rect(i(n?e.util.object.clone(n):{},s));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,n=e.util.array.max,s=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:(n(t,"x")||0)-e,height:(n(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,n=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,n=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-n);for(var s=0;s"},toObject:function(t){return n(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,n,s=[],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 n=e.toObject(t);return e.includeDefaultValues=r,n})),n=e.Object.prototype.toObject.call(this,t);return n.objects=r,n},toDatalessObject:function(t){var i,r=this.sourcePath;if(r)i=r;else{var n=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=n;var r=e.toDatalessObject(t);return e.includeDefaultValues=i,r}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},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,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,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,n=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&n>e)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=t.scaleX=r,this._lastScaleY=t.scaleY=n,x.filterBackend.applyFilters([t],s,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 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(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,n=this.width,s=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(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);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,n=1,s=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?(n=c/i,s=u/r):("meet"===e.meetOrSlice&&(t=(c-i*(n=s=x.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(o=-t),"Max"===e.alignX&&(o=t),t=(u-r*s)/2,"Min"===e.alignY&&(a=-t),"Max"===e.alignY&&(a=t)),"slice"===e.meetOrSlice&&(t=i-c/(n=s=x.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(h=t/2),"Max"===e.alignX&&(h=t),t=r-u/s,"Mid"===e.alignY&&(l=t/2),"Max"===e.alignY&&(l=t),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(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 n=x.parseAttributes(t,x.Image.ATTRIBUTE_NAMES);x.Image.fromURL(n["xlink:href"],i,e(r?x.util.object.clone(r):{},n))})}(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,n=this;return x.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){n.rotate(t),r()},onComplete:function(){n.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"),n=!1;if(r){x.maxTextureSize=r.getParameter(r.MAX_TEXTURE_SIZE),n=x.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],o=0;o<3;o++)if(t(r,s[o])){x.webGlPrecision=s[o];break}}return this.isSupported=n,n},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 n="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(r&&i&&n&&s){var o=x.util.createCanvasElement(),a=new ArrayBuffer(t*e*4);if(x.forceGLPutImageData)return this.imageBuffer=a,void(this.copyGLTo2D=I);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,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(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},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(t,e,i,r,n,s){var o,a=this.gl;s&&(o=this.getCachedTexture(s,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:n},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,n=t.destinationWidth,s=t.destinationHeight;i===n&&r===s||(e.width=n,e.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(t,e,i,r){var n=t.createTexture();return t.bindTexture(t.TEXTURE_2D,n),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),n},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:E,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),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),n&&(e.vendor=n.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,n){var s=n.getContext("2d");s.drawImage(e,0,0,i,r);var o={sourceWidth:i,sourceHeight:r,imageData:s.getImageData(0,0,i,r),originalEl:e,originalImageData:s.getImageData(0,0,i,r),canvasEl:n,ctx:s,filterBackend:this};return t.forEach((function(t){t.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(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 n=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var s=t.createProgram();if(t.attachShader(s,r),t.attachShader(s,n),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var o=this.getAttributeLocations(t,s),a=this.getUniformLocations(t,s)||{};return a.uStepW=t.getUniformLocation(s,"uStepW"),a.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,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,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),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,n,s,o=t.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],e+=_[h]*l,i+=_[h+1]*l,r+=_[h+2]*l,b||(n+=_[h+3]*l));w[s]=e,w[s+1]=i,w[s+2]=r,w[s+3]=b?_[s+3]:n}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,n=r.length,s=this.mode;for(e=0;el[0]&&n>l[1]&&s>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,n,s,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,n=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 n,s=e.width,a=e.height,h=o(s*i),l=o(a*r);"sliceHack"===this.resizeType?n=this.sliceByTwo(t,s,a,h,l):"hermite"===this.resizeType?n=this.hermiteFastResize(t,s,a,h,l):"bilinear"===this.resizeType?n=this.bilinearFiltering(t,s,a,h,l):"lanczos"===this.resizeType&&(n=this.lanczosResize(t,s,a,h,l)),t.imageData=n},sliceByTwo:function(t,i,n,s,o){var a,h,l=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=n*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*s(x-C.x)),S[M]||(S[M]={});for(var F=w.y-y;F<=w.y+y;F++)F<0||F>=o||(L=r(1e3*s(F-C.y)),S[M][L]||(S[M][L]=f(n(i(M*p,2)+i(L*m,2))/1e3)),(T=S[M][L])>0&&(I+=T,O+=T*c[E=4*(F*e+x)],R+=T*c[E+1],D+=T*c[E+2],A+=T*c[E+3]))}d[E=4*(b*a+h)]=O/I,d[E+1]=R/I,d[E+2]=D/I,d[E+3]=A/I}return++h1&&L<-1||(y=2*L*L*L-3*L*L+1)>0&&(T+=y*f[3+(M=4*(A+I*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,n=Math.floor(255*this.contrast),s=259*(n+255)/(255*(259-n));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,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)),e=0,n=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,n,s){this._renderChars(t,e,i,r,n,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,r,n,s,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,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(t,i,r){var n=t+i.kernedWidth/2,s=this.path,o=e.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(t,e,i,r,n){var s,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+=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[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,n=e.length;r0){var I=v+s+u;"rtl"===this.direction&&(I=this.width-I-d),l&&m&&(t.fillStyle=m,t.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),t.fillStyle=p,g&&p&&t.fillRect(I,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,n=this.fontFamily,s=e.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[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),n=["\n"],s=[],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,n,s=0,o=0,a=this.get2DCursorLocation(t);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(t,e){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=t.topOffset,l=this.getValueOfPropertyAt(r,n,"deltaY");h+=(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(r,n,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-a/2,h+t.top+l,a,s)},renderSelection:function(t,e){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=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 n in e.styles[r])t(e.styles[r][n]);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 n;return n={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){n.isAborted||t[r]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return n.isAborted}}),n},_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),n=x.util.string.graphemeSplit(r).length;if(t===e)return{selectionStart:n,selectionEnd:n};var s=i.slice(t,e);return{selectionStart:n,selectionEnd:n+x.util.string.graphemeSplit(s).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,n=i.charIndex,s=this.getValueOfPropertyAt(r,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.calcTransformMatrix(),h={x:e.left+o,y:e.top+e.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 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,n=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!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(t,e){var i=b(this.styles);for(var r in this.styles){var n=parseInt(r,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,r){var n,s={},o=!1,a=this._unwrappedTextLines[t].length===e;for(var h in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(n=this.styles[t][0===e?e:e-1]),this.styles[t]){var l=parseInt(h,10);l>=e&&(o=!0,s[l-e]=this.styles[t][h],a&&0===e||delete this.styles[t][h])}var c=!1;for(o&&!a&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)r&&r[i-1]?this.styles[t+i]={0:b(r[i-1])}:n?this.styles[t+i]={0:b(n)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,r){this.styles||(this.styles={});var n=this.styles[t],s=n?b(n):{};for(var o in i||(i=1),s){var a=parseInt(o,10);a>=e&&(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[t]||(this.styles[t]={}),this.styles[t][e+i]=b(r[i]));else if(n)for(var h=n[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),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(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,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,e=this._textLines[a],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+n);for(var c=0,u=e.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 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,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[t][e-1]).left+i.width),r},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(i),n=r.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.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(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),n=r.lineIndex;if(0===n||t.metaKey||33===t.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(t,e){for(var i,r,n=this._textLines[t],s=this._getLineLeftOffset(t),o=0,a=0,h=n.length;ae){r=!0;var l=s-i,c=s,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 n=x.util.string.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),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 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=[],n=[],s=t;this._setSVGBg(n);for(var o=0,a=this._textLines.length;o",x.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,r){var n,s,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||(n=n||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),h=this._hasStyleChangedForSvg(n,s)),h&&(a=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,a,i,r)),u="",n=s,i+=d,d=0)},_pushTextBgRect:function(e,i,r,n,s,o){var a=x.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,r){for(var n,s,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,n={},s=0;s0?(i=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&s>0&&(i++,r++),n[s]={line:e,offset:i},r+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return n},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,n=!1,s=this._styleMap[t],o=this._styleMap[t+1];for(var a in s&&(t=s.line,r=s.offset),o&&(n=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&&(!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(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),n=new Array(r.length),s=0;s{},898:()=>{},245:()=>{}},I={};function O(t){var e=I[t];if(void 0!==e)return e.exports;var i=I[t]={exports:{}};return E[t](i,i.exports,O),i.exports}O.d=(t,e)=>{for(var i in e)O.o(e,i)&&!O.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},O.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var R={};(()=>{let t;O.d(R,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?O(653).fabric:{version:"5.2.1"}})();var D=R.R; -/*! - * Dynamsoft JavaScript Library - * @product Dynamsoft Camera Enhancer JS Edition - * @website https://www.dynamsoft.com - * @copyright Copyright 2023, Dynamsoft Corporation - * @author Dynamsoft - * @version 3.3.9 (js 20231205) - * @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 M,L,F,P,k;if("undefined"!=typeof navigator&&(M=navigator,L=M.userAgent,F=M.platform,P=M.mediaDevices),!A){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:M.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,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||L,o=n.search||e,a=n.verStr||L,h=n.verSearch||e;if(h instanceof Array||(h=[h]),-1!=s.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||L,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=L.indexOf("Windows NT")&&(n="HarmonyOS"),k={browser:i,version:r,OS:n}}A&&(k={browser:"ssr",version:0,OS:"ssr"});const B="undefined"!=typeof WebAssembly&&L&&!(/Safari/.test(L)&&!/Chrome/.test(L)&&/\(.+\s11_2_([2-6]).*\)/.test(L)),N=!("undefined"==typeof Worker),j=!(!P||!P.getUserMedia),U=async()=>{let t=!1;if(j)try{(await P.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===k.browser&&k.version>66||"Safari"===k.browser&&k.version>13||"OPR"===k.browser&&k.version>43||"Edge"===k.browser&&k.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 G{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 n=r.get(e);n||(n=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,n,s;const o=i.target.getBoundingClientRect();t=o.left,e=o.top,n=t+window.scrollX,s=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,Y),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 D.Control({positionHandler:W,actionHandler:X(r>0?r-1:i,Y),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,n=i.y-e.pathOffset.y;const s=D.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.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=n.length)}if(-1===i)break;for(let r=0;r=t[r].length-1)continue;let n=" ".repeat(i+2-t[r][e].length);t[r][e]=t[r][e].concat(n)}}})(e),(t=>{let e="";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}},D.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();D.util.addListener(D.document,"touchend",this._onTouchEnd,{passive:!1}),D.util.addListener(D.document,"touchmove",this._onMouseMove,{passive:!1}),D.util.removeListener(i,r+"down",this._onMouseDown)},D.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.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?D.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 n,s;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 D.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=[],n=[];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&&n.push(i)}setTimeout((()=>{t.onSelectionChange&&t.onSelectionChange(r,n)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas),this.id=e,this._mapDrawingStyles=i,e){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 t of G.arrMediaTypes)this.mapMediaType_Style.set(t,{default:n,selected:s})}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 n;switch(t){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 t of n){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)},n=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e._on("selected",r),e._on("deselected",n),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=n}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 n,s;if(r.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){n=t.getChildItems();for(let t of n)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(n){for(let t of n){const e=this.mapMediaType_Style.get(t._mediaType);for(let i of G.arrStyleSelectors)t._mapStyle.set(i,e[i]);if(t.styleId)s=this._getDrawingStyle(t.styleId);else{s=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,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapMediaType_Style.get(t._mediaType);for(let i of G.arrStyleSelectors)t._mapStyle.set(i,e[i]);if(t.styleId)s=this._getDrawingStyle(t.styleId);else{s=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,s)}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 ${static multiply(t,e){const i=[];for(let r=0;r<3;r++){const n=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*n[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 $.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 $.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return $.multiply(t,[e,0,0,0,i,0,0,0,1])}}var tt;!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"}(tt||(tt={}));const et=(t,e,i,r)=>{if(!i)return t;let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class it{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._cvsSingleFrameMode=null,this._cvsOriginalImage=null,this._imgWidth=0,this._imgHeight=0,this._singleFrameInputContainer=null,this._clickIptSingleFrameMode=()=>{if(!this._isSingleFrameModeEnabled())return;if(this.getDrawingLayers().some((t=>"editor"==t.getMode())))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this.singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):1!=this.singleFrameMode&&"image"!==this.singleFrameMode||(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),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),n=new Image;n.dbrObjUrl=i,n.src=i,n.onload=()=>{t(n)},n.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,n=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=r,this._imgHeight=n;const s=t=>{const e=Date.now();if(0===r||0===n)return null;if(t instanceof HTMLImageElement&&!t.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(t,r,n,s,null,{pixelFormat:a});if(!l)return null;const c=Date.now();return it._onLog&&it._onLog("DCE: _getVideoData(region?) END: "+c),h.data=l.data,h.pixelFormat=h.colorMode=l.pixelFormat,h._bUseWebGL=l._bUseWebGL,h.timeSpent=c-e,h.timeStamp=c,l.pixelFormat===tt.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==n||(e.width=r,e.height=n);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=s(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="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),e.style.position="absolute",e.style.width="1px",e.style.height="1px",e.style.overflow="hidden",e.style.pointerEvents="none",this._elContainer.prepend(e),this._singleFrameInputContainer=e}null==t||t.click()},this.styleEls=[],this._framePixelFormat=void 0,this._defaultFramePixelFormat="rgba",this.mapPixelFormatString_Enum=new Map([["grey",tt.GREY],["grey32",tt.GREY32],["rgba",tt.RGBA],["rbga",tt.RBGA],["grba",tt.GRBA],["gbra",tt.GBRA],["brga",tt.BRGA],["bgra",tt.BGRA]]),this.shaderPixelFormat=tt.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._isSingleFrameModeEnabled())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,n;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 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=(e-l)/p,n=(i-c-(f-d/_)/2)/p):(p=f/a,n=(i-c)/p,r=(e-l-(d-f*_)/2)/p);else{if("cover"!==s)throw new Error("Unsupported object-fit.");_>g?(p=f/a,n=(i-c)/p,r=(e-l+(f*_-d)/2)/p):(p=d/o,r=(e-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 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.cameraOpenTimeout=4e3,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._isSingleFrameModeEnabled())if("visible"===document.visibilityState){if(it._onLog&&it._onLog("DCE: document visible."),this._bOpen&&this._vc_bPlayingVideoBeforeHide)if(this.videoSrc)this._video.play();else if(this._video.srcObject){const t=this._video.srcObject.getTracks()[0];if(this._video.srcObject.active&&t)if(t.muted&&["iPhone","iPad","Mac"].includes(k.OS)){if(k.version>=17)return;this.play()}else this._video.play();else this.play()}}else if("hidden"===document.visibilityState)if(it._onLog&&it._onLog("DCE: document hidden."),["iPhone","iPad","Mac"].includes(k.OS)){if(this._vc_bPlayingVideoBeforeHide=!0,k.version>=17)return;this._video&&this._video.pause()}else 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._windowResizeListener=()=>{this._windowWidth!==document.documentElement.clientWidth&&(this._windowWidth=document.documentElement.clientWidth,this._updateLayers())},this.mapCameraEvents=new Map([["cameraopen",[]],["cameraclose",[]],["camerachange",[]],["resolutionchange",[]],["played",[]],["singleframeacquired",[]],["frameaddedtobuffer",[]]]),this._controler=null,navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this._singleFrameMode=!1:this._singleFrameMode=!0}static getVersion(){return this._version}static async detectEnvironment(){return await(async()=>({wasm:B,worker:N,getUserMedia:j,camera:await U(),browser:k.browser,version:k.version,OS:k.OS}))()}static set engineResourcePath(t){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");it._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){it._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=it._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",it.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(){var t,e;let i,r,n;if(this._isSingleFrameModeEnabled()?(i=this._imgWidth,r=this._imgHeight,n="contain"):(i=null===(t=this._video)||void 0===t?void 0:t.videoWidth,r=null===(e=this._video)||void 0===e?void 0:e.videoHeight,n=this.getVideoFit()),!i||!r)throw new Error("Invalid content dimensions.");return{width:i,height:r,objectFit:n}}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;let e;try{e=this._calculateCvsSize()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}const{width:i,height:r,objectFit:n}=e;if(i<=0||r<=0)return t.width=0,void(t.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;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"===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),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"],n=["crossline","crosshair"];let s=!1,o=!1;for(let t of i)t=t.toLowerCase(),r.includes(t)&&!s&&(s=!0,this._decoratorType.push(t)),n.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._isSingleFrameModeEnabled())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);if(!i)return;const r=i.regionRight-i.regionLeft,n=i.regionBottom-i.regionTop;if(e.width==r&&e.height==n||(e.width=r,e.height=n),r<=0||n<=0)return;const s=e.getContext("2d");s.clearRect(0,0,e.width,e.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 t of this._decoratorType){if("rectangle"===t){s.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,s.fillRect(0,0,e.width,e.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 t=s.lineWidth/2;s.strokeRect(Math.round(o-t),Math.round(a-t),Math.round(h+s.lineWidth),Math.round(l+s.lineWidth))}if("focus"===t){s.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,s.fillRect(0,0,e.width,e.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 t=s.lineWidth/2,i=[0,.25,.75,1],r=[0,.25,.75,1];s.beginPath();for(let t=0;t{const t=parseFloat(window.getComputedStyle(this._elContainer).width),e=parseFloat(window.getComputedStyle(this._elContainer).height);let s,o={regionBottom:r,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===n?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 it;("string"==typeof t||t instanceof String)&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return this._hasEngineResourceLoaded=!0,it.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{it.onWarning&&it.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((()=>{it.onWarning&&it.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),e._drawingLayersManager=new q,e}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,new Promise(((e,r)=>{let n;const s=()=>{t.removeEventListener("loadstart",h),t.removeEventListener("abort",l),t.removeEventListener("play",c),t.removeEventListener("error",u)},o=()=>{n&&clearTimeout(n),s(),e(t)},a=t=>{n&&clearTimeout(n),s(),r(t)},h=()=>{t.addEventListener("abort",l,{once:!0})},l=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",a(t)},c=()=>{o()},u=()=>{a(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};t.addEventListener("loadstart",h,{once:!0}),t.autoplay?(t.addEventListener("play",c,{once:!0}),t.addEventListener("error",u,{once:!0})):(t.load(),t.play().then((()=>{o()})).catch((t=>{a(t)}))),i&&(n=setTimeout((()=>{s(),r(new Error("Failed to play video. Timeout."))}),i))}))}static findBestRearCameraInIOS(t){if(!t||!t.length)return null;const e=["back","baksidan","bakre","bak","後置","后置","背面","خلفية","задна","posteriore","posterior","zadní","bagside","rück","πίσω","trasera","taka","arrière","אחורית","बैक","stražnja","hátsó","belakang","aртқы","후면","achterzijde","tylny","traseira","spate","задняя","задней","zadná","านหลัง","arka","sau"],i=["triple","三镜头","三鏡頭","トリプル","ثلاثية","тройна","trojný","τριπλή","kolmois","משולשת","ट्रिपल","trostruka","tiga","tripla","үштік","트리플","trippelt","trippel","trójobiektywowy","triplă","тройная","trojitá","สาม","üçlü","потроєна","ba camera"],r=["dual wide","dual-weitwinkel","dual con gran angular","dual","doble","double","双广角","雙廣角","デュアル広角","مزدوجة عريضة","двойна широкоъгълна","duální širokoúhlý","διπλή ευρεία","laajakulmainen kaksois","כפולה רחבה","ड्युअल वाइड","dvostruka široka","kettős, széles látószögű","ganda","doppia con grandangolo","қос кең бұрышты","듀얼 와이드","dwikamera","dobbelt vidvinkelkamera","dwuobiektywowy","dupla grande-angular","grande angular dupla","dublă","двойная широкоугольная","duálna širokouhlá","dubbel vidvinkel","คู่ด้านหลังมุมกว้าง","çift geniş","здвоєна ширококутна","kép rộng mặt sau"],n=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!n.length)return null;const s=n.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const o=n.find((t=>{const e=t.label.toLowerCase();return r.some((t=>e.includes(t)))}));return o?o.deviceId:n[0].deviceId}static findBestRearCamera(t){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(k.OS))return it.findBestRearCameraInIOS(t);const e=["rear","back","rück","arrière","trasera","trás","traseira","posteriore","posterior","后面","後面","背面","后置","後置","背置","задней","خلفية","후","arka","achterzijde","หลัง","baksidan","bagside","sau","bak","tylny","taka","אחורית","πίσω","spate","hátsó","zadní","darrere","zadná","задня","stražnja","belakang","बैक","задна","aртқы","задняя","bakre","านหลัง"];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(k.OS)?t[t.length-1].deviceId:null}_isSingleFrameModeEnabled(){return 0!=this.singleFrameMode}async play(t,e,i,r){let n;if(this._video&&this.videoSrc){it._onLog&&(n=Date.now(),it._onLog("DCE: start loading static video: "+n));const t=await it.playVideo(this._video,this.videoSrc,this.cameraOpenTimeout);if(it._onLog&&it._onLog("DCE: finish loading static video. Costs: "+(Date.now()-n)),!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._isSingleFrameModeEnabled())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 n;try{this._video&&this._video.srcObject&&this.stop(),it._onLog&&it._onLog("DCE: ======before video========");const s=()=>{if(!this._video)throw h&&h.getTracks().forEach((t=>{t.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},o=this.getVideoSettings();let a,h;if("boolean"==typeof o.video&&(o.video={}),t)delete o.video.facingMode,o.video.deviceId={exact:t};else if(o.video.deviceId);else if(this._lastDeviceId)delete o.video.facingMode,o.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&it.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete o.video.facingMode,o.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&&(o.video.width=t,o.video.height=e)}else if(this.ifSkipCameraInspection);else if(o.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let t=o.video.facingMode;if(t instanceof Array&&t.length&&(t=t[0]),t=t.exact||t.ideal||t,"environment"===t){a=!0;const t=it.findBestRearCamera(this._allCameras);t&&(delete o.video.facingMode,o.video.deviceId={exact:t})}}e&&(o.video.width={ideal:e}),i&&(o.video.height={ideal:i}),it._onLog&&it._onLog("DCE: ======try getUserMedia========");let l=[0,500],c=null;const u=async t=>{for(let e of l){e&&await new Promise((t=>setTimeout(t,e))),s();try{it._onLog&&it._onLog("DCE: ask "+JSON.stringify(t)),h=await navigator.mediaDevices.getUserMedia(t);break}catch(t){if(s(),"NotFoundError"===t.name||"NotAllowedError"===t.name)throw t;c=t,it._onLog&&it._onLog("DCE: "+t.message||t)}}s()};let d;if(await u(o),h||(it._onLog&&it._onLog("DCE: ======try getUserMedia again========"),d=JSON.parse(JSON.stringify(o)),"object"==typeof d.video&&(["iPhone","iPad"].includes(k.OS)?(e>=1280||i>=1280?d.video.width=1280:e>=640||i>=640?d.video.width=640:(e<640||i<640)&&(d.video.width=320),delete d.video.height):a&&!o.video.deviceId?(delete d.video.facingMode,this._allCameras.length&&(d.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):d.video=!0),it._onLog&&it._onLog("DCE: "+d),await u(d)),h||(l=[1e3,2e3],await u(o)),h||await u(d),!h)throw c;const f=()=>{const t=h.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(),a&&!this.ifSkipCameraInspection){f();const t=it.findBestRearCamera(this._allCameras),e=null===(n=this._currentCamera)||void 0===n?void 0:n.deviceId;t&&t!=e&&(h.getTracks().forEach((t=>{t.stop()})),l=[0,500,1e3,2e3],o.video.deviceId={exact:t},await u(o))}it._onLog&&it._onLog("DCE: ======play video========"),s(),await it.playVideo(this._video,h,this.cameraOpenTimeout),s(),it._onLog&&it._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const g="got "+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=g,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),it._onLog&&it._onLog("DCE: got "+g),f(),this._renderSelCameraInfo();const _={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(_.deviceId&&(this._lastDeviceId=_.deviceId,this.ifSaveLastUsedCamera&&it.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),o.video.width&&o.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(o.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(o.video.height))))),!r||!r.notTriggerPlayedEvent){const t=this.mapCameraEvents.get("played");for(let e of t){if(!e)continue;const t=JSON.parse(JSON.stringify(_));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return this.promisePlay=null,_}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}})(),it._onLog&&(n=Date.now(),it._onLog("DCE: start opening camera: "+n));const o=await this.promisePlay;return it._onLog&&it._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()}isPaused(){var t;return!this._isSingleFrameModeEnabled()&&!0===(null===(t=this._video)||void 0===t?void 0:t.paused)}_bindUI(){if(!this.UIElement)throw new Error("Need to define `UIElement` before opening.");const t=[this.UIElement];for(let e=0;e=17&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),this._video=t;const i=document.createElement("div");i.append(t),i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.width="100%",i.style.height="100%",i.style.overflow="hidden",this._videoContainer=i,e.prepend(i)}else!this._divScanArea&&e.classList.contains("dce-scanarea")?this._divScanArea=e:!this._divScanLight&&e.classList.contains("dce-scanlight")?this._divScanLight=e:!this._bgLoading&&e.classList.contains("dce-bg-loading")?this._bgLoading=e:!this._bgCamera&&e.classList.contains("dce-bg-camera")?this._bgCamera=e:!this._selCam&&e.classList.contains("dce-sel-camera")?this._selCam=e:!this._selRsl&&e.classList.contains("dce-sel-resolution")?(this._selRsl=e,this.videoSrc||this._isSingleFrameModeEnabled()||this._selRsl.options.length||(this._selRsl.innerHTML=[this._optGotRsl?"":'','','',''].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._isSingleFrameModeEnabled()||this.videoSrc?(this._isSingleFrameModeEnabled()&&(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(k.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)),this._windowWidth=document.documentElement.clientWidth,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){this._isSingleFrameModeEnabled()?(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._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=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._windowResizeListener)}_assertOpen(){if(!this._bOpen)throw Error("The camera is not open.")}async open(t){this.UIElement||await this.setUIElement(it.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._isSingleFrameModeEnabled()&&(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&&(it._onLog&&it._onLog("DCE: ======stop video========"),this._video.srcObject.getTracks().forEach((t=>{t.stop()})),this._video.srcObject=null,this._videoTrack=null,this._currentCamera=null),this._video&&this.videoSrc&&(it._onLog&&it._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(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!==s.width||n!==s.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(s));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return s}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 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 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){var e,i;let r="";const n=(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},s=async(t,e,i)=>{const r={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let n=null;try{n=await navigator.mediaDevices.getUserMedia(r)}catch(t){return null}if(!n)return null;const s=n.getVideoTracks();let o=null;try{const t=s[0].getSettings();o={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=n,o={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),o};if(!this._bOpen){const o=null===(i=null===(e=this.videoSettings)||void 0===e?void 0:e.video)||void 0===i?void 0:i.deviceId;if(!o)return null;if(r=o.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:o.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!r)return null;let a=this._mapCameraResolutions.get(r);if(a&&!t)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),a=this._mapCameraResolutions.get(r);for(let t of this._predefinedResolutions){const e=await s(r,t.width,t.height);e&&!n(r,e)&&a.push([e.width,e.height])}return a}if(this._currentCamera){r=this._currentCamera.deviceId;let e=this._mapCameraResolutions.get(r);if(e&&!t)return this._mapCameraResolutions.get(r);this._mapCameraResolutions.set(r,[]),e=this._mapCameraResolutions.get(r);let i=this._videoTrack;for(let t of this._predefinedResolutions){await i.applyConstraints({width:{ideal:t.width},height:{ideal:t.height}});const s=i.getSettings(),o={width:s.width,height:s.height};n(r,o)||e.push([o.width,o.height])}return this._video.srcObject.getTracks().forEach((t=>{t.stop()})),await this.play(r,null,null,{notTriggerPlayedEvent:!0}),e}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._isSingleFrameModeEnabled())throw new Error("'getCapabilities()' is unavailable in singleFrameMode.");return this._videoTrack&&this._videoTrack.getCapabilities?this._videoTrack.getCapabilities():{}}getCameraSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getCameraSettings()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings():null}getConstraints(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getConstraints()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getConstraints():null}async applyConstraints(t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getColorTemperature()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().colorTemperature||0:null}async setExposureCompensation(t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getExposureCompensation()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().exposureCompensation||0:null}async _setHardwareScale(t){if(this._assertOpen(),this._isSingleFrameModeEnabled())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=et(t,e.min,e.step,e.max),await this._videoTrack.applyConstraints({advanced:[{zoom:t}]}),t}_getHardwareScale(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'_getHardwareScale()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().zoom||1:null}_setSoftwareScale(t,e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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,n=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"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");return this._videoTrack?this._getHardwareScale()*this._softwareScale:null}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())throw new Error("'getFrameRate()' is unavailable in singleFrameMode.");return this._videoTrack?this._videoTrack.getSettings().frameRate:null}async _setFocus(t,e){if(this._assertOpen(),this._isSingleFrameModeEnabled())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=et(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._isSingleFrameModeEnabled())throw new Error("'setFocus()' is unavailable in singleFrameMode.");if(!t)return;const i=this.getCapabilities(),r=i.focusMode,n=i.focusDistance;if(!r)throw Error("Not supported.");if("string"!=typeof t.mode)throw Error("Invalid focus mode.");const s=t.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(t.hasOwnProperty("distance")){let e=t.distance;return en.max&&(e=n.max),e=et(e,n.min,n.step,n.max),this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:s,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._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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=et(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 n=t.focusL-t.focusW/2,s=t.focusT-t.focusH/2,o=t.focusW,a=t.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:tt.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,s,o,r,n,l,c)}else{let a=await this._setFocusAndGetContract(t,l);if(o>a)return await this._doFocusDetail(t,s,o,r,n,l,a);if(o==a)return await this._doFocusDetail(t,s,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=et(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=et(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=et(Math.sqrt(r*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await this._setFocusAndGetContract(t,s),a=await this._setFocusAndGetContract(t,n),h=await this._setFocusAndGetContract(t,r);if(a>h&&ho&&a>o){let e=await this._setFocusAndGetContract(t,i);const n=await this._doFocusDetail(t,r,h,i,e,s,o);return this._focusParameters.isDoingFocus=0,n}if(a==h&&hh){const e=await this._doFocusDetail(t,r,h,s,o);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,r,n)}async enableTapToFocus(){if(this._assertOpen(),this._isSingleFrameModeEnabled())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._isSingleFrameModeEnabled())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),n=parseFloat(r.width),s=parseFloat(r.height),o=t/i;if(n/sa?o/(i/t):s/(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 n,s,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),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 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:n,sy:s,sWidth:h,sHeight:l,dWidth:o,dHeight:a}}getFrame(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getFrame()' is unavailable in singleFrameMode.");return this._getVideoData()}getImage(){return this.getFrame()}_drawImage(t,e,i,r,n,s,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;it._onLog&&(a=Date.now(),it._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=tt.RGBA;o&&o.pixelFormat&&(p=o.pixelFormat);const m=t;if(!o||!o.bUseWebGL){it._onLog&&it._onLog("DCE: _drawImage() in context2d."),m.ctx2d||(m.ctx2d=m.getContext("2d",{willReadFrequently:!0}));const t=m.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(m.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},n=(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},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(t,[n(t,t.VERTEX_SHADER,s),n(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=p}const n=(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,n=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,r,n,s,i)},v=(t,e,s,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),n(t,s.positions,e.attribLocations.vertexPosition),n(t,s.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,[tt.GREY,tt.GREY32].includes(p)?1:0);let a,m,v=$.translate($.identity(),-1,-1);v=$.scale(v,2,2),v=$.scale(v,1/t.canvas.width,1/t.canvas.height),a=$.translate(v,d,f),a=$.scale(a,g,_),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,a),m=$.translate($.identity(),h/i,l/r),m=$.scale(m,c/i,u/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,m),t.drawArrays(t.TRIANGLES,0,6)};let y;if(o(t,this._webGLTexture,e),v(t,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),s){if(s.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.");let o;it._onLog&&(o=Date.now(),it._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=tt.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(it._onLog&&it._onLog("DCE: _getImageData() in WebGL."),n)if(f===tt.GREY){if(p=new Uint8Array(u*d*4),_=this._drawImage(g,t,e,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.");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=()=>{it._onLog&&it._onLog("DCE: start fetching a frame into buffer: "+Date.now());const t=this.getCurrentRegion();let e=this._getVideoData(null,{region:t});if(!e)return void(it._onLog&&it._onLog("DCE: get a invalid frame, abandon it: "+Date.now()));for(;this._frameQueue&&this._frameQueue.length>=this.maxNumberOfFramesInBuffer;)this._frameQueue.shift();this._frameQueue.push(e),it._onLog&&it._onLog("DCE: finish fetching a frame into buffer: "+Date.now());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()?(it._onLog&&it._onLog("DCE: second timeout executes: "+Date.now()),e(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};t&&(this._frameQueue.length0&&i()):0===this.refreshInterval&&e()),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._isSingleFrameModeEnabled())throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,it._onLog&&it._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(it._onLog&&it._onLog("DCE: stop fetching loop: "+Date.now()),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,n=3e3,s=!0){this._assertOpen(),this._tipArgs.x=t,this._tipArgs.y=e,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 J(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 n=r.getContext("2d");n.clearRect(0,0,r.width,r.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),n.putImageData(new ImageData(t,e,i),0,0)):t instanceof HTMLCanvasElement&&n.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._isSingleFrameModeEnabled()&&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)}transformCoord(t){if(!this.isOpen())throw new Error("Unavailable when the camera is not open.");if(this._isSingleFrameModeEnabled()&&!this._cvsSingleFrameMode)throw new Error("No image is selected. ");const e=this._elContainer.getBoundingClientRect();let i,r,n,s,o,a=e.left,h=e.top,l=a+window.scrollX,c=h+window.scrollY;this._isSingleFrameModeEnabled()?(i=this._cvsSingleFrameMode.width,r=this._cvsSingleFrameMode.height,n=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).width),s=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,r=this.video.videoHeight,n=parseFloat(window.getComputedStyle(this._elContainer).width),s=parseFloat(window.getComputedStyle(this._elContainer).height),o=this.videoFit);const u=n/s,d=i/r;let f,g,_,p,m=1;if("contain"===o)u({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 D.Control({positionHandler:W,actionHandler:X(i>0?i-1:r,Y),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,n=t.y-i.pathOffset.y;const s=D.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}},DT_Group:class extends G{constructor(t){super(new D.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 nt(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 ot(t,e,i,r){let n=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(r[1]-e[1])+e[0]*(t[1]-r[1])+r[0]*(e[1]-t[1]);return!((n^s)>=0&&0!==n&&0!==s)&&(n=i[0]*(t[1]-r[1])+r[0]*(i[1]-t[1])+t[0]*(r[1]-i[1]),s=i[0]*(e[1]-r[1])+r[0]*(i[1]-e[1])+e[0]*(r[1]-i[1]),!((n^s)>=0&&0!==n&&0!==s))}var at,ht,lt,ct,ut,dt,ft,gt,_t,pt,mt,vt,yt,St,Ct,wt,bt,xt,Tt,Et,It,Ot,Rt,Dt,At,Mt,Lt,Ft;class Pt extends T{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._onPlayed=null}static set _onLog(t){!function(t,e,i,r,n){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?n.call(t,i):n?n.value=i:e.set(t,i)}(Pt,at,t,"f",ht),it._onLog=t}static get _onLog(){return function(t,e,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(t):r?r.value:e.get(t)}(Pt,at,"f",ht)}static get version(){return this._version+`(DCE ${it.getVersion()})`}static _fireHTTPSWarnning(){Pt.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{Pt.onWarning&&Pt.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return it.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){if("boolean"!=typeof t&&!["image","camera"].includes(t))throw new Error("Invalid value.");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||(T._onLog&&T._onLog("createDCEInstance()"),it.defaultUIElementURL=null,this.dce=await it.createInstance(),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=rt,["iPhone","iPad","Android","HarmonyOS"].includes(T.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:n,width:s,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,s,o,a,m.IPF_GrayScaled,0,d);else if("rgba"===h)e=await this._decodeBuffer_Uint8Array(i,s,o,a,m.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);e=await this._decodeBuffer_Uint8Array(i,s,o,a,m.IPF_ARGB_8888,0,d)}if(await this.clearMapDecodeRecord(),T.recalculateResultLocation(e,r,n,c,u,s,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){const e=new Pt;e._instanceID=await Pt.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(Pt.defaultUIElementURL),e.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),Pt._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(!T._bUseFullFeature){if(0!=(e.barcodeFormatIds&~(S.BF_ONED|S.BF_QR_CODE|S.BF_PDF417|S.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=T._nextTaskID++;T._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)}})),T._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 T._onLog&&T._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));T._onLog&&T._onLog("======= once read ======="),T._onLog&&(this._timeStartDecode=Date.now());const t=this._getVideoFrame();if(!t)return T._onLog&&T._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:n,width:s,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,s,o,a,m.IPF_GrayScaled,0,d);else if("rgba"===h)e=await this._decodeBuffer_Uint8Array(i,s,o,a,m.IPF_ABGR_8888,0,d);else{if("bgra"!==h)throw new Error(`Pixel format '${h}' is not supported.`);e=await this._decodeBuffer_Uint8Array(i,s,o,a,m.IPF_ARGB_8888,0,d)}if(T.recalculateResultLocation(e,r,n,c,u,s,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=async()=>new Promise(((t,e)=>{let i=T._nextTaskID++;T._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)}})),T._dbrWorker.postMessage({type:"getIntermediateResults",id:i,instanceID:this._instanceID,body:{isCharge:!1}})})),e=await t(),i=(t,e,i,r,n,s,o)=>{let a=s/r,h=o/n;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},a=t=>{if(!t)return null;const e={};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,n=this.video.videoHeight*(1-this.autoZoomDetectionArea)/2,s=n,o=this.video.videoHeight*(1+this.autoZoomDetectionArea)/2;f={x1:t,x2:e,x3:i,x4:r,y1:n,y2:s,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 n=t.length;if(n<=2)return!1;for(let s=0;s0!=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)=>!!(ot([t[0],t[1]],[t[2],t[3]],[e.x1,e.y1],[e.x2,e.y2])||ot([t[0],t[1]],[t[2],t[3]],[e.x2,e.y2],[e.x3,e.y3])||ot([t[0],t[1]],[t[2],t[3]],[e.x3,e.y3],[e.x4,e.y4])||ot([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 e of t){if(e.resultType!==C.IRT_TYPED_BARCODE_ZONE)continue;const t=e.scaleDownRatio;for(let a of e.results){if(!a)continue;const e={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};i(e,r,n,c,u,s,o),g(f,e)&&_.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-s/2)*(e-s/2)+(i-o/2)*(i-o/2)};let i,r=t.filter((t=>t.barcodeFormat==S.BF_QR_CODE||t.barcodeFormat==S.BF_DATAMATRIX));if(r.length||(r=t.filter((t=>t.barcodeFormat==S.BF_ONED)),r.length||(r=t)),!r.length)return null;i=r[0];let n=e(i);if(1!=r.length)for(let t=1;t1.1*i.confidence?(i=r[t],n=s):r[t].confidence>.9*i.confidence&&s!0===t)).length>=this.suggestTipFrameLimit[1]){this.suggestTipFrameArray.length=0;const t=h.x3-h.x1,e=h.y3-h.y1;h.result.moduleSizee?t>s*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):t>.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."):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 e=(1-this.autoZoomTargetBorder)/2;const a=h.x1/c,l=(c-h.x3)/c,d=h.y1/u,f=(u-h.y3)/u;if(a>t&&l>t&&d>t&&f>t&&h.result.moduleSize{}))),this.autoZoomInFrameArray.filter((t=>!0===t)).length>=this.autoZoomInFrameLimit[1]){this.autoZoomInFrameArray.length=0;const t=[(.5-e)/(.5-a),(.5-e)/(.5-l),(.5-e)/(.5-d),(.5-e)/(.5-f)].filter((t=>t>0)),i=Math.min(...t,this.autoZoomInIdealModuleSize/h.result.moduleSize),r=this.dce.getZoomSettings().factor;let n=Math.max(Math.pow(r*i,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);n=Math.min(n,i);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((t=>!0===t)).length>=this.frameLimitInIdealZoom[1])if(this.frameArrayInIdealZoom.length=0,"focus"===this.nextActionInIdealZoom&&this.autoFocus){i(h,r,n,c,u,s,o);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(t){}this.dce.clearFrameBuffer(),this.nextActionInIdealZoom="zoomOut"}else{if("zoomOut"!==this.nextActionInIdealZoom&&this.autoFocus)throw new Error("Invalid action.");if(this.enableZoomOutInIdealZoom){e=this.autoZoomIdealArea[1]+this.autoZoomOutStepRate_2;const t=[(.5-e)/(.5-a),(.5-e)/(.5-l),(.5-e)/(.5-d),(.5-e)/(.5-f)].filter((t=>t>0));let i=Math.min(...t)*this.dce.getZoomSettings().factor;await this.setZoom({factor:i}),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{i(h,r,n,c,u,s,o),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(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(T._onLog&&T._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 n=0,s=0;n=i+1>=this.region.length?0:i+1,s=n+1>=this.region.length?0:n+1,r=t[n]&&t[n].length&&e[s]&&e[s].length?Math.min(...t[n])-Math.max(...e[s]):0}else if(e&&e.length){let i=Math.min(...t),n=Math.max(...e);i&&n&&(r=i-n)}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,T._onLog&&T._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&&(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){T._onLog&&T._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 T._onLog&&T._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._drawResults(null),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,n=3e3,s=!0){this.dce&&this.dce.showTip(t,e,i,r,n,s)}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()}convertToPageCoordinates(t){return this.dce.convertToPageCoordinates(t)}convertToClientCoordinates(t){return this.dce.convertToClientCoordinates(t)}destroyContext(){this.close(),this.dce&&this.dce.dispose(!1),this.bDestroyed||super.destroyContext()}}at=Pt,ht={value:void 0},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"}(lt||(lt={})),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"}(ct||(ct={})),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=-1]="BF2_ALL"}(ut||(ut={})),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"}(dt||(dt={})),function(t){t[t.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(ft||(ft={})),function(t){t[t.CFM_GENERAL=1]="CFM_GENERAL"}(gt||(gt={})),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"}(_t||(_t={})),function(t){t[t.CICM_GENERAL=1]="CICM_GENERAL",t[t.CICM_SKIP=0]="CICM_SKIP",t[t.CICM_REV=2147483648]="CICM_REV"}(pt||(pt={})),function(t){t[t.CM_IGNORE=1]="CM_IGNORE",t[t.CM_OVERWRITE=2]="CM_OVERWRITE"}(mt||(mt={})),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"}(vt||(vt={})),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"}(yt||(yt={})),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"}(St||(St={})),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"}(Ct||(Ct={})),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"}(wt||(wt={})),function(t){t[t.IRSM_MEMORY=1]="IRSM_MEMORY",t[t.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",t[t.IRSM_BOTH=4]="IRSM_BOTH"}(bt||(bt={})),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"}(xt||(xt={})),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"}(Tt||(Tt={})),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"}(Et||(Et={})),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"}(It||(It={})),function(t){t[t.RCT_PIXEL=1]="RCT_PIXEL",t[t.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(Ot||(Ot={})),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"}(Rt||(Rt={})),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"}(Dt||(Dt={})),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"}(At||(At={})),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"}(Mt||(Mt={})),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"}(Lt||(Lt={})),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"}(Ft||(Ft={}));export{T as BarcodeReader,Pt as BarcodeScanner,lt as EnumBarcodeColourMode,ct as EnumBarcodeComplementMode,S as EnumBarcodeFormat,ut as EnumBarcodeFormat_2,dt as EnumBinarizationMode,ft as EnumClarityCalculationMethod,gt as EnumClarityFilterMode,_t as EnumColourClusteringMode,pt as EnumColourConversionMode,mt as EnumConflictMode,St as EnumDPMCodeReadingMode,vt as EnumDeblurMode,yt as EnumDeformationResistingMode,v as EnumErrorCode,Ct as EnumGrayscaleTransformationMode,y as EnumIMResultDataType,m as EnumImagePixelFormat,wt as EnumImagePreprocessingMode,bt as EnumIntermediateResultSavingMode,C as EnumIntermediateResultType,xt as EnumLocalizationMode,Tt as EnumPDFReadingMode,Et as EnumQRCodeErrorCorrectionLevel,It as EnumRegionPredetectionMode,Ot as EnumResultCoordinateType,Rt as EnumResultType,Dt as EnumScaleUpMode,At as EnumTerminatePhase,Mt as EnumTextFilterMode,Lt as EnumTextResultOrderMode,Ft as EnumTextureDetectionMode}; +import{Howl as e}from"dm-howler";import{CameraEnhancer as t,DrawingItem as i}from"dynamsoft-camera-enhancer";const s="undefined"==typeof self,a=s?{}:self;let r,o,n,c,d;"undefined"!=typeof navigator&&(r=navigator,o=r.userAgent,n=r.platform,c=r.mediaDevices),function(){if(!s){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:r.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 i="unknownBrowser",s=0,a="unknownOS";for(let t in e){const a=e[t]||{};let r=a.str||o,n=a.search||t,c=a.verStr||o,d=a.verSearch||t;if(d instanceof Array||(d=[d]),-1!=r.indexOf(n)){i=t;for(let e of d){let t=c.indexOf(e);if(-1!=t){s=parseFloat(c.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let s=i.str||o,r=i.search||e;if(-1!=s.indexOf(r)){a=e;break}}"Linux"==a&&-1!=o.indexOf("Windows NT")&&(a="HarmonyOS"),d={browser:i,version:s,OS:a}}s&&(d={browser:"ssr",version:0,OS:"ssr"})}();const l="undefined"!=typeof WebAssembly&&o&&!(/Safari/.test(o)&&!/Chrome/.test(o)&&/\(.+\s11_2_([2-6]).*\)/.test(o)),h=!("undefined"==typeof Worker),_=!(!c||!c.getUserMedia),u=async()=>{let e=!1;if(_)try{(await c.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===d.browser&&d.version>66||"Safari"===d.browser&&d.version>13||"OPR"===d.browser&&d.version>43||"Edge"===d.browser&&d.version;const g=(()=>{if(!s&&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"./"})(),m=" is not allowed to change after `createInstance` or `loadWasm` is called.",R=!s&&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"))||"",I=!s&&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 y extends Promise{constructor(e){let t,i;super(((e,s)=>{t=e,i=s})),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}}const p=["iPhone","iPad","Android","HarmonyOS"].includes(d.OS)?2048:4096;class L{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`"+m);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`"+m);i._sessionPassword=t})(L,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:l,worker:h,getUserMedia:_,camera:await u(),browser:d.browser,version:d.version,OS:d.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="./"),s);else{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`"+m);i._licenseServer=S(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`"+m);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(t){this._soundSource=t,this.beepSound=new e({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(),s=this.dce.constructor;if("@engineResourcePath/dce.ui.html"===s._defaultUIElementURL)try{i?i===t._innerSetUI&&(await e.setUIElement(`${s.engineResourcePath}dce.ui.html`),t._innerSetUI=e.getUIElement()):(await e.setUIElement(`${s.engineResourcePath}dbr.ui.html`),t._innerSetUI=e.getUIElement())}catch(t){await e.setUIElement(s.defaultUIElementURL)}else i||await e.setUIElement(s.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:s,sy:a,width:r,height:o,_sWidth:n,_sHeight:c}=e;i=t.map((e=>({localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(i,s,a,n,c,r,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:s,rmk:r}=((e,t=!1)=>{const i=e;if(i._pLoad.isEmpty){let e,s,r,o=i._license||"",n=JSON.parse(JSON.stringify(i._licenseServer)),c=i._sessionPassword,d=0;if(o.startsWith("t")||o.startsWith("f"))d=0;else if(0===o.length||o.startsWith("P")||o.startsWith("L")||o.startsWith("Y")||o.startsWith("A"))d=1;else{d=2;const t=o.indexOf(":");-1!=t&&(o=o.substring(t+1));const i=o.indexOf("?");if(-1!=i&&(s=o.substring(i+1),o=o.substring(0,i)),o.startsWith("DLC2"))d=0;else{if(o.startsWith("DLS2")){let t;try{let e=o.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(o=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof o&&(o=JSON.stringify(o)),0===n.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),n=S(e)}!c&&t.sessionPassword&&(c=t.sessionPassword),e=t.remark}o&&"200001"!==o&&!o.startsWith("200001-")||(d=1)}}if(d&&(t||(a.crypto||(r="Please upgrade your browser to support online key."),a.crypto.subtle||(r="Require https to use online key in this browser."))),r){if(1!==d)throw new Error(r);d=0,console.warn(r),i._lastErrorCode=-1,i._lastErrorString=r}return 1===d&&(o="",console.warn("Applying for a public trial license ...")),{lt:d,l:o,ls:n,sp:c,rmk:e,cv:s}}throw new Error("Can't preprocess license again"+m)})(L);this._pLoad.task=async(a,o)=>{let n=L.engineResourcePath+L._workerName;L.engineResourcePath.startsWith(location.origin)||(n=await fetch(n).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),L._dbrWorker=new Worker(n),URL.revokeObjectURL(n),L._dbrWorker.onerror=e=>{let t=new Error(e.message);o(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,s=!1;1===e&&(s=!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,s||111==i.ltsErrorCode&&-1!=i.message.toLowerCase().indexOf("trial license")&&(s=!0)),s&&L.showDialog(i.success?"warn":"error",i.message),i.success?a():o(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:d,cv:L.authCacheVersion,fn:L.deviceFriendlyName,ls:i,sp:s,rmk:r})}}await this._pLoad}static async showDialog(e,t){await(async(e,t,i)=>{if(!e._bNeverShowDialog)try{let s=await fetch(e.engineResourcePath+"dls.license.dialog.html");if(!s.ok)throw Error("Get license dialog fail. Network Error: "+s.statusText);let a=await s.text();if(!a.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let r=document.createElement("div");r.innerHTML=a;let o=[];for(let e=0;e{if(e==t.target){n.remove();for(let e of o)e.remove()}}));else if(!d&&e.classList.contains("dls-license-icon-close"))d=e,e.addEventListener("click",(()=>{n.remove();for(let e of o)e.remove()}));else if(!l&&e.classList.contains("dls-license-icon-error"))l=e,"error"!=t&&e.remove();else if(!h&&e.classList.contains("dls-license-icon-warn"))h=e,"warn"!=t&&e.remove();else if(!_&&e.classList.contains("dls-license-msg-content")){_=e;let t=i;for(;t;){let i=t.indexOf("["),s=t.indexOf("]",i),a=t.indexOf("(",s),r=t.indexOf(")",a);if(-1==i||-1==s||-1==a||-1==r){e.appendChild(new Text(t));break}i>0&&e.appendChild(new Text(t.substring(0,i)));let o=document.createElement("a"),n=t.substring(i+1,s);o.innerText=n;let c=t.substring(a+1,r);o.setAttribute("href",c),o.setAttribute("target","_blank"),e.appendChild(o),t=t.substring(r+1)}}document.body.appendChild(n)}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 s=L._nextTaskID++;L._taskCallbackMap.set(s,(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:s,bScanner:e})}))}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.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=p,this._promiseStartScan=null,this.beepSound=new e({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}static async createInstance(){const 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,s,a,r,o){return await new Promise(((n,c)=>{let d=L._nextTaskID++;L._taskCallbackMap.set(d,(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 c(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 n(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,c(t)}})),this._timeEnterInnerDBR=Date.now(),L._onLog&&L._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),L._dbrWorker.postMessage({type:"decodeBuffer",id:d,instanceID:this._instanceID,body:{buffer:e,width:t,height:i,stride:s,format:a,orientation:r,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,s,a,r,o){L._onLog&&L._onLog("_decodeBuffer_Blob(buffer,width,height,stride,format)");const n=e.arrayBuffer?await e.arrayBuffer():await new Promise(((t,i)=>{let s=new FileReader;s.readAsArrayBuffer(e),s.onload=()=>{t(s.result)},s.onerror=()=>{i(s.error)}}));return await this._decodeBuffer_Uint8Array(new Uint8Array(n),t,i,s,a,r,o)}async decodeBuffer(e,t,i,s,a,r,o){let n;return L._onLog&&L._onLog("decodeBuffer(buffer,width,height,stride,format)"),L._onLog&&(this._timeStartDecode=Date.now()),e instanceof Uint8Array||e instanceof Uint8ClampedArray?n=await this._decodeBuffer_Uint8Array(e,t,i,s,a,r,o):e instanceof ArrayBuffer?n=await this._decodeBuffer_Uint8Array(new Uint8Array(e),t,i,s,a,r,o):e instanceof Blob&&(n=await this._decodeBuffer_Blob(e,t,i,s,a,r,o)),n}async _decodeFileInMemory_Uint8Array(e){return await new Promise(((t,i)=>{let s=L._nextTaskID++;L._taskCallbackMap.set(s,(e=>{if(e.success){let s;this._lastInnerDecodeDuration=e.duration;try{s=this._handleRetJsonString(e.decodeReturn)}catch(e){return i(e)}return t(s)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,i(t)}})),L._dbrWorker.postMessage({type:"decodeFileInMemory",id:s,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(t.barcodeFormatIds&~(T.BF_ONED|T.BF_QR_CODE|T.BF_PDF417|T.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|=D.IRT_TYPED_BARCODE_ZONE),await new Promise(((e,i)=>{let s=L._nextTaskID++;L._taskCallbackMap.set(s,(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:s,instanceID:this._instanceID,body:{settings:JSON.stringify(t)}})}))}async resetRuntimeSettings(){return this.userDefinedRegion=null,this.region=null,this.maxCvsSideLength=p,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=p,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);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 s=L._nextTaskID++;L._taskCallbackMap.set(s,(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:s,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){L._onLog&&L._onLog("_decode_Blob(blob: Blob)");let i=null,s=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(e)}catch(e){}i||(s=await function(e){return new Promise(((t,i)=>{let s=URL.createObjectURL(e),a=new Image;a.src=s,a.onload=()=>{URL.revokeObjectURL(a.src),t(a)},a.onerror=e=>{i(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}}))}(e));let a=await this._decode_Image(i||s,t);return i&&i.close(),a}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,s,a=e instanceof HTMLImageElement?e.naturalWidth:e.width,r=e instanceof HTMLImageElement?e.naturalHeight:e.height,o=Math.max(a,r);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(a*e),s=Math.round(r*e)}else i=a,s=r;this.canvas||(this.canvas=document.createElement("canvas"));const n=this.canvas;n.width===i&&n.height===s||(n.width=i,n.height=s),n.ctx2d||(n.ctx2d=n.getContext("2d",{willReadFrequently:!0}));n.ctx2d.drawImage(e,0,0,a,r,0,0,i,s);let c=await this._decode_Canvas(n,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return L.recalculateResultLocation(c,0,0,a,r,i,s),c}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,E.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,s,a=e.videoWidth,r=e.videoHeight,o=Math.max(a,r);if(o>this._maxCvsSideLength){let e=this._maxCvsSideLength/o;i=Math.round(a*e),s=Math.round(r*e)}else i=a,s=r;this.canvas||(this.canvas=document.createElement("canvas"));const n=this.canvas;n.width===i&&n.height===s||(n.width=i,n.height=s),n.ctx2d||(n.ctx2d=n.getContext("2d",{willReadFrequently:!0}));n.ctx2d.drawImage(e,0,0,a,r,0,0,i,s);let c=await this._decode_Canvas(n,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return L.recalculateResultLocation(c,0,0,a,r,i,s),c}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:s,height:a,colorMode:r,pixelFormat:o,stride:n,timeStamp:c}=e;let d;d=t&&t.bCopyData?new Uint8Array(e.data):e.data;let l=null;if(t?(l=JSON.parse(JSON.stringify(t)),l.timeStamp=c):l={timeStamp:c},o&&n)if("grey"===o)i=await this._decodeBuffer_Uint8Array(d,s,a,n,E.IPF_GrayScaled,0,l);else if("rgba"===o)i=await this._decodeBuffer_Uint8Array(d,s,a,n,E.IPF_ABGR_8888,0,l);else{if("bgra"!==o)throw new Error(`Pixel format '${o}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(d,s,a,n,E.IPF_ARGB_8888,0,l)}else if("grey"===r)i=await this._decodeBuffer_Uint8Array(d,s,a,s,E.IPF_GrayScaled,0,l);else if("rgba"===r)i=await this._decodeBuffer_Uint8Array(d,s,a,4*s,E.IPF_ABGR_8888,0,l);else{if("bgra"!==r)throw new Error(`Color mode '${r}' is not supported to decode.`);i=await this._decodeBuffer_Uint8Array(d,s,a,4*s,E.IPF_ARGB_8888,0,l)}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 s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="blob",s.send(),s.onloadend=async()=>{t(s.response)},s.onerror=()=>{i(new Error("Network Error: "+s.statusText))}}));return await this._decode_Blob(i,t)}static recalculateResultLocation(e,t,i,s,a,r,o){if(e.length>0)for(let n of e){let e=n.localizationResult;2==e.resultCoordinateType&&(e.x1*=.01*r,e.x2*=.01*r,e.x3*=.01*r,e.x4*=.01*r,e.y1*=.01*o,e.y2*=.01*o,e.y3*=.01*o,e.y4*=.01*o);let c=r/s,d=o/a;e.x1=e.x1/c+t,e.x2=e.x2/c+t,e.x3=e.x3/c+t,e.x4=e.x4/c+t,e.y1=e.y1/d+i,e.y2=e.y2/d+i,e.y3=e.y3/d+i,e.y4=e.y4/d+i,2==e.resultCoordinateType&&(e.x1*=100/s,e.x2*=100/s,e.x3*=100/s,e.x4*=100/s,e.y1*=100/a,e.y2*=100/a,e.y3*=100/a,e.y4*=100/a),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}static BarcodeReaderException(e,t){let i,s=A.DBR_UNKNOWN;return"number"==typeof e?(s=e,i=new Error(t)):i=new Error(e),i.code=s,i}_handleRetJsonString(e){let t=A;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,s){return await new Promise(((a,r)=>{let o=L._nextTaskID++;L._taskCallbackMap.set(o,(e=>{if(e.success){try{this._handleRetJsonString(e.setReturn)}catch(e){return r(e)}return a()}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,r(t)}})),L._dbrWorker.postMessage({type:"setModeArgument",id:o,instanceID:this._instanceID,body:{modeName:e,index:t,argumentName:i,argumentValue:s}})}))}async getModeArgument(e,t,i){return await new Promise(((s,a)=>{let r=L._nextTaskID++;L._taskCallbackMap.set(r,(e=>{if(e.success){let t;try{t=this._handleRetJsonString(e.getReturn)}catch(e){return a(e)}return s(t)}{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,a(t)}})),L._dbrWorker.postMessage({type:"getModeArgument",id:r,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,body:{isCharge:!0}})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let i of e)if(i.dataType==f.IMRDT_IMAGE)for(let e of i.results){const i=e.bytes;let s;switch(L._onLog&&L._onLog(" "+i.length+" "+i.byteLength+" "+e.width+" "+e.height+" "+e.stride+" "+e.format),e.format){case E.IPF_ABGR_8888:s=new Uint8ClampedArray(i);break;case E.IPF_RGB_888:{const e=i.length/3;s=new Uint8ClampedArray(4*e);for(let t=0;t=a)break;s[o]=s[o+1]=s[o+2]=(128&t)/128*255,s[o+3]=255,t<<=1}}break}default:console.warn("unknow intermediate image",e)}if(!s)continue;let a=new ImageData(s,e.width,e.height),r=document.createElement("canvas");r.width=e.width,r.height=e.height,r.getContext("2d").putImageData(a,0,0),t.push(r)}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|=D.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 s=L._nextTaskID++;L._taskCallbackMap.set(s,(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:s,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;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 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:s,sy:a,width:r,height:o,_sWidth:n,_sHeight:c}=e;t=i.map((e=>({resultState:e.resultState,localizationResult:JSON.parse(JSON.stringify(e.localizationResult))}))),L.recalculateResultLocation(t,s,a,n,c,r,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 s=Math.min(...e),a=Math.max(...t);s&&a&&(i=s-a)}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&&(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;const t=e=>this.dce.getDrawingLayers().some((t=>t.getId()===e));if(!t(3)&&!(null==e?void 0:e.length))return;this._dbrDrawingLayer=this.dce.getDrawingLayer(3)}const i=this._dbrDrawingLayer;e||(e=[]);let s=this._arrPolygons;for(let a=0;a{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.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})}}function M(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 O(e){return Math.abs(e)<1e-6?0:e<0?-1:1}function w(e,t,i,s){let a=e[0]*(i[1]-t[1])+t[0]*(e[1]-i[1])+i[0]*(t[1]-e[1]),r=e[0]*(s[1]-t[1])+t[0]*(e[1]-s[1])+s[0]*(t[1]-e[1]);return!((a^r)>=0&&0!==a&&0!==r)&&(a=i[0]*(e[1]-s[1])+s[0]*(i[1]-e[1])+e[0]*(s[1]-i[1]),r=i[0]*(t[1]-s[1])+s[0]*(i[1]-t[1])+t[0]*(s[1]-i[1]),!((a^r)>=0&&0!==a&&0!==r))}var F,B,N,b,P,v,V,x,U,k,G,Z,W,H,K,J,Y,Q,X,z,j,q,$,ee,te,ie,se;L._jsVersion="9.6.42",L._jsEditVersion="20240426",L._version=`loading...(JS ${L._jsVersion}.${L._jsEditVersion})`,L._license=R,L._sessionPassword=I,L.browserInfo=d,L._workerName=`dbr-${L._jsVersion}.browser.worker.js`,L._engineResourcePath=g,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 y,L._lastErrorCode=0,L._lastErrorString="",L._setWarnnedEx=new Set,L._defaultUIElementURL="@engineResourcePath/dbr.ui.html","function"==typeof SuppressedError&&SuppressedError;class ae extends L{static set _onLog(e){!function(e,t,i,s,a){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===s?a.call(e,i):a?a.value=i:t.set(e,i)}(ae,F,e,"f",B),t._onLog=e}static get _onLog(){return function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)}(ae,F,"f",B)}static get version(){return this._version+`(DCE ${t.getVersion()})`}static _fireHTTPSWarnning(){ae.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{ae.onWarning&&ae.onWarning({id:2,message:"Not connected via SSL (HTTPS), the SDK may not work correctly."})}),0)}static async testCameraAccess(){return t.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){if("boolean"!=typeof e&&!["image","camera"].includes(e))throw new Error("Invalid value.");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 cameraOpenTimeout(e){this.dce&&(this.dce.cameraOpenTimeout=e)}get cameraOpenTimeout(){return this.dce&&this.dce.cameraOpenTimeout}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()"),t.defaultUIElementURL=null,this.dce=await t.createInstance(),this.dce.cameraOpenTimeout<15e3&&(this.dce.cameraOpenTimeout=15e3),this.dce.refreshInterval=200,this.dce.framePixelFormat="grey",this.dce.maxCvsSideLength=this.maxCvsSideLength,this._drawingItemNamespace=i,["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:s,sy:a,width:r,height:o,stride:n,pixelFormat:c,timeStamp:d,_sWidth:l,_sHeight:h}=e,_={timeStamp:d};if("grey"===c)t=await this._decodeBuffer_Uint8Array(i,r,o,n,E.IPF_GrayScaled,0,_);else if("rgba"===c)t=await this._decodeBuffer_Uint8Array(i,r,o,n,E.IPF_ABGR_8888,0,_);else{if("bgra"!==c)throw new Error(`Pixel format '${c}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,r,o,n,E.IPF_ARGB_8888,0,_)}if(await this.clearMapDecodeRecord(),L.recalculateResultLocation(t,s,a,l,h,r,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}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._onPlayed=null}static async createInstance(e){const t=new ae;t._instanceID=await ae.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(ae.defaultUIElementURL),t.singleFrameMode&&console.warn("The `navigator.mediaDevices.getUserMedia` is unavailable. automatically change to `singleFrameMode`."),ae._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(t.barcodeFormatIds&~(T.BF_ONED|T.BF_QR_CODE|T.BF_PDF417|T.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 s=L._nextTaskID++;L._taskCallbackMap.set(s,(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:s,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 s=await this.dce.play(e,t,i);return this._fireResolutionWarning(),s}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:s,sy:a,width:r,height:o,stride:n,pixelFormat:c,timeStamp:d,_sWidth:l,_sHeight:h}=e,_={timeStamp:d};if("grey"===c)t=await this._decodeBuffer_Uint8Array(i,r,o,n,E.IPF_GrayScaled,0,_);else if("rgba"===c)t=await this._decodeBuffer_Uint8Array(i,r,o,n,E.IPF_ABGR_8888,0,_);else{if("bgra"!==c)throw new Error(`Pixel format '${c}' is not supported.`);t=await this._decodeBuffer_Uint8Array(i,r,o,n,E.IPF_ARGB_8888,0,_)}if(L.recalculateResultLocation(t,s,a,l,h,r,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=async()=>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,body:{isCharge:!1}})})),t=await e(),i=(e,t,i,s,a,r,o)=>{let n=r/s,c=o/a;e.x1=e.x1/n+t,e.x2=e.x2/n+t,e.x3=e.x3/n+t,e.x4=e.x4/n+t,e.y1=e.y1/c+i,e.y2=e.y2/c+i,e.y3=e.y3/c+i,e.y4=e.y4/c+i},n=e=>{if(!e)return null;const t={};let n,c,d,_,u;{const e=this.video.videoWidth*(1-this.autoZoomDetectionArea)/2,t=this.video.videoWidth*(1+this.autoZoomDetectionArea)/2,i=t,s=e,a=this.video.videoHeight*(1-this.autoZoomDetectionArea)/2,r=a,o=this.video.videoHeight*(1+this.autoZoomDetectionArea)/2;u={x1:e,x2:t,x3:i,x4:s,y1:a,y2:r,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 s=!1;const a=e.length;if(a<=2)return!1;for(let r=0;r0!=O(n.y-i)>0&&O(t-(i-o.y)*(o.x-n.x)/(o.y-n.y)-o.x)<0&&(s=!s)}return s}([{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)},s=(e,t)=>!!(w([e[0],e[1]],[e[2],e[3]],[t.x1,t.y1],[t.x2,t.y2])||w([e[0],e[1]],[e[2],e[3]],[t.x2,t.y2],[t.x3,t.y3])||w([e[0],e[1]],[e[2],e[3]],[t.x3,t.y3],[t.x4,t.y4])||w([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))||!!(s([t.x1,t.y1,t.x2,t.y2],e)||s([t.x2,t.y2,t.x3,t.y3],e)||s([t.x3,t.y3,t.x4,t.y4],e)||s([t.x4,t.y4,t.x1,t.y1],e)))},m=[];for(let t of e){if(t.resultType!==D.IRT_TYPED_BARCODE_ZONE)continue;const e=t.scaleDownRatio;for(let n of t.results){if(!n)continue;const t={x1:n.x1=n.x1*e,x2:n.x2=n.x2*e,x3:n.x3=n.x3*e,x4:n.x4=n.x4*e,y1:n.y1=n.y1*e,y2:n.y2=n.y2*e,y3:n.y4=n.y3*e,y4:n.y4=n.y4*e};i(t,s,a,l,h,r,o),g(u,t)&&m.push(n)}}const R=(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-r/2)*(t-r/2)+(i-o/2)*(i-o/2)};let i,s=e.filter((e=>e.barcodeFormat==T.BF_QR_CODE||e.barcodeFormat==T.BF_DATAMATRIX));if(s.length||(s=e.filter((e=>e.barcodeFormat==T.BF_ONED)),s.length||(s=e)),!s.length)return null;i=s[0];let a=t(i);if(1!=s.length)for(let e=1;e1.1*i.confidence?(i=s[e],a=r):s[e].confidence>.9*i.confidence&&r!0===e)).length>=this.suggestTipFrameLimit[1]){this.suggestTipFrameArray.length=0;const e=c.x3-c.x1,t=c.y3-c.y1;c.result.moduleSizet?e>r*this.hugeBarcodeTipLimit?this.dce&&this.dce.suggestTip("huge-barcode","Please zoom out or move farther."):e>.6*r&&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 t=(1-this.autoZoomTargetBorder)/2;const n=c.x1/l,d=(l-c.x3)/l,_=c.y1/h,u=(h-c.y3)/h;if(n>e&&d>e&&_>e&&u>e&&c.result.moduleSize{}))),this.autoZoomInFrameArray.filter((e=>!0===e)).length>=this.autoZoomInFrameLimit[1]){this.autoZoomInFrameArray.length=0;const e=[(.5-t)/(.5-n),(.5-t)/(.5-d),(.5-t)/(.5-_),(.5-t)/(.5-u)].filter((e=>e>0)),i=Math.min(...e,this.autoZoomInIdealModuleSize/c.result.moduleSize),s=this.dce.getZoomSettings().factor;let a=Math.max(Math.pow(s*i,1/this.autoZoomInMaxTimes),this.autoZoomInMinStep);a=Math.min(a,i);const r=s*a;try{await this.setZoom({factor:r})}catch(e){const t=e.message||e;console.warn(t)}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(c,s,a,l,h,r,o);try{await this.setFocus({mode:"manual",area:{centerPoint:{x:(c.x1+c.x3)/2+"px",y:(c.y1+c.y3)/2+"px"},width:c.x3-c.x1+"px",height:c.y3-c.y1+"px"}})}catch(e){const t=e.message||e;console.warn(t)}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-n),(.5-t)/(.5-d),(.5-t)/(.5-_),(.5-t)/(.5-u)].filter((e=>e>0));let i=Math.min(...e)*this.dce.getZoomSettings().factor;try{await this.setZoom({factor:i})}catch(e){const t=e.message||e;console.warn(t)}this.dce.clearFrameBuffer(),this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((()=>{})))}}}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(c,s,a,l,h,r,o),await this.setFocus({mode:"manual",area:{centerPoint:{x:(c.x1+c.x3)/2+"px",y:(c.y1+c.y3)/2+"px"},width:c.x3-c.x1+"px",height:c.y3-c.y1+"px"}})}catch(e){const t=e.message||e;console.warn(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 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);try{await this.setZoom({factor:i})}catch(e){const t=e.message||e;console.warn(t)}this.dce.clearFrameBuffer()}}this.autoFocus&&(this.nextActionInIdealZoom="focus",this.setFocus({mode:"continuous"}).catch((()=>{})))}else this.autoFocus&&(this.autoFocusFrameArray.length=0,this.setFocus({mode:"continuous"}).catch((()=>{})))}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 s=()=>{let s=0;if(this.region instanceof Array){let a=0,r=0;a=i+1>=this.region.length?0:i+1,r=a+1>=this.region.length?0:a+1,s=e[a]&&e[a].length&&t[r]&&t[r].length?Math.min(...e[a])-Math.max(...t[r]):0}else if(t&&t.length){let i=Math.min(...e),a=Math.max(...t);i&&a&&(s=i-a)}else s=0;return s>0?s: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=s()+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&&(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._drawResults(null),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,s,a=3e3,r=!0){this.dce&&this.dce.showTip(e,t,i,s,a,r)}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()}convertToPageCoordinates(e){return this.dce.convertToPageCoordinates(e)}convertToClientCoordinates(e){return this.dce.convertToClientCoordinates(e)}destroyContext(){this.close(),this.dce&&this.dce.dispose(!1),this.bDestroyed||super.destroyContext()}}F=ae,B={value:void 0},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"}(N||(N={})),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"}(b||(b={})),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=-1]="BF2_ALL"}(P||(P={})),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"}(V||(V={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(x||(x={})),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"}(k||(k={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(G||(G={})),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"}(Z||(Z={})),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"}(H||(H={})),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"}(K||(K={})),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"}(J||(J={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(Y||(Y={})),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"}(Q||(Q={})),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"}(X||(X={})),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"}(z||(z={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(j||(j={})),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"}(q||(q={})),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"}($||($={})),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"}(ee||(ee={})),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"}(te||(te={})),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"}(ie||(ie={})),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"}(se||(se={}));export{L as BarcodeReader,ae as BarcodeScanner,N as EnumBarcodeColourMode,b as EnumBarcodeComplementMode,T as EnumBarcodeFormat,P as EnumBarcodeFormat_2,v as EnumBinarizationMode,V as EnumClarityCalculationMethod,x as EnumClarityFilterMode,U as EnumColourClusteringMode,k as EnumColourConversionMode,G as EnumConflictMode,H as EnumDPMCodeReadingMode,Z as EnumDeblurMode,W as EnumDeformationResistingMode,A as EnumErrorCode,K as EnumGrayscaleTransformationMode,f as EnumIMResultDataType,E as EnumImagePixelFormat,J as EnumImagePreprocessingMode,Y as EnumIntermediateResultSavingMode,D as EnumIntermediateResultType,Q as EnumLocalizationMode,X as EnumQRCodeErrorCorrectionLevel,z as EnumRegionPredetectionMode,j as EnumResultCoordinateType,q as EnumResultType,$ as EnumScaleUpMode,ee as EnumTerminatePhase,te as EnumTextFilterMode,ie as EnumTextResultOrderMode,se as EnumTextureDetectionMode}; diff --git a/dist/dbr.pure.js b/dist/dbr.pure.js index 10447ae..1d958c8 100644 --- a/dist/dbr.pure.js +++ b/dist/dbr.pure.js @@ -2,10 +2,10 @@ * Dynamsoft JavaScript Library * @product Dynamsoft Barcode Reader JS Edition * @website http://www.dynamsoft.com - * @copyright Copyright 2023, Dynamsoft Corporation + * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft - * @version 9.6.32 (js 20231027) + * @version 9.6.42 (js 20240426) * @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";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 f=s._node;if(r._webAudio){var g=function(){r._playLock=!1,m(),r._refreshBuffer(s);var e=s._muted||r._muted?0:s._volume;f.gain.setValueAtTime(e,n.ctx.currentTime),s._playStart=n.ctx.currentTime,void 0===f.bufferSource.start?s._loop?f.bufferSource.noteGrainOn(0,d,86400):f.bufferSource.noteGrainOn(0,d,u):s._loop?f.bufferSource.start(0,d,86400):f.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 p=function(){f.currentTime=d,f.muted=s._muted||r._muted||n._muted||f.muted,f.volume=s._volume*n.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,m(),o.then((function(){r._playLock=!1,f._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)),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),l):(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 A=window&&window.ejecta||!f.readyState&&n._navigator.isCocoonJS;if(f.readyState>=3||A)p();else{r._playLock=!0,r._state="loading";var E=function(){r._state="loaded",p(),f.removeEventListener(n._canPlayEvent,E,!1)};f.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(I)try{(await g.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===p.browser&&p.version>66||"Safari"===p.browser&&p.version>13||"OPR"===p.browser&&p.version>43||"Edge"===p.browser&&p.version;const T=(()=>{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"./"})(),D=" is not allowed to change after `createInstance` or `loadWasm` is called.",S=!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"))||"",C=!l&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",y=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&&(b(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,b(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(p.OS)?2048:4096;class P{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.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,this.beepSound=new r({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}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`"+D);n._license=t})(P,e)}static get productKeys(){return this._license}static set productKeys(e){P.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){P.license=e}static get organizationID(){return this._license}static set organizationID(e){P.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+D);n._sessionPassword=t})(P,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:A,worker:E,getUserMedia:I,camera:await R(),browser:p.browser,version:p.version,OS:p.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.");P._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`"+D);n._licenseServer=y(t)})(P,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+D);n._deviceFriendlyName=t||""})(P,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.");P.__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=P._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",P.engineResourcePath)}static set defaultUIElementURL(e){P._defaultUIElementURL=e}static _fireHTTPSWarnning(){P.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{P.onWarning&&P.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;P._onLog&&P._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))}))),P.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&&(P._onLog&&P._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(!P.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=y(e)}!i&&t.sessionPassword&&(i=t.sessionPassword),e=t.remark}("200001"===r||r.startsWith("200001-"))&&(o&&o.length||(r="")),r||(a=1)}if(a&&(c.crypto||(n="Please upgrade your browser to support online key."),c.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"+D)})(P);this._pLoad.task=async(i,a)=>{let s=P.engineResourcePath+P._workerName;P.engineResourcePath.startsWith(location.origin)||(s=await fetch(s).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),P._dbrWorker=new Worker(s),P._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},P._dbrWorker.onmessage=async t=>{let n=t.data?t.data:t;switch(n.type){case"log":P._onLog&&P._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?(P._dbrWorker.onerror=null,P._version=n.version+"(JS "+P._jsVersion+"."+P._jsEditVersion+")",P._onLog&&P._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&&P.showDialog(n.success?"warn":"error",n.message),n.success?i():a(t);break}case"task":{let e=n.id,t=n.body;try{P._taskCallbackMap.get(e)(t),P._taskCallbackMap.delete(e)}catch(t){throw P._taskCallbackMap.delete(e),t}break}default:P._onLog&&P._onLog(t)}},P._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:P.engineResourcePath,bUseFullFeature:P._bUseFullFeature,bd:P._bWasmDebug,v:P._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:p,cv:P.authCacheVersion,fn:P.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 P.loadWasm(),await new Promise(((t,n)=>{let r=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}static async createInstance(){const e=new P;return e._instanceID=await P.createInstanceInWorker(),P._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){P._onLog&&P._onLog("decode(source: any)"),P._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):P.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):P.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=P._nextTaskID++;P._taskCallbackMap.set(d,(e=>{if(e.success){let t,n=P._onLog?Date.now():0;P._onLog&&P._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return _(e)}if(P._onLog){let e=Date.now();P._onLog("DBR getting message from worker timestamp: "+n),P._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),P._onLog("From DBR entering worker to returning message from worker costs: "+(n-this._timeEnterInnerDBR)),P._onLog("Handling results from DBR worker costs: "+(e-n)),P._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(),P._onLog&&P._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),P._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]),P._onLog&&a&&a.timeStamp&&P._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-a.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,r,o,i,a){P._onLog&&P._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 P._onLog&&P._onLog("decodeBuffer(buffer,width,height,stride,format)"),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=P._nextTaskID++;P._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)}})),P._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(!P._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=P._nextTaskID++;P._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)}})),P._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=N,await new Promise(((e,t)=>{let n=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){P._onLog&&P._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){P._onLog&&P._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}));s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl);let _=await this._decode_Canvas(s,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(_,0,0,o,i,n,r),_}async _decode_Canvas(t,n){if(P._onLog&&P._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(P._onLog&&P._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}));s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r);let _=await this._decode_Canvas(s,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(_,0,0,o,i,n,r),_}async _decode_DCEFrame(t,n){if(P._onLog&&P._onLog("_decode_DCEFrame(dceFrame)"),!P.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(P._onLog&&P._onLog("_decode_DSImage(dsImage)"),!P.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 P._onLog&&P._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),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}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&&!P._setWarnnedEx.has(t.description)&&(P._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==n.DBR_SUCCESS)return t.data;throw P.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,n,r){return await new Promise(((o,i)=>{let a=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID,body:{isCharge:!0}})}))}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(P._onLog&&P._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=P._nextTaskID++;P._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)}})),P._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(!P._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=P._nextTaskID++;P._taskCallbackMap.set(r,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),P._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 P._onLog&&P._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));P._onLog&&P._onLog("======= once read ======="),P._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(),!P.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return P._onLog&&P._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))}))),P.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(P._onLog&&P._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&&(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"),P._onLog&&P._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(P._onLog&&P._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 P._onLog&&P._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.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(P._onLog&&P._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||this._promiseStartScan)&&this.stopScanning(),this.setImageSource(null);let e=P._nextTaskID++;P._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),P._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}var F,x,V,k,G,U,H,W,K,Z,Y,J,X,Q,j,q,z,$,ee,te,ne,re,oe,ie,ae,se;P._jsVersion="9.6.32",P._jsEditVersion="20231027",P._version=`loading...(JS ${P._jsVersion}.${P._jsEditVersion})`,P._license=S,P._sessionPassword=C,P.browserInfo=p,P._workerName=`dbr-${P._jsVersion}.browser.worker.js`,P._engineResourcePath=T,P._licenseServer=[],P._deviceFriendlyName="",P._isShowRelDecodeTimeInResults=!1,P._bWasmDebug=!1,P._bNeverShowDialog=!1,P.__bUseFullFeature=!0,P._nextTaskID=0,P._taskCallbackMap=new Map,P._pLoad=new B,P._lastErrorCode=0,P._lastErrorString="",P._setWarnnedEx=new Set,P._defaultUIElementURL="@engineResourcePath/dbr.ui.html",e.EnumBarcodeColourMode=void 0,(F=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[F.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",F[F.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",F[F.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",F[F.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",F[F.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",F[F.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",F[F.BICM_SKIP=0]="BICM_SKIP",F[F.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(x=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[x.BCM_AUTO=1]="BCM_AUTO",x[x.BCM_GENERAL=2]="BCM_GENERAL",x[x.BCM_SKIP=0]="BCM_SKIP",x[x.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=-1]="BF2_ALL",e.EnumBinarizationMode=void 0,(k=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[k.BM_AUTO=1]="BM_AUTO",k[k.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",k[k.BM_SKIP=0]="BM_SKIP",k[k.BM_THRESHOLD=4]="BM_THRESHOLD",k[k.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(G=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[G.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(U=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[U.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(H=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[H.CCM_AUTO=1]="CCM_AUTO",H[H.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",H[H.CCM_SKIP=0]="CCM_SKIP",H[H.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(W=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[W.CICM_GENERAL=1]="CICM_GENERAL",W[W.CICM_SKIP=0]="CICM_SKIP",W[W.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,(Z=e.EnumDeblurMode||(e.EnumDeblurMode={}))[Z.DM_SKIP=0]="DM_SKIP",Z[Z.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",Z[Z.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",Z[Z.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",Z[Z.DM_SMOOTHING=8]="DM_SMOOTHING",Z[Z.DM_MORPHING=16]="DM_MORPHING",Z[Z.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",Z[Z.DM_SHARPENING=64]="DM_SHARPENING",Z[Z.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",Z[Z.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(Y=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[Y.DRM_AUTO=1]="DRM_AUTO",Y[Y.DRM_GENERAL=2]="DRM_GENERAL",Y[Y.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",Y[Y.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",Y[Y.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",Y[Y.DRM_SKIP=0]="DRM_SKIP",Y[Y.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(J=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[J.DPMCRM_AUTO=1]="DPMCRM_AUTO",J[J.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",J[J.DPMCRM_SKIP=0]="DPMCRM_SKIP",J[J.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(X=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[X.GTM_INVERTED=1]="GTM_INVERTED",X[X.GTM_ORIGINAL=2]="GTM_ORIGINAL",X[X.GTM_SKIP=0]="GTM_SKIP",X[X.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(Q=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[Q.IPM_AUTO=1]="IPM_AUTO",Q[Q.IPM_GENERAL=2]="IPM_GENERAL",Q[Q.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",Q[Q.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",Q[Q.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",Q[Q.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",Q[Q.IPM_SKIP=0]="IPM_SKIP",Q[Q.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(j=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[j.IRSM_MEMORY=1]="IRSM_MEMORY",j[j.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",j[j.IRSM_BOTH=4]="IRSM_BOTH",e.EnumLocalizationMode=void 0,(q=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[q.LM_SKIP=0]="LM_SKIP",q[q.LM_AUTO=1]="LM_AUTO",q[q.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",q[q.LM_LINES=8]="LM_LINES",q[q.LM_STATISTICS=4]="LM_STATISTICS",q[q.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",q[q.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",q[q.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",q[q.LM_CENTRE=128]="LM_CENTRE",q[q.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",q[q.LM_REV=2147483648]="LM_REV",e.EnumPDFReadingMode=void 0,(z=e.EnumPDFReadingMode||(e.EnumPDFReadingMode={}))[z.PDFRM_RASTER=1]="PDFRM_RASTER",z[z.PDFRM_AUTO=2]="PDFRM_AUTO",z[z.PDFRM_VECTOR=4]="PDFRM_VECTOR",z[z.PDFRM_REV=2147483648]="PDFRM_REV",e.EnumQRCodeErrorCorrectionLevel=void 0,($=e.EnumQRCodeErrorCorrectionLevel||(e.EnumQRCodeErrorCorrectionLevel={}))[$.QRECL_ERROR_CORRECTION_H=0]="QRECL_ERROR_CORRECTION_H",$[$.QRECL_ERROR_CORRECTION_L=1]="QRECL_ERROR_CORRECTION_L",$[$.QRECL_ERROR_CORRECTION_M=2]="QRECL_ERROR_CORRECTION_M",$[$.QRECL_ERROR_CORRECTION_Q=3]="QRECL_ERROR_CORRECTION_Q",e.EnumRegionPredetectionMode=void 0,(ee=e.EnumRegionPredetectionMode||(e.EnumRegionPredetectionMode={}))[ee.RPM_AUTO=1]="RPM_AUTO",ee[ee.RPM_GENERAL=2]="RPM_GENERAL",ee[ee.RPM_GENERAL_RGB_CONTRAST=4]="RPM_GENERAL_RGB_CONTRAST",ee[ee.RPM_GENERAL_GRAY_CONTRAST=8]="RPM_GENERAL_GRAY_CONTRAST",ee[ee.RPM_GENERAL_HSV_CONTRAST=16]="RPM_GENERAL_HSV_CONTRAST",ee[ee.RPM_SKIP=0]="RPM_SKIP",ee[ee.RPM_REV=2147483648]="RPM_REV",e.EnumResultCoordinateType=void 0,(te=e.EnumResultCoordinateType||(e.EnumResultCoordinateType={}))[te.RCT_PIXEL=1]="RCT_PIXEL",te[te.RCT_PERCENTAGE=2]="RCT_PERCENTAGE",e.EnumResultType=void 0,(ne=e.EnumResultType||(e.EnumResultType={}))[ne.RT_STANDARD_TEXT=0]="RT_STANDARD_TEXT",ne[ne.RT_RAW_TEXT=1]="RT_RAW_TEXT",ne[ne.RT_CANDIDATE_TEXT=2]="RT_CANDIDATE_TEXT",ne[ne.RT_PARTIAL_TEXT=3]="RT_PARTIAL_TEXT",e.EnumScaleUpMode=void 0,(re=e.EnumScaleUpMode||(e.EnumScaleUpMode={}))[re.SUM_AUTO=1]="SUM_AUTO",re[re.SUM_LINEAR_INTERPOLATION=2]="SUM_LINEAR_INTERPOLATION",re[re.SUM_NEAREST_NEIGHBOUR_INTERPOLATION=4]="SUM_NEAREST_NEIGHBOUR_INTERPOLATION",re[re.SUM_SKIP=0]="SUM_SKIP",re[re.SUM_REV=2147483648]="SUM_REV",e.EnumTerminatePhase=void 0,(oe=e.EnumTerminatePhase||(e.EnumTerminatePhase={}))[oe.TP_REGION_PREDETECTED=1]="TP_REGION_PREDETECTED",oe[oe.TP_IMAGE_PREPROCESSED=2]="TP_IMAGE_PREPROCESSED",oe[oe.TP_IMAGE_BINARIZED=4]="TP_IMAGE_BINARIZED",oe[oe.TP_BARCODE_LOCALIZED=8]="TP_BARCODE_LOCALIZED",oe[oe.TP_BARCODE_TYPE_DETERMINED=16]="TP_BARCODE_TYPE_DETERMINED",oe[oe.TP_BARCODE_RECOGNIZED=32]="TP_BARCODE_RECOGNIZED",e.EnumTextFilterMode=void 0,(ie=e.EnumTextFilterMode||(e.EnumTextFilterMode={}))[ie.TFM_AUTO=1]="TFM_AUTO",ie[ie.TFM_GENERAL_CONTOUR=2]="TFM_GENERAL_CONTOUR",ie[ie.TFM_SKIP=0]="TFM_SKIP",ie[ie.TFM_REV=2147483648]="TFM_REV",e.EnumTextResultOrderMode=void 0,(ae=e.EnumTextResultOrderMode||(e.EnumTextResultOrderMode={}))[ae.TROM_CONFIDENCE=1]="TROM_CONFIDENCE",ae[ae.TROM_POSITION=2]="TROM_POSITION",ae[ae.TROM_FORMAT=4]="TROM_FORMAT",ae[ae.TROM_SKIP=0]="TROM_SKIP",ae[ae.TROM_REV=2147483648]="TROM_REV",e.EnumTextureDetectionMode=void 0,(se=e.EnumTextureDetectionMode||(e.EnumTextureDetectionMode={}))[se.TDM_AUTO=1]="TDM_AUTO",se[se.TDM_GENERAL_WIDTH_CONCENTRATION=2]="TDM_GENERAL_WIDTH_CONCENTRATION",se[se.TDM_SKIP=0]="TDM_SKIP",se[se.TDM_REV=2147483648]="TDM_REV",e.BarcodeReader=P,Object.defineProperty(e,"__esModule",{value:!0})})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("dynamsoft-camera-enhancer")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-camera-enhancer"],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,n=t?{}:self;let r,o,i,a,s;"undefined"!=typeof navigator&&(r=navigator,o=r.userAgent,i=r.platform,a=r.mediaDevices),function(){if(!t){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:r.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:i,search:"Win"},Mac:{str:i},Linux:{str:i}};let n="unknownBrowser",a=0,_="unknownOS";for(let t in e){const r=e[t]||{};let i=r.str||o,s=r.search||t,_=r.verStr||o,d=r.verSearch||t;if(d instanceof Array||(d=[d]),-1!=i.indexOf(s)){n=t;for(let e of d){let t=_.indexOf(e);if(-1!=t){a=parseFloat(_.substring(t+e.length+1));break}}break}}for(let e in t){const n=t[e]||{};let r=n.str||o,i=n.search||e;if(-1!=r.indexOf(i)){_=e;break}}"Linux"==_&&-1!=o.indexOf("Windows NT")&&(_="HarmonyOS"),s={browser:n,version:a,OS:_}}t&&(s={browser:"ssr",version:0,OS:"ssr"})}();const _="undefined"!=typeof WebAssembly&&o&&!(/Safari/.test(o)&&!/Chrome/.test(o)&&/\(.+\s11_2_([2-6]).*\)/.test(o)),d=!("undefined"==typeof Worker),u=!(!a||!a.getUserMedia),l=async()=>{let e=!1;if(u)try{(await a.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(!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"./"})(),h=" is not allowed to change after `createInstance` or `loadWasm` is called.",m=!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"))||"",f=!t&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword")||"",g=e=>{if(null==e)e=[];else{e=e instanceof Array?[...e]:[e];for(let n=0;ne&&"object"==typeof e&&"function"==typeof e.then;class D extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(T(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,T(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}}var S=function(){this.init()};S.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||b(),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 n=0;n=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,b()),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 n=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",o=r.match(/OPR\/([0-6].)/g),i=o&&parseInt(o[0].split("/")[1],10)<33,a=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),s=r.match(/Version\/(.*?) /),_=a&&s&&parseInt(s[1],10)<15;return e._codecs={mp3:!(i||!n&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!n,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:!(_||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(_||!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(n){for(;e._html5AudioPool.length0?a._seek:n._sprite[e][0]/1e3),d=Math.max(0,(n._sprite[e][0]+n._sprite[e][1])/1e3-_),u=1e3*d/Math.abs(a._rate),l=n._sprite[e][0]/1e3,c=(n._sprite[e][0]+n._sprite[e][1])/1e3;a._sprite=e,a._ended=!1;var h=function(){a._paused=!1,a._seek=_,a._start=l,a._stop=c,a._loop=!(!a._loop&&!n._sprite[e][2])};if(!(_>=c)){var m=a._node;if(n._webAudio){var f=function(){n._playLock=!1,h(),n._refreshBuffer(a);var e=a._muted||n._muted?0:a._volume;m.gain.setValueAtTime(e,C.ctx.currentTime),a._playStart=C.ctx.currentTime,void 0===m.bufferSource.start?a._loop?m.bufferSource.noteGrainOn(0,_,86400):m.bufferSource.noteGrainOn(0,_,d):a._loop?m.bufferSource.start(0,_,86400):m.bufferSource.start(0,_,d),u!==1/0&&(n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),u)),t||setTimeout((function(){n._emit("play",a._id),n._loadQueue()}),0)};"running"===C.state&&"interrupted"!==C.ctx.state?f():(n._playLock=!0,n.once("resume",f),n._clearTimer(a._id))}else{var g=function(){m.currentTime=_,m.muted=a._muted||n._muted||C._muted||m.muted,m.volume=a._volume*C.volume(),m.playbackRate=a._rate;try{var r=m.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(n._playLock=!0,h(),r.then((function(){n._playLock=!1,m._unlocked=!0,t?n._loadQueue():n._emit("play",a._id)})).catch((function(){n._playLock=!1,n._emit("playerror",a._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."),a._ended=!0,a._paused=!0}))):t||(n._playLock=!1,h(),n._emit("play",a._id)),m.playbackRate=a._rate,m.paused)return void n._emit("playerror",a._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||a._loop?n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),u):(n._endTimers[a._id]=function(){n._ended(a),m.removeEventListener("ended",n._endTimers[a._id],!1)},m.addEventListener("ended",n._endTimers[a._id],!1))}catch(e){n._emit("playerror",a._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===m.src&&(m.src=n._src,m.load());var p=window&&window.ejecta||!m.readyState&&C._navigator.isCocoonJS;if(m.readyState>=3||p)g();else{n._playLock=!0,n._state="loading";var A=function(){n._state="loaded",g(),m.removeEventListener(C._canPlayEvent,A,!1)};m.addEventListener(C._canPlayEvent,A,!1),n._clearTimer(a._id)}}return a._id}n._ended(a)},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(o[0],10):e=parseFloat(o[0]):o.length>=2&&(e=parseFloat(o[0]),t=parseInt(o[1],10)),!(void 0!==e&&e>=0&&e<=1))return(n=t?r._soundById(t):r._sounds[0])?n._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,o)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var i=0;i0?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,n=t._soundById(e);return n&&n._interval&&(t._webAudio&&n._node.gain.cancelScheduledValues(C.ctx.currentTime),clearInterval(n._interval),n._interval=null,t.volume(n._fadeTo,e),n._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(o[0],10):e=parseFloat(o[0])}else 2===o.length&&(e=parseFloat(o[0]),t=parseInt(o[1],10));if("number"!=typeof e)return(n=r._soundById(t))?n._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,o)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var i=0;i=0?t=parseInt(r[0],10):n._sounds.length&&(t=n._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"!==n._state||n._playLock))return n._queue.push({event:"seek",action:function(){n.seek.apply(n,r)}}),n;var o=n._soundById(t);if(o){if(!("number"==typeof e&&e>=0)){if(n._webAudio){var i=n.playing(t)?C.ctx.currentTime-o._playStart:0,a=o._rateSeek?o._rateSeek-o._seek:0;return o._seek+(a+i*Math.abs(o._rate))}return o._node.currentTime}var s=n.playing(t);s&&n.pause(t,!0),o._seek=e,o._ended=!1,n._clearTimer(t),n._webAudio||!o._node||isNaN(o._node.duration)||(o._node.currentTime=e);var _=function(){s&&n.play(t,!0),n._emit("seek",t)};if(s&&!n._webAudio){var d=function(){n._playLock?setTimeout(d,0):_()};setTimeout(d,0)}else _()}return n},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&&C._howls.splice(r,1);var o=!0;for(n=0;n=0){o=!1;break}return M&&o&&delete M[e._src],C.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,n=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(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 v=function(e){this._parent=e,this.init()};v.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,n=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(n,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=n*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 M={},L=function(e){var t=e._src;if(M[t])return e._duration=M[t].duration,void B(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),r=new Uint8Array(n.length),o=0;o0?(M[t._src]=e,B(t,e)):n()};"undefined"!=typeof Promise&&1===C.ctx.decodeAudioData.length?C.ctx.decodeAudioData(e).then(r).catch(n):C.ctx.decodeAudioData(e,r,n)},B=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())},b=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+)?/),n=t?parseInt(t[1],10):null;if(e&&n&&n<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,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{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+h);n._license=t})(P,e)}static get productKeys(){return this._license}static set productKeys(e){P.license=e}static get handshakeCode(){return this._license}static set handshakeCode(e){P.license=e}static get organizationID(){return this._license}static set organizationID(e){P.license=e}static set sessionPassword(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`sessionPassword`"+h);n._sessionPassword=t})(P,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:_,worker:d,getUserMedia:u,camera:await l(),browser:s.browser,version:s.version,OS:s.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.");P._engineResourcePath=(e=>{if(null==e&&(e="./"),t);else{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`"+h);n._licenseServer=g(t)})(P,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){((e,t)=>{const n=e;if(!n._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+h);n._deviceFriendlyName=t||""})(P,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.");P.__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=P._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",P.engineResourcePath)}static set defaultUIElementURL(e){P._defaultUIElementURL=e}static _fireHTTPSWarnning(){P.onWarning&&location&&"https:"!==location.protocol&&setTimeout((()=>{P.onWarning&&P.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 y({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;P._onLog&&P._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))}))),P.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&&(P._onLog&&P._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(!P.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:r,sp:o,rmk:i}=((e,t=!1)=>{const r=e;if(r._pLoad.isEmpty){let e,o,i,a=r._license||"",s=JSON.parse(JSON.stringify(r._licenseServer)),_=r._sessionPassword,d=0;if(a.startsWith("t")||a.startsWith("f"))d=0;else if(0===a.length||a.startsWith("P")||a.startsWith("L")||a.startsWith("Y")||a.startsWith("A"))d=1;else{d=2;const t=a.indexOf(":");-1!=t&&(a=a.substring(t+1));const n=a.indexOf("?");if(-1!=n&&(o=a.substring(n+1),a=a.substring(0,n)),a.startsWith("DLC2"))d=0;else{if(a.startsWith("DLS2")){let t;try{let e=a.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(a=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof a&&(a=JSON.stringify(a)),0===s.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),s=g(e)}!_&&t.sessionPassword&&(_=t.sessionPassword),e=t.remark}a&&"200001"!==a&&!a.startsWith("200001-")||(d=1)}}if(d&&(t||(n.crypto||(i="Please upgrade your browser to support online key."),n.crypto.subtle||(i="Require https to use online key in this browser."))),i){if(1!==d)throw new Error(i);d=0,console.warn(i),r._lastErrorCode=-1,r._lastErrorString=i}return 1===d&&(a="",console.warn("Applying for a public trial license ...")),{lt:d,l:a,ls:s,sp:_,rmk:e,cv:o}}throw new Error("Can't preprocess license again"+h)})(P);this._pLoad.task=async(n,a)=>{let _=P.engineResourcePath+P._workerName;P.engineResourcePath.startsWith(location.origin)||(_=await fetch(_).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),P._dbrWorker=new Worker(_),URL.revokeObjectURL(_),P._dbrWorker.onerror=e=>{let t=new Error(e.message);a(t)},P._dbrWorker.onmessage=async t=>{let r=t.data?t.data:t;switch(r.type){case"log":P._onLog&&P._onLog(r.message);break;case"load":{r.message&&(r.message=r.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let t,o=!1;1===e&&(o=!0,r.message||(r.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),r.success?(P._dbrWorker.onerror=null,P._version=r.version+"(JS "+P._jsVersion+"."+P._jsEditVersion+")",P._onLog&&P._onLog("load dbr worker success"),r.message&&console.warn(r.message)):(t=new Error(r.message),t.stack=r.stack+"\n"+t.stack,t.ltsErrorCode=r.ltsErrorCode,o||111==r.ltsErrorCode&&-1!=r.message.toLowerCase().indexOf("trial license")&&(o=!0)),o&&P.showDialog(r.success?"warn":"error",r.message),r.success?n():a(t);break}case"task":{let e=r.id,t=r.body;try{P._taskCallbackMap.get(e)(t),P._taskCallbackMap.delete(e)}catch(t){throw P._taskCallbackMap.delete(e),t}break}default:P._onLog&&P._onLog(t)}},P._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:P.engineResourcePath,bUseFullFeature:P._bUseFullFeature,bd:P._bWasmDebug,v:P._jsVersion,brtk:!!e,bptk:1===e,l:t,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:s,cv:P.authCacheVersion,fn:P.deviceFriendlyName,ls:r,sp:o,rmk:i})}}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 P.loadWasm(),await new Promise(((t,n)=>{let r=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"createInstance",id:r,bScanner:e})}))}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.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,this.beepSound=new y({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}static async createInstance(){const e=new P;return e._instanceID=await P.createInstanceInWorker(),P._fireHTTPSWarnning(),e}async clearMapDecodeRecord(){return await new Promise(((e,t)=>{let n=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"clearMapDecodeRecord",id:n,instanceID:this._instanceID})}))}async decode(e){P._onLog&&P._onLog("decode(source: any)"),P._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):P.isDCEFrame(e)?(t.bCopyData=!0,await this._decode_DCEFrame(e,t)):P.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=P._nextTaskID++;P._taskCallbackMap.set(d,(e=>{if(e.success){let t,n=P._onLog?Date.now():0;P._onLog&&P._onLog("worker return result: "+n),this._lastInnerDecodeDuration=e.duration;try{t=this._handleRetJsonString(e.decodeReturn)}catch(e){return _(e)}if(P._onLog){let e=Date.now();P._onLog("DBR getting message from worker timestamp: "+n),P._onLog("From DBR staring decoding to entering worker costs: "+(this._timeEnterInnerDBR-this._timeStartDecode)),P._onLog("From DBR entering worker to returning message from worker costs: "+(n-this._timeEnterInnerDBR)),P._onLog("Handling results from DBR worker costs: "+(e-n)),P._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(),P._onLog&&P._onLog("Sending buffer to worker timestamp:"+this._timeEnterInnerDBR),P._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]),P._onLog&&a&&a.timeStamp&&P._onLog("Delay of decoding image: "+(this._timeEnterInnerDBR-a.timeStamp))}))}async _decodeBuffer_Blob(e,t,n,r,o,i,a){P._onLog&&P._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 P._onLog&&P._onLog("decodeBuffer(buffer,width,height,stride,format)"),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"decodeFileInMemory",id:r,instanceID:this._instanceID,body:{bytes:e}})}))}async getRuntimeSettings(){return await new Promise(((e,t)=>{let n=P._nextTaskID++;P._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)}})),P._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(!P._bUseFullFeature){if(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=P._nextTaskID++;P._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)}})),P._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=N,await new Promise(((e,t)=>{let n=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"resetRuntimeSettingsToCppDefault",id:n,instanceID:this._instanceID})}))}async outputRuntimeSettingsToString(){if(!P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"outputRuntimeSettingsToString",id:n,instanceID:this._instanceID})}))}async initRuntimeSettingsWithString(e){if(!P._bUseFullFeature)throw Error("initRuntimeSettingsWithString() is not supported in the compact version. Please try the full-featured version.");if("string"==typeof 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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"initRuntimeSettingsWithString",id:r,instanceID:this._instanceID,body:{settings:e}})}))}async _decode_Blob(e,t){P._onLog&&P._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.src=r,o.onload=()=>{URL.revokeObjectURL(o.src),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){P._onLog&&P._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}));s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r);let _=await this._decode_Canvas(s,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(_,0,0,o,i,n,r),_}async _decode_Canvas(t,n){if(P._onLog&&P._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(P._onLog&&P._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}));s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r);let _=await this._decode_Canvas(s,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return P.recalculateResultLocation(_,0,0,o,i,n,r),_}async _decode_DCEFrame(t,n){if(P._onLog&&P._onLog("_decode_DCEFrame(dceFrame)"),!P.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(P._onLog&&P._onLog("_decode_DSImage(dsImage)"),!P.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)}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),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}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&&!P._setWarnnedEx.has(t.description)&&(P._setWarnnedEx.add(t.description),console.warn(t.description)),t.textResults}if(t.exception==n.DBR_SUCCESS)return t.data;throw P.BarcodeReaderException(t.exception,t.description)}async setModeArgument(e,t,n,r){return await new Promise(((o,i)=>{let a=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._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=P._nextTaskID++;P._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)}})),P._dbrWorker.postMessage({type:"getIntermediateResults",id:n,instanceID:this._instanceID,body:{isCharge:!0}})}))}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(P._onLog&&P._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=P._nextTaskID++;P._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)}})),P._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(!P._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=P._nextTaskID++;P._taskCallbackMap.set(r,(n=>{if(n.success)return e();{let e=new Error(n.message);return e.stack+="\n"+n.stack,t(e)}})),P._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 P._onLog&&P._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));P._onLog&&P._onLog("======= once read ======="),P._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(),!P.isDSImage(t)))throw new Error("Invalid DSImage.");if(!e&&!t)return P._onLog&&P._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))}))),P.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(P._onLog&&P._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&&(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"),P._onLog&&P._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(P._onLog&&P._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 P._onLog&&P._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;const t=e=>this.dce.getDrawingLayers().some((t=>t.getId()===e));if(!t(3)&&!(null==e?void 0:e.length))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.setDisiredValue(this,"ifShowScanRegionLaser",!0),this.dce.ifShowScanRegionLaser&&this.dce.showScanRegionLaser())}}destroyContext(){if(P._onLog&&P._onLog("destroyContext()"),this.bDestroyed)return;this.bDestroyed=!0,(this.dce||this._promiseStartScan)&&this.stopScanning(),this.setImageSource(null);let e=P._nextTaskID++;P._taskCallbackMap.set(e,(e=>{if(!e.success){let t=new Error(e.message);throw t.stack=e.stack+"\n"+t.stack,t}})),P._dbrWorker.postMessage({type:"destroyContext",id:e,instanceID:this._instanceID})}}var F,x,k,V,G,U,H,W,K,Z,Y,J,X,Q,j,q,z,$,ee,te,ne,re,oe,ie,ae;P._jsVersion="9.6.42",P._jsEditVersion="20240426",P._version=`loading...(JS ${P._jsVersion}.${P._jsEditVersion})`,P._license=m,P._sessionPassword=f,P.browserInfo=s,P._workerName=`dbr-${P._jsVersion}.browser.worker.js`,P._engineResourcePath=c,P._licenseServer=[],P._deviceFriendlyName="",P._isShowRelDecodeTimeInResults=!1,P._bWasmDebug=!1,P._bNeverShowDialog=!1,P.__bUseFullFeature=!0,P._nextTaskID=0,P._taskCallbackMap=new Map,P._pLoad=new D,P._lastErrorCode=0,P._lastErrorString="",P._setWarnnedEx=new Set,P._defaultUIElementURL="@engineResourcePath/dbr.ui.html","function"==typeof SuppressedError&&SuppressedError,e.EnumBarcodeColourMode=void 0,(F=e.EnumBarcodeColourMode||(e.EnumBarcodeColourMode={}))[F.BICM_DARK_ON_LIGHT=1]="BICM_DARK_ON_LIGHT",F[F.BICM_LIGHT_ON_DARK=2]="BICM_LIGHT_ON_DARK",F[F.BICM_DARK_ON_DARK=4]="BICM_DARK_ON_DARK",F[F.BICM_LIGHT_ON_LIGHT=8]="BICM_LIGHT_ON_LIGHT",F[F.BICM_DARK_LIGHT_MIXED=16]="BICM_DARK_LIGHT_MIXED",F[F.BICM_DARK_ON_LIGHT_DARK_SURROUNDING=32]="BICM_DARK_ON_LIGHT_DARK_SURROUNDING",F[F.BICM_SKIP=0]="BICM_SKIP",F[F.BICM_REV=2147483648]="BICM_REV",e.EnumBarcodeComplementMode=void 0,(x=e.EnumBarcodeComplementMode||(e.EnumBarcodeComplementMode={}))[x.BCM_AUTO=1]="BCM_AUTO",x[x.BCM_GENERAL=2]="BCM_GENERAL",x[x.BCM_SKIP=0]="BCM_SKIP",x[x.BCM_REV=2147483648]="BCM_REV",e.EnumBarcodeFormat_2=void 0,(k=e.EnumBarcodeFormat_2||(e.EnumBarcodeFormat_2={}))[k.BF2_NULL=0]="BF2_NULL",k[k.BF2_POSTALCODE=32505856]="BF2_POSTALCODE",k[k.BF2_NONSTANDARD_BARCODE=1]="BF2_NONSTANDARD_BARCODE",k[k.BF2_USPSINTELLIGENTMAIL=1048576]="BF2_USPSINTELLIGENTMAIL",k[k.BF2_POSTNET=2097152]="BF2_POSTNET",k[k.BF2_PLANET=4194304]="BF2_PLANET",k[k.BF2_AUSTRALIANPOST=8388608]="BF2_AUSTRALIANPOST",k[k.BF2_RM4SCC=16777216]="BF2_RM4SCC",k[k.BF2_DOTCODE=2]="BF2_DOTCODE",k[k.BF2_PHARMACODE_ONE_TRACK=4]="BF2_PHARMACODE_ONE_TRACK",k[k.BF2_PHARMACODE_TWO_TRACK=8]="BF2_PHARMACODE_TWO_TRACK",k[k.BF2_PHARMACODE=12]="BF2_PHARMACODE",k[k.BF2_ALL=-1]="BF2_ALL",e.EnumBinarizationMode=void 0,(V=e.EnumBinarizationMode||(e.EnumBinarizationMode={}))[V.BM_AUTO=1]="BM_AUTO",V[V.BM_LOCAL_BLOCK=2]="BM_LOCAL_BLOCK",V[V.BM_SKIP=0]="BM_SKIP",V[V.BM_THRESHOLD=4]="BM_THRESHOLD",V[V.BM_REV=2147483648]="BM_REV",e.EnumClarityCalculationMethod=void 0,(G=e.EnumClarityCalculationMethod||(e.EnumClarityCalculationMethod={}))[G.ECCM_CONTRAST=1]="ECCM_CONTRAST",e.EnumClarityFilterMode=void 0,(U=e.EnumClarityFilterMode||(e.EnumClarityFilterMode={}))[U.CFM_GENERAL=1]="CFM_GENERAL",e.EnumColourClusteringMode=void 0,(H=e.EnumColourClusteringMode||(e.EnumColourClusteringMode={}))[H.CCM_AUTO=1]="CCM_AUTO",H[H.CCM_GENERAL_HSV=2]="CCM_GENERAL_HSV",H[H.CCM_SKIP=0]="CCM_SKIP",H[H.CCM_REV=2147483648]="CCM_REV",e.EnumColourConversionMode=void 0,(W=e.EnumColourConversionMode||(e.EnumColourConversionMode={}))[W.CICM_GENERAL=1]="CICM_GENERAL",W[W.CICM_SKIP=0]="CICM_SKIP",W[W.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,(Z=e.EnumDeblurMode||(e.EnumDeblurMode={}))[Z.DM_SKIP=0]="DM_SKIP",Z[Z.DM_DIRECT_BINARIZATION=1]="DM_DIRECT_BINARIZATION",Z[Z.DM_THRESHOLD_BINARIZATION=2]="DM_THRESHOLD_BINARIZATION",Z[Z.DM_GRAY_EQUALIZATION=4]="DM_GRAY_EQUALIZATION",Z[Z.DM_SMOOTHING=8]="DM_SMOOTHING",Z[Z.DM_MORPHING=16]="DM_MORPHING",Z[Z.DM_DEEP_ANALYSIS=32]="DM_DEEP_ANALYSIS",Z[Z.DM_SHARPENING=64]="DM_SHARPENING",Z[Z.DM_BASED_ON_LOC_BIN=128]="DM_BASED_ON_LOC_BIN",Z[Z.DM_SHARPENING_SMOOTHING=256]="DM_SHARPENING_SMOOTHING",e.EnumDeformationResistingMode=void 0,(Y=e.EnumDeformationResistingMode||(e.EnumDeformationResistingMode={}))[Y.DRM_AUTO=1]="DRM_AUTO",Y[Y.DRM_GENERAL=2]="DRM_GENERAL",Y[Y.DRM_BROAD_WARP=4]="DRM_BROAD_WARP",Y[Y.DRM_LOCAL_REFERENCE=8]="DRM_LOCAL_REFERENCE",Y[Y.DRM_DEWRINKLE=16]="DRM_DEWRINKLE",Y[Y.DRM_SKIP=0]="DRM_SKIP",Y[Y.DRM_REV=2147483648]="DRM_REV",e.EnumDPMCodeReadingMode=void 0,(J=e.EnumDPMCodeReadingMode||(e.EnumDPMCodeReadingMode={}))[J.DPMCRM_AUTO=1]="DPMCRM_AUTO",J[J.DPMCRM_GENERAL=2]="DPMCRM_GENERAL",J[J.DPMCRM_SKIP=0]="DPMCRM_SKIP",J[J.DPMCRM_REV=2147483648]="DPMCRM_REV",e.EnumGrayscaleTransformationMode=void 0,(X=e.EnumGrayscaleTransformationMode||(e.EnumGrayscaleTransformationMode={}))[X.GTM_INVERTED=1]="GTM_INVERTED",X[X.GTM_ORIGINAL=2]="GTM_ORIGINAL",X[X.GTM_SKIP=0]="GTM_SKIP",X[X.GTM_REV=2147483648]="GTM_REV",e.EnumImagePreprocessingMode=void 0,(Q=e.EnumImagePreprocessingMode||(e.EnumImagePreprocessingMode={}))[Q.IPM_AUTO=1]="IPM_AUTO",Q[Q.IPM_GENERAL=2]="IPM_GENERAL",Q[Q.IPM_GRAY_EQUALIZE=4]="IPM_GRAY_EQUALIZE",Q[Q.IPM_GRAY_SMOOTH=8]="IPM_GRAY_SMOOTH",Q[Q.IPM_SHARPEN_SMOOTH=16]="IPM_SHARPEN_SMOOTH",Q[Q.IPM_MORPHOLOGY=32]="IPM_MORPHOLOGY",Q[Q.IPM_SKIP=0]="IPM_SKIP",Q[Q.IPM_REV=2147483648]="IPM_REV",e.EnumIntermediateResultSavingMode=void 0,(j=e.EnumIntermediateResultSavingMode||(e.EnumIntermediateResultSavingMode={}))[j.IRSM_MEMORY=1]="IRSM_MEMORY",j[j.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",j[j.IRSM_BOTH=4]="IRSM_BOTH",e.EnumLocalizationMode=void 0,(q=e.EnumLocalizationMode||(e.EnumLocalizationMode={}))[q.LM_SKIP=0]="LM_SKIP",q[q.LM_AUTO=1]="LM_AUTO",q[q.LM_CONNECTED_BLOCKS=2]="LM_CONNECTED_BLOCKS",q[q.LM_LINES=8]="LM_LINES",q[q.LM_STATISTICS=4]="LM_STATISTICS",q[q.LM_SCAN_DIRECTLY=16]="LM_SCAN_DIRECTLY",q[q.LM_STATISTICS_MARKS=32]="LM_STATISTICS_MARKS",q[q.LM_STATISTICS_POSTAL_CODE=64]="LM_STATISTICS_POSTAL_CODE",q[q.LM_CENTRE=128]="LM_CENTRE",q[q.LM_ONED_FAST_SCAN=256]="LM_ONED_FAST_SCAN",q[q.LM_REV=2147483648]="LM_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=P})); diff --git a/dist/dbr.pure.mjs b/dist/dbr.pure.mjs index 59620ea..bc121b7 100644 --- a/dist/dbr.pure.mjs +++ b/dist/dbr.pure.mjs @@ -2,10 +2,10 @@ * Dynamsoft JavaScript Library * @product Dynamsoft Barcode Reader JS Edition * @website http://www.dynamsoft.com - * @copyright Copyright 2023, Dynamsoft Corporation + * @copyright Copyright 2024, Dynamsoft Corporation * @author Dynamsoft - * @version 9.6.32 (js 20231027) + * @version 9.6.42 (js 20240426) * @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 f=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 m=s._node;if(r._webAudio){var A=function(){r._playLock=!1,f(),r._refreshBuffer(s);var e=s._muted||r._muted?0:s._volume;m.gain.setValueAtTime(e,t.ctx.currentTime),s._playStart=t.ctx.currentTime,void 0===m.bufferSource.start?s._loop?m.bufferSource.noteGrainOn(0,d,86400):m.bufferSource.noteGrainOn(0,d,c):s._loop?m.bufferSource.start(0,d,86400):m.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?A():(r._playLock=!0,r.once("resume",A),r._clearTimer(s._id))}else{var p=function(){m.currentTime=d,m.muted=s._muted||r._muted||t._muted||m.muted,m.volume=s._volume*t.volume(),m.playbackRate=s._rate;try{var o=m.play();if(o&&"undefined"!=typeof Promise&&(o instanceof Promise||"function"==typeof o.then)?(r._playLock=!0,f(),o.then((function(){r._playLock=!1,m._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,f(),r._emit("play",s._id)),m.playbackRate=s._rate,m.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),m.removeEventListener("ended",r._endTimers[s._id],!1)},m.addEventListener("ended",r._endTimers[s._id],!1))}catch(e){r._emit("playerror",s._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===m.src&&(m.src=r._src,m.load());var g=window&&window.ejecta||!m.readyState&&t._navigator.isCocoonJS;if(m.readyState>=3||g)p();else{r._playLock=!0,r._state="loading";var I=function(){r._state="loaded",p(),m.removeEventListener(t._canPlayEvent,I,!1)};m.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(I)try{(await m.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===A.browser&&A.version>66||"Safari"===A.browser&&A.version>13||"OPR"===A.browser&&A.version>43||"Edge"===A.browser&&A.version;const E=(()=>{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"./"})(),T=" is not allowed to change after `createInstance` or `loadWasm` is called.",D=!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"))||"",S=!c&&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 N 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(A.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.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,this.beepSound=new n({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}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})(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`"+T);n._sessionPassword=t})(B,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:p,worker:g,getUserMedia:I,camera:await R(),browser:A.browser,version:A.version,OS:A.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`"+T);n._licenseServer=C(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`"+T);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=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&&(u.crypto||(n="Please upgrade your browser to support online key."),u.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)})(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:A,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(){const 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&~(O.BF_ONED|O.BF_QR_CODE|O.BF_PDF417|O.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=b,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=b,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}));s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r),e.dbrObjUrl&&URL.revokeObjectURL(e.dbrObjUrl);let _=await this._decode_Canvas(s,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return B.recalculateResultLocation(_,0,0,o,i,n,r),_}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,y.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}));s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r);let _=await this._decode_Canvas(s,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return B.recalculateResultLocation(_,0,0,o,i,n,r),_}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,y.IPF_GrayScaled,0,c);else if("rgba"===a)n=await this._decodeBuffer_Uint8Array(d,r,o,s,y.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,y.IPF_ARGB_8888,0,c)}else if("grey"===i)n=await this._decodeBuffer_Uint8Array(d,r,o,r,y.IPF_GrayScaled,0,c);else if("rgba"===i)n=await this._decodeBuffer_Uint8Array(d,r,o,4*r,y.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,y.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),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}static BarcodeReaderException(e,t){let n,r=v.DBR_UNKNOWN;return"number"==typeof e?(r=e,n=new Error(t)):n=new Error(e),n.code=r,n}_handleRetJsonString(e){let t=v;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,body:{isCharge:!0}})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let n of e)if(n.dataType==L.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 y.IPF_ABGR_8888:r=new Uint8ClampedArray(n);break;case y.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&&(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.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 P,F,x,V,k,G,U,H,W,K,Z,Y,J,X,Q,j,q,$,z,ee,te,ne,re,oe,ie,ae;B._jsVersion="9.6.32",B._jsEditVersion="20231027",B._version=`loading...(JS ${B._jsVersion}.${B._jsEditVersion})`,B._license=D,B._sessionPassword=S,B.browserInfo=A,B._workerName=`dbr-${B._jsVersion}.browser.worker.js`,B._engineResourcePath=E,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 N,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"}(P||(P={})),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"}(F||(F={})),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=-1]="BF2_ALL"}(x||(x={})),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"}(k||(k={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(G||(G={})),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"}(H||(H={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(W||(W={})),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"}(Z||(Z={})),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"}(Y||(Y={})),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"}(J||(J={})),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"}(X||(X={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(Q||(Q={})),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"}(j||(j={})),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"}(q||(q={})),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"}($||($={})),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"}(z||(z={})),function(e){e[e.RCT_PIXEL=1]="RCT_PIXEL",e[e.RCT_PERCENTAGE=2]="RCT_PERCENTAGE"}(ee||(ee={})),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"}(te||(te={})),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"}(ne||(ne={})),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"}(re||(re={})),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"}(oe||(oe={})),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"}(ie||(ie={})),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"}(ae||(ae={}));export{B as BarcodeReader,P as EnumBarcodeColourMode,F as EnumBarcodeComplementMode,O as EnumBarcodeFormat,x as EnumBarcodeFormat_2,V as EnumBinarizationMode,k as EnumClarityCalculationMethod,G as EnumClarityFilterMode,U as EnumColourClusteringMode,H as EnumColourConversionMode,W as EnumConflictMode,Y as EnumDPMCodeReadingMode,K as EnumDeblurMode,Z as EnumDeformationResistingMode,v as EnumErrorCode,J as EnumGrayscaleTransformationMode,L as EnumIMResultDataType,y as EnumImagePixelFormat,X as EnumImagePreprocessingMode,Q as EnumIntermediateResultSavingMode,M as EnumIntermediateResultType,j as EnumLocalizationMode,q as EnumPDFReadingMode,$ as EnumQRCodeErrorCorrectionLevel,z as EnumRegionPredetectionMode,ee as EnumResultCoordinateType,te as EnumResultType,ne as EnumScaleUpMode,re as EnumTerminatePhase,oe as EnumTextFilterMode,ie as EnumTextResultOrderMode,ae as EnumTextureDetectionMode}; +import"dynamsoft-camera-enhancer";const e="undefined"==typeof self,t=e?{}:self;let n,r,o,i,a;"undefined"!=typeof navigator&&(n=navigator,r=n.userAgent,o=n.platform,i=n.mediaDevices),function(){if(!e){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:n.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:o,search:"Win"},Mac:{str:o},Linux:{str:o}};let i="unknownBrowser",s=0,_="unknownOS";for(let t in e){const n=e[t]||{};let o=n.str||r,a=n.search||t,_=n.verStr||r,d=n.verSearch||t;if(d instanceof Array||(d=[d]),-1!=o.indexOf(a)){i=t;for(let e of d){let t=_.indexOf(e);if(-1!=t){s=parseFloat(_.substring(t+e.length+1));break}}break}}for(let e in t){const n=t[e]||{};let o=n.str||r,i=n.search||e;if(-1!=o.indexOf(i)){_=e;break}}"Linux"==_&&-1!=r.indexOf("Windows NT")&&(_="HarmonyOS"),a={browser:i,version:s,OS:_}}e&&(a={browser:"ssr",version:0,OS:"ssr"})}();const s="undefined"!=typeof WebAssembly&&r&&!(/Safari/.test(r)&&!/Chrome/.test(r)&&/\(.+\s11_2_([2-6]).*\)/.test(r)),_=!("undefined"==typeof Worker),d=!(!i||!i.getUserMedia),c=async()=>{let e=!1;if(d)try{(await i.getUserMedia({video:!0})).getTracks().forEach((e=>{e.stop()})),e=!0}catch(e){}return e};"Chrome"===a.browser&&a.version>66||"Safari"===a.browser&&a.version>13||"OPR"===a.browser&&a.version>43||"Edge"===a.browser&&a.version;const u=(()=>{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"./"})(),l=" is not allowed to change after `createInstance` or `loadWasm` is called.",h=!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")||"",m=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let n=0;ne&&"object"==typeof e&&"function"==typeof e.then;class T extends Promise{constructor(e){let t,n;super(((e,r)=>{t=e,n=r})),this._s="pending",this.resolve=e=>{this.isPending&&(E(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,E(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}}var D=function(){this.init()};D.prototype={init:function(){var e=this||S;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||S;if(e=parseFloat(e),t.ctx||N(),void 0!==e&&e>=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,S.ctx.currentTime);for(var n=0;n=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,N()),e},codecs:function(e){return(this||S)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||S;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||S,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!t||"function"!=typeof t.canPlayType)return e;var n=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",o=r.match(/OPR\/([0-6].)/g),i=o&&parseInt(o[0].split("/")[1],10)<33,a=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),s=r.match(/Version\/(.*?) /),_=a&&s&&parseInt(s[1],10)<15;return e._codecs={mp3:!(i||!n&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!n,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:!(_||!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(_||!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||S;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?a._seek:n._sprite[e][0]/1e3),d=Math.max(0,(n._sprite[e][0]+n._sprite[e][1])/1e3-_),c=1e3*d/Math.abs(a._rate),u=n._sprite[e][0]/1e3,l=(n._sprite[e][0]+n._sprite[e][1])/1e3;a._sprite=e,a._ended=!1;var h=function(){a._paused=!1,a._seek=_,a._start=u,a._stop=l,a._loop=!(!a._loop&&!n._sprite[e][2])};if(!(_>=l)){var f=a._node;if(n._webAudio){var m=function(){n._playLock=!1,h(),n._refreshBuffer(a);var e=a._muted||n._muted?0:a._volume;f.gain.setValueAtTime(e,S.ctx.currentTime),a._playStart=S.ctx.currentTime,void 0===f.bufferSource.start?a._loop?f.bufferSource.noteGrainOn(0,_,86400):f.bufferSource.noteGrainOn(0,_,d):a._loop?f.bufferSource.start(0,_,86400):f.bufferSource.start(0,_,d),c!==1/0&&(n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),c)),t||setTimeout((function(){n._emit("play",a._id),n._loadQueue()}),0)};"running"===S.state&&"interrupted"!==S.ctx.state?m():(n._playLock=!0,n.once("resume",m),n._clearTimer(a._id))}else{var A=function(){f.currentTime=_,f.muted=a._muted||n._muted||S._muted||f.muted,f.volume=a._volume*S.volume(),f.playbackRate=a._rate;try{var r=f.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(n._playLock=!0,h(),r.then((function(){n._playLock=!1,f._unlocked=!0,t?n._loadQueue():n._emit("play",a._id)})).catch((function(){n._playLock=!1,n._emit("playerror",a._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."),a._ended=!0,a._paused=!0}))):t||(n._playLock=!1,h(),n._emit("play",a._id)),f.playbackRate=a._rate,f.paused)return void n._emit("playerror",a._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||a._loop?n._endTimers[a._id]=setTimeout(n._ended.bind(n,a),c):(n._endTimers[a._id]=function(){n._ended(a),f.removeEventListener("ended",n._endTimers[a._id],!1)},f.addEventListener("ended",n._endTimers[a._id],!1))}catch(e){n._emit("playerror",a._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===f.src&&(f.src=n._src,f.load());var p=window&&window.ejecta||!f.readyState&&S._navigator.isCocoonJS;if(f.readyState>=3||p)A();else{n._playLock=!0,n._state="loading";var g=function(){n._state="loaded",A(),f.removeEventListener(S._canPlayEvent,g,!1)};f.addEventListener(S._canPlayEvent,g,!1),n._clearTimer(a._id)}}return a._id}n._ended(a)},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(o[0],10):e=parseFloat(o[0]):o.length>=2&&(e=parseFloat(o[0]),t=parseInt(o[1],10)),!(void 0!==e&&e>=0&&e<=1))return(n=t?r._soundById(t):r._sounds[0])?n._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,o)}}),r;void 0===t&&(r._volume=e),t=r._getSoundIds(t);for(var i=0;i0?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 t=this,n=t._soundById(e);return n&&n._interval&&(t._webAudio&&n._node.gain.cancelScheduledValues(S.ctx.currentTime),clearInterval(n._interval),n._interval=null,t.volume(n._fadeTo,e),n._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(o[0],10):e=parseFloat(o[0])}else 2===o.length&&(e=parseFloat(o[0]),t=parseInt(o[1],10));if("number"!=typeof e)return(n=r._soundById(t))?n._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,o)}}),r;void 0===t&&(r._rate=e),t=r._getSoundIds(t);for(var i=0;i=0?t=parseInt(r[0],10):n._sounds.length&&(t=n._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"!==n._state||n._playLock))return n._queue.push({event:"seek",action:function(){n.seek.apply(n,r)}}),n;var o=n._soundById(t);if(o){if(!("number"==typeof e&&e>=0)){if(n._webAudio){var i=n.playing(t)?S.ctx.currentTime-o._playStart:0,a=o._rateSeek?o._rateSeek-o._seek:0;return o._seek+(a+i*Math.abs(o._rate))}return o._node.currentTime}var s=n.playing(t);s&&n.pause(t,!0),o._seek=e,o._ended=!1,n._clearTimer(t),n._webAudio||!o._node||isNaN(o._node.duration)||(o._node.currentTime=e);var _=function(){s&&n.play(t,!0),n._emit("seek",t)};if(s&&!n._webAudio){var d=function(){n._playLock?setTimeout(d,0):_()};setTimeout(d,0)}else _()}return n},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&&S._howls.splice(r,1);var o=!0;for(n=0;n=0){o=!1;break}return L&&o&&delete L[e._src],S.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,n=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(S._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),t))try{e.bufferSource.buffer=S._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(S._navigator&&S._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var y=function(e){this._parent=e,this.init()};y.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=++S._counter,t._sounds.push(e),e.create(),e},create:function(){var e=this,t=e._parent,n=S._muted||e._muted||e._parent._muted?0:e._volume;return t._webAudio?(e._node=void 0===S.ctx.createGain?S.ctx.createGainNode():S.ctx.createGain(),e._node.gain.setValueAtTime(n,S.ctx.currentTime),e._node.paused=!0,e._node.connect(S.masterGain)):S.noAudio||(e._node=S._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(S._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=n*S.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=++S._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(S._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 L={},v=function(e){var t=e._src;if(L[t])return e._duration=L[t].duration,void w(e);if(/^data:[^;]+;base64,/.test(t)){for(var n=atob(t.split(",")[1]),r=new Uint8Array(n.length),o=0;o0?(L[t._src]=e,w(t,e)):n()};"undefined"!=typeof Promise&&1===S.ctx.decodeAudioData.length?S.ctx.decodeAudioData(e).then(r).catch(n):S.ctx.decodeAudioData(e,r,n)},w=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())},N=function(){if(S.usingWebAudio){try{"undefined"!=typeof AudioContext?S.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?S.ctx=new webkitAudioContext:S.usingWebAudio=!1}catch(e){S.usingWebAudio=!1}S.ctx||(S.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(S._navigator&&S._navigator.platform),t=S._navigator&&S._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),n=t?parseInt(t[1],10):null;if(e&&n&&n<9){var r=/safari/.test(S._navigator&&S._navigator.userAgent.toLowerCase());S._navigator&&!r&&(S.usingWebAudio=!1)}S.usingWebAudio&&(S.masterGain=void 0===S.ctx.createGain?S.ctx.createGainNode():S.ctx.createGain(),S.masterGain.gain.setValueAtTime(S._muted?0:S._volume,S.ctx.currentTime),S.masterGain.connect(S.ctx.destination)),S._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{const n=e;if(!n._pLoad.isEmpty)throw new Error("`license`"+l);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`"+l);n._sessionPassword=t})(B,e)}static get sessionPassword(){return this._sessionPassword}static async detectEnvironment(){return await(async()=>({wasm:s,worker:_,getUserMedia:d,camera:await c(),browser:a.browser,version:a.version,OS:a.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.");B._engineResourcePath=(t=>{if(null==t&&(t="./"),e);else{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 n=e;if(!n._pLoad.isEmpty)throw new Error("`licenseServer`"+l);n._licenseServer=m(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`"+l);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 C({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:n,ls:r,sp:o,rmk:i}=((e,n=!1)=>{const r=e;if(r._pLoad.isEmpty){let e,o,i,a=r._license||"",s=JSON.parse(JSON.stringify(r._licenseServer)),_=r._sessionPassword,d=0;if(a.startsWith("t")||a.startsWith("f"))d=0;else if(0===a.length||a.startsWith("P")||a.startsWith("L")||a.startsWith("Y")||a.startsWith("A"))d=1;else{d=2;const t=a.indexOf(":");-1!=t&&(a=a.substring(t+1));const n=a.indexOf("?");if(-1!=n&&(o=a.substring(n+1),a=a.substring(0,n)),a.startsWith("DLC2"))d=0;else{if(a.startsWith("DLS2")){let t;try{let e=a.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(a=t.handshakeCode?t.handshakeCode:t.organizationID?t.organizationID:"","number"==typeof a&&(a=JSON.stringify(a)),0===s.length){let e=[];t.mainServerURL&&(e[0]=t.mainServerURL),t.standbyServerURL&&(e[1]=t.standbyServerURL),s=m(e)}!_&&t.sessionPassword&&(_=t.sessionPassword),e=t.remark}a&&"200001"!==a&&!a.startsWith("200001-")||(d=1)}}if(d&&(n||(t.crypto||(i="Please upgrade your browser to support online key."),t.crypto.subtle||(i="Require https to use online key in this browser."))),i){if(1!==d)throw new Error(i);d=0,console.warn(i),r._lastErrorCode=-1,r._lastErrorString=i}return 1===d&&(a="",console.warn("Applying for a public trial license ...")),{lt:d,l:a,ls:s,sp:_,rmk:e,cv:o}}throw new Error("Can't preprocess license again"+l)})(B);this._pLoad.task=async(t,s)=>{let _=B.engineResourcePath+B._workerName;B.engineResourcePath.startsWith(location.origin)||(_=await fetch(_).then((e=>e.blob())).then((e=>URL.createObjectURL(e)))),B._dbrWorker=new Worker(_),URL.revokeObjectURL(_),B._dbrWorker.onerror=e=>{let t=new Error(e.message);s(t)},B._dbrWorker.onmessage=async n=>{let r=n.data?n.data:n;switch(r.type){case"log":B._onLog&&B._onLog(r.message);break;case"load":{r.message&&(r.message=r.message.replace("(https://www.dynamsoft.com/purchase-center/)","(https://www.dynamsoft.com/store/dynamsoft-barcode-reader/#javascript)"));let n,o=!1;1===e&&(o=!0,r.message||(r.message="Using a temporary license. [Register for a 30-day trial license >>>](https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&deploymenttype=browser)")),r.success?(B._dbrWorker.onerror=null,B._version=r.version+"(JS "+B._jsVersion+"."+B._jsEditVersion+")",B._onLog&&B._onLog("load dbr worker success"),r.message&&console.warn(r.message)):(n=new Error(r.message),n.stack=r.stack+"\n"+n.stack,n.ltsErrorCode=r.ltsErrorCode,o||111==r.ltsErrorCode&&-1!=r.message.toLowerCase().indexOf("trial license")&&(o=!0)),o&&B.showDialog(r.success?"warn":"error",r.message),r.success?t():s(n);break}case"task":{let e=r.id,t=r.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(n)}},B._dbrWorker.postMessage({type:"loadWasm",engineResourcePath:B.engineResourcePath,bUseFullFeature:B._bUseFullFeature,bd:B._bWasmDebug,v:B._jsVersion,brtk:!!e,bptk:1===e,l:n,dm:location.origin.startsWith("http")?location.origin:"https://localhost",os:a,cv:B.authCacheVersion,fn:B.deviceFriendlyName,ls:r,sp:o,rmk:i})}}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})}))}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.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,this.beepSound=new C({src:[this._soundSource],onplayerror:(e,t)=>{console.warn(`Sound '${e}' playback failure: ${t}`)}})}static async createInstance(){const 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(t.barcodeFormatIds&~(I.BF_ONED|I.BF_QR_CODE|I.BF_PDF417|I.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|=R.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=b,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=b,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);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.src=r,o.onload=()=>{URL.revokeObjectURL(o.src),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}));s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r);let _=await this._decode_Canvas(s,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.width,t.height=e.height;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return B.recalculateResultLocation(_,0,0,o,i,n,r),_}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,A.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}));s.ctx2d.drawImage(e,0,0,o,i,0,0,n,r);let _=await this._decode_Canvas(s,t);if(this.ifSaveOriginalImageInACanvas){const t=document.createElement("canvas");t.width=e.videoWidth,t.height=e.videoHeight;t.getContext("2d").drawImage(e,0,0),this.oriCanvas=t,this.oriCanvasData=null}return B.recalculateResultLocation(_,0,0,o,i,n,r),_}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,A.IPF_GrayScaled,0,c);else if("rgba"===a)n=await this._decodeBuffer_Uint8Array(d,r,o,s,A.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,A.IPF_ARGB_8888,0,c)}else if("grey"===i)n=await this._decodeBuffer_Uint8Array(d,r,o,r,A.IPF_GrayScaled,0,c);else if("rgba"===i)n=await this._decodeBuffer_Uint8Array(d,r,o,4*r,A.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,A.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)}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),e.x1=Math.round(e.x1),e.x2=Math.round(e.x2),e.x3=Math.round(e.x3),e.x4=Math.round(e.x4),e.y1=Math.round(e.y1),e.y2=Math.round(e.y2),e.y3=Math.round(e.y3),e.y4=Math.round(e.y4)}}static BarcodeReaderException(e,t){let n,r=p.DBR_UNKNOWN;return"number"==typeof e?(r=e,n=new Error(t)):n=new Error(e),n.code=r,n}_handleRetJsonString(e){let t=p;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,body:{isCharge:!0}})}))}async getIntermediateCanvas(){let e=await this.getIntermediateResults(),t=[];for(let n of e)if(n.dataType==g.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 A.IPF_ABGR_8888:r=new Uint8ClampedArray(n);break;case A.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|=R.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&&(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;const t=e=>this.dce.getDrawingLayers().some((t=>t.getId()===e));if(!t(3)&&!(null==e?void 0:e.length))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.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 P,F,x,k,V,G,U,H,W,K,Z,Y,J,X,Q,j,q,$,z,ee,te,ne,re,oe,ie;B._jsVersion="9.6.42",B._jsEditVersion="20240426",B._version=`loading...(JS ${B._jsVersion}.${B._jsEditVersion})`,B._license=h,B._sessionPassword=f,B.browserInfo=a,B._workerName=`dbr-${B._jsVersion}.browser.worker.js`,B._engineResourcePath=u,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 T,B._lastErrorCode=0,B._lastErrorString="",B._setWarnnedEx=new Set,B._defaultUIElementURL="@engineResourcePath/dbr.ui.html","function"==typeof SuppressedError&&SuppressedError,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"}(P||(P={})),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"}(F||(F={})),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=-1]="BF2_ALL"}(x||(x={})),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"}(k||(k={})),function(e){e[e.ECCM_CONTRAST=1]="ECCM_CONTRAST"}(V||(V={})),function(e){e[e.CFM_GENERAL=1]="CFM_GENERAL"}(G||(G={})),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"}(H||(H={})),function(e){e[e.CM_IGNORE=1]="CM_IGNORE",e[e.CM_OVERWRITE=2]="CM_OVERWRITE"}(W||(W={})),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"}(Z||(Z={})),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"}(Y||(Y={})),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"}(J||(J={})),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"}(X||(X={})),function(e){e[e.IRSM_MEMORY=1]="IRSM_MEMORY",e[e.IRSM_FILESYSTEM=2]="IRSM_FILESYSTEM",e[e.IRSM_BOTH=4]="IRSM_BOTH"}(Q||(Q={})),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"}(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,P as EnumBarcodeColourMode,F as EnumBarcodeComplementMode,I as EnumBarcodeFormat,x as EnumBarcodeFormat_2,k as EnumBinarizationMode,V as EnumClarityCalculationMethod,G as EnumClarityFilterMode,U as EnumColourClusteringMode,H as EnumColourConversionMode,W as EnumConflictMode,Y as EnumDPMCodeReadingMode,K as EnumDeblurMode,Z as EnumDeformationResistingMode,p as EnumErrorCode,J as EnumGrayscaleTransformationMode,g as EnumIMResultDataType,A as EnumImagePixelFormat,X as EnumImagePreprocessingMode,Q as EnumIntermediateResultSavingMode,R as EnumIntermediateResultType,j as EnumLocalizationMode,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 deleted file mode 100644 index 1237547..0000000 --- a/dist/types/class/barcodereader.d.ts +++ /dev/null @@ -1,928 +0,0 @@ -/// -import { TextResult } from "../interface/textresult"; -import { RuntimeSettings } from "../interface/runtimesettings"; -import { EnumImagePixelFormat } from "../enum/enumimagepixelformat"; -import { BarcodeReaderException } from "../interface/barcodereaderexception"; -import { Region } from "../interface/region"; -import { CameraEnhancer, DCEFrame } from 'dynamsoft-camera-enhancer'; -import { Howl } from 'dm-howler'; -import { ImageSource } from '../interface/imagesource'; -import { DSImage } from '../interface/dsimage'; -import { ScanSettings } from '../interface/scanSettings'; -import { ScannerPlayCallbackInfo } from '../interface/scannerplaycallbackinfo'; -import { Warning } from '../interface/warning'; -/** - * The `BarcodeReader` class is used for image decoding - * Comparing to `BarcodeScanner`, the default decoding settings are more accurate but slower. - * @example - * ```js - * (async()=>{ - * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - * let results = await reader.decode(imageSource); - * for(let result of results){ - * console.log(result.barcodeText); - * } - * })(); - * ``` - */ -export default class BarcodeReader { - private static _jsVersion; - private static _jsEditVersion; - protected static _version: string; - /** - * Returns the version of the library including the detailed version numbers of the engine and the main JavaScript code. - * - * The engine version is only valid after {@link loadWasm} has been called. - * @readonly - */ - static get version(): string; - protected static _license: string; - /** - * Specify an online license or an offline license. Dynamsoft usually provides an online license. - * - * `license` needs to be set before {@link createInstance} or {@link loadWasm}. - * - * Besides, it is also recommended to set license in `data-license` attribute of `script` tag, instead of in `Javascript` code. - * @example - * ```html - * - * ``` - * or - * ```js - * Dynamsoft.DBR.BarcodeReader.license = "YOUR-LICENSE-KEY"; - * ``` - */ - static get license(): string; - static set license(license: string); - /** @ignore */ - static get productKeys(): string; - /** @ignore */ - static set productKeys(keys: string); - /** @ignore */ - static get handshakeCode(): string; - /** @ignore */ - static set handshakeCode(keys: string); - /** @ignore */ - static get organizationID(): string; - /** @ignore */ - static set organizationID(keys: string); - protected static _sessionPassword: string; - /** @ignore */ - static set sessionPassword(value: string); - static get sessionPassword(): string; - /** - * @ignore - */ - static browserInfo: { - browser: string; - version: number; - OS: string; - }; - /** - * Detects the current running environment and returns a report. - * @returns A promise resolving to an object which contains some information of the current running environment. - * @example - * ```js - * console.log(await Dynamsoft.DBR.BarcodeReader.detectEnvironment()); - * // {"wasm":true, "worker":true, "getUserMedia":true, "camera":true, "browser":"Chrome", "version":90, "OS":"Windows"} - * ``` - */ - static detectEnvironment(): Promise; - /** @ignore */ - static _workerName: string; - protected static _engineResourcePath?: string; - static get engineResourcePath(): string; - /** - * Specify the Barcode Reader SDK engine (WASM) url. The SDK tries to automatically explore the engine location. - * If the auto-explored engine location is incorrect, you can manually specify the engine location. - * The property needs to be set before [[loadWasm]]. - * ```js - * Dynamsoft.DBR.BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode/dist/"; - * await Dynamsoft.DBR.BarcodeReader.loadWasm(); - * ``` - */ - static set engineResourcePath(value: string); - /** @ignore */ - protected static _licenseServer?: string[]; - static get licenseServer(): string[] | string; - /** - * Specify the license server URL. - */ - static set licenseServer(value: string[] | string); - private static _deviceFriendlyName; - /** - * Sets a human-readable name that identifies the device. - * This name will appear in the device details table when you check the statistics of the according license. - * @defaultValue `""` - */ - static get deviceFriendlyName(): string; - /** @ignore */ - static set deviceFriendlyName(value: string); - static authCacheVersion: string; - /** @ignore */ - static _isShowRelDecodeTimeInResults: boolean; - /** @ignore */ - static _onLog: any; - /** @ignore */ - static _bWasmDebug: boolean; - /** @ignore */ - static _bNeverShowDialog: boolean; - /** - * Whether to use full feature wasm. The api may change in later version. - * For web, `_bUseFullFeature` is false as default. - * For Node.js, `_bUseFullFeature` will not work, and BarcodeReader will always work on full feature. - * The property needs to be set before `loadWasm`. - *
-     * Compact wasm:
-     * oned + qr + pdf417 + datamatrix.
-     * ===
-     * Full wasm:
-     * all supported barcode format +
-     * high level deblur available (lv8, 9) +
-     * DPM +
-     * template API +
-     * intermediate results API
-     * ===
-     * e.g.:
-     * Use compact in video deocode (small, download and initialization fast).
-     * Use full in file decode (need high level deblur).
-     * 
- * - * ```js - * DBR.BarcodeReader._bUseFullFeature = true; - * await DBR.BarcodeReader.loadWasm(); - * ``` - */ - protected static __bUseFullFeature: boolean; - static get _bUseFullFeature(): boolean; - static set _bUseFullFeature(value: boolean); - /** @ignore */ - static _dbrWorker: Worker; - protected static _nextTaskID: number; - protected static _taskCallbackMap: Map void>; - private static _pLoad; - /** @ignore */ - static isImageSource(value: any): boolean; - /** @ignore */ - static isDSImage(value: any): boolean; - /** @ignore */ - static isDCEFrame(value: any): boolean; - /** @ignore */ - _instanceID: number; - protected _ifSaveOriginalImageInACanvas: boolean; - /** - * Whether to save the original image into a `HTMLCanvasElement` element. The original image refers to the actual image the library tried to read barcodes from. It can be returned by {@link getOriginalImageInACanvas}. - * @defaultValue `false` - * @example - * ```js - * reader.ifSaveOriginalImageInACanvas = true; - * let results = await reader.decode(source); - * document.body.append(reader.getOriginalImageInACanvas()); - * ``` - * @see {@link getOriginalImageInACanvas} - */ - get ifSaveOriginalImageInACanvas(): boolean; - set ifSaveOriginalImageInACanvas(value: boolean); - /** @ignore */ - protected oriCanvas?: HTMLCanvasElement; - /** @ignore */ - protected oriCanvasData?: any; - /** - * An `HTMLCanvasElement` that holds the original image. - * The original image refers to the actual image the library tried to read barcodes from. - * ```js - * reader.ifSaveOriginalImageInACanvas = true; - * let results = await reader.decode(source); - * document.body.append(reader.getOriginalImageInACanvas()); - * ``` - * @see {@link ifSaveOriginalImageInACanvas} - */ - getOriginalImageInACanvas(): any; - /** @ignore */ - private canvas; - protected bFilterRegionInJs: boolean; - protected userDefinedRegion: any; - protected _region?: Region | Region[]; - protected set region(value: null | Region | Region[]); - protected get region(): null | Region | Region[]; - /** @ignore */ - _timeStartDecode: any; - /** @ignore */ - _timeEnterInnerDBR: any; - /** @ignore */ - _timeGetMessage: any; - /** @ignore */ - decodeRecords: any; - /** - * @ignore A callback when wasm download success in browser environment. - */ - static _onWasmDownloaded: () => void; - /** - * Check if the decoding module is loaded. - * @category Initialize and Destroy - */ - static isWasmLoaded(): boolean; - protected bDestroyed: boolean; - /** - * Returns whether the instance has been destroyed. - * @see {@link destroyContext} - */ - isContextDestroyed(): boolean; - /** @ignore */ - protected static _lastErrorCode: number; - /** @ignore */ - static get lastErrorCode(): number; - /** @ignore */ - protected static _lastErrorString: string; - /** @ignore */ - static get lastErrorString(): string; - /** @ignore */ - protected static _setWarnnedEx: Set; - /** @ignore */ - protected _lastErrorCode: number; - /** @ignore */ - get lastErrorCode(): number; - /** @ignore */ - protected _lastErrorString: string; - /** @ignore */ - get lastErrorString(): string; - /** @ignore */ - _lastInnerDecodeDuration: number; - private static _defaultUIElementURL; - /** - * Returns or sets the URL of the *.html* file that defines the default UI Element. - * The URL can only be set before the {@link createInstance} is called. - */ - static get defaultUIElementURL(): string; - static set defaultUIElementURL(value: string); - /** - * A callback which is triggered when the running environment is not ideal. In this version, it may get triggered in two scenarios: - * - * 1. If the page is opened from the disk - * 2. The page is hosted in a HTTP site without SSL - * - * In both cases, the following warning is returned: - * ```js - * { - * id: 2, - * message: "Not connected via SSL (HTTPS), the SDK may not work correctly." - * } - * ``` - * @defaultValue `undefined` - * @see {@link Warning} - */ - static onWarning: (warning: Warning) => void; - protected static _fireHTTPSWarnning(): void; - /** @ignore */ - intervalTime: number; - /** @ignore */ - protected _intervalGetVideoFrame: number; - protected _loopReadVideoTimeoutId: any; - /** @ignore */ - protected array_getFrameTimeCost: any[]; - /** @ignore */ - protected array_decodeFrameTimeCost: any[]; - /** @ignore */ - protected _indexCurrentDecodingFrame: number; - protected _dbrDrawingLayer: any; - protected _arrPolygons: any; - protected _bPauseScan: boolean; - protected _intervalDetectVideoPause: number; - /** @ignore */ - beepSound: Howl; - private _soundSource; - private get soundSource(); - private set soundSource(value); - /** - * Whether to play sound when the scanner reads a barcode successfully. - * Default value is `false`, which does not play sound. - * Use `frame` or `true` to play a sound when any barcode is found within a frame. - * Use `unique` to play a sound only when any unique/unduplicated barcode is found within a frame. - * ```js - * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies - * startPlayButton.addEventListener('click', function() { - * scanner.bPlaySoundOnSuccessfulRead = true; - * }); - * ``` - * refer: `favicon bug` https://bugs.chromium.org/p/chromium/issues/detail?id=1069731&q=favicon&can=2 - * @ignore - */ - protected bPlaySoundOnSuccessfulRead: (boolean | string); - private get whenToPlaySoundforSuccessfulRead(); - /** - * Whether to play sound when the scanner reads a barcode successfully. - * Default value is `never`, which does not play sound. - * Use `frame` to play a sound when any barcode is found within a frame. - * Use `unique` to play a sound only when any unique/unduplicated barcode is found within a frame. - * ```js - * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies - * startPlayButton.addEventListener('click', function() { - * scanner.whenToPlaySoundforSuccessfulRead = 'frame'; - * }); - * ``` - * refer: `favicon bug` https://bugs.chromium.org/p/chromium/issues/detail?id=1069731&q=favicon&can=2 - * @ignore - */ - private set whenToPlaySoundforSuccessfulRead(value); - /** - * Whether to vibrate when the scanner reads a barcode successfully. - * Default value is `false`, which does not vibrate. - * Use `frame` or `true` to vibrate when any barcode is found within a frame. - * Use `unique` to vibrate only when any unique/unduplicated barcode is found within a frame. - * ```js - * // Can I use? https://caniuse.com/?search=vibrate - * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies - * startVibrateButton.addEventListener('click', function() { - * scanner.bVibrateOnSuccessfulRead = true; - * }); - * ``` - * @ignore - */ - protected bVibrateOnSuccessfulRead: (boolean | string); - /** - * Get or set how long (ms) the vibration lasts. - * @see [[whenToVibrateforSuccessfulRead]] - * @ignore - */ - protected vibrateDuration: number; - private get whenToVibrateforSuccessfulRead(); - /** - * Whether to vibrate when the scanner reads a barcode successfully. - * Default value is `never`, which does not vibrate. - * Use `frame` to vibrate when any barcode is found within a frame. - * Use `unique` to vibrate only when any unique/unduplicated barcode is found within a frame. - * ```js - * // Can I use? https://caniuse.com/?search=vibrate - * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies - * startPlayButton.addEventListener('click', function() { - * scanner.whenToVibrateforSuccessfulRead = 'frame'; - * }); - * ``` - * @ignore - */ - private set whenToVibrateforSuccessfulRead(value); - protected captureAndDecodeInParallel: boolean; - protected autoSuggestTip: boolean; - protected suggestTipFrameArray: Array; - protected suggestTipFrameLimit: number[]; - protected noIntermediateResultsCount: number; - protected noIntermediateResultsTipLimit: number; - protected tinyBarcodeTipModuleSizeLimit: number; - protected hugeBarcodeTipLimit: number; - protected autoZoomInFrameArray: Array; - protected autoZoomInFrameLimit: number[]; - protected autoZoomInStepRate: number; - protected autoZoomInMaxStep: number; - protected autoZoomInMaxTimes: number; - protected autoZoomInMinStep: number; - protected autoZoomInIdealModuleSize: number; - protected autoZoomOutFrameCount: number; - protected autoZoomOutFrameLimit: number; - protected autoZoomOutStepRate: number; - protected autoZoomOutMinValue: number; - protected autoZoomOutMinStep: number; - protected autoZoomOutStepRate_2: number; - protected autoZoomOutMinValue_2: number; - protected frameArrayInIdealZoom: Array; - protected frameLimitInIdealZoom: number[]; - protected enableZoomOutInIdealZoom: boolean; - protected nextActionInIdealZoom: string; - protected autoFocusFrameArray: Array; - protected autoFocusFrameLimit: number[]; - protected autoZoomIdealArea: number[]; - protected autoZoomTargetBorder: number; - protected autoZoomDetectionArea: number; - protected autoZoom: boolean; - protected autoFocus: boolean; - protected _clearResultsCanvasTimeoutId: any; - _resultHighlightingDuration: number; - private _dce; - protected set dce(value: CameraEnhancer); - protected get dce(): CameraEnhancer; - protected _drawingItemNamespace: any; - protected _styleIdBeforeVerification: number; - private _dceControler; - private _imgSource; - private callbackCameraChange?; - private callbackResolutionChange?; - private callbackCameraClose?; - private callbackSingleFrameAcquired?; - protected _maxCvsSideLength: number; - /** @ignore */ - set maxCvsSideLength(value: number); - get maxCvsSideLength(): number; - private _registerDCEControler; - private _logoutDCEControler; - /** - * Sets an image source for continous scanning. - * @param imgSource Specifies the image source. - * @param options Options to help with the usage of the `ImageSource` object. At present, it only contains one property `resultsHighlightBaseShapes` that accepts `Dynamsoft.DCE.DrawingItem` as its value to help with the highlighting of barcode regions as shown in the code snippet below. More properties will be added as needed in the future. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); - * let options = { resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem }; - * await reader.setImageSource(enhancer, options); - * reader.onUniqueRead = (txt, result) => { - * console.log(txt); - * }; - * await reader.startScanning(true); - * ``` - * @see {@link ImageSource} - */ - setImageSource(imgSource: ImageSource | CameraEnhancer, options?: any): Promise; - /** - * Downloads and compiles the engine to get it loaded/ready for a `BarcodeReader` or `BarcodeScanner` instance to be created. - * You can call this API to silently set the operating environment of the library as soon as the page is loaded, avoiding unnecessary waiting time when using the library later. - * - * If this API is not called beforehand, it will be called automatically when creating an instance of `BarcodeReader` or `BarcodeScanner`. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * window.addEventListener('DOMContentLoaded', (event) => { - * Dynamsoft.DBR.BarcodeReader.loadWasm(); - * }); - * ``` - * @category Initialize and Destroy - */ - static loadWasm(): Promise; - /** - * @param type "warn" or "error" - * @param content - * @returns - */ - protected static showDialog(type: string, content: string): Promise; - protected static createInstanceInWorker(bScanner?: boolean): Promise; - protected constructor(); - /** - * Creates a `BarcodeReader` instance. - * @returns A promise resolving to the created `BarcodeReader` object. - * @example - * ``` - * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - * ``` - * @see {@link destroyContext} - * @category Initialize and Destroy - */ - static createInstance(): Promise; - protected clearMapDecodeRecord(): Promise; - /** - * Decode barcodes from a image. - * If the content in the binary data is raw img data, such as `RGBA` , use {@link decodeBuffer} instead. - * - * Note: To speed up the reading, the image will be scaled down when it exceeds a size limit either horizontally or vertically. - * The limit is 2048 pixels on mobile devices and 4096 on other devices. - * If the template "dense" or "distance" is used, the limit is 4096 regardless of which device is used. - * @param source specifies the image to decode. The supported image formats include `png` , `jpeg` , `bmp` , `gif` and a few others (some browsers support `webp` , `tif` ). - * Also note that the image can be specified in a lot of ways including binary data, base64 string (with MIME), URL, etc. - * @returns A promise resolving to an array of `TextResult` that contains all the barcode results found in this image. - * @example - * ```js - * let results1 = await reader.decode(blob); - * let results2 = await reader.decode(htmlImageElement); - * let results3 = await reader.decode(url); - * let results4 = await reader.decode(base64WithMime); // like `data:image/png;base64,iV************` - * ``` - * - * You can even use an `HTMLVideoElement` as the source. If the video is playing, the current frame will be decoded. - * - * ```js - * let results; - * try{ - * // The current frame will be decoded. - * results = await reader.decode(htmlVideoElement); - * }catch(ex){ - * // If no frame in the video, will throw an exception. - * } - * ``` - * @see {@link TextResult} - * @see {@link decodeBuffer} - * @category Decode - */ - decode(source: Blob | Buffer | ArrayBuffer | Uint8Array | Uint8ClampedArray | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | string | DCEFrame | DSImage): Promise; - /** - * Decodes barcodes from a base64-encoded image (with or without MIME). - * @param base64 Specifies the image represented by a string. - * @returns A promise resolving to an array of {@link TextResult} object that contains the barcode results found in this image. - * @example - * ```js - * let results = await reader.decodeBase64String(strBase64); //e.g. `data:image/jpg;base64,Xfjshekk....` or `Xfjshekk...`. - * for(let result of results){ - * console.log(result.barcodeText); - * } - * ``` - * @see {@link TextResult} - * @category Decode - */ - decodeBase64String(base64: string): Promise; - /** - * Decodes barcodes from an image specified by its URL. - * - * Note that the image should either be from the same domain or has the 'Access-Control-Allow-Origin' header set to allow access from your current domain. - * @param url Specifies the image by its URL. - * @returns A promise resolving to an array of {@link TextResult} object that contains the barcode results found in this image. - * @example - * ```js - * let results = await reader.decodeUrl("https://www.yourdomain.com/imageWithBarcodes.png"); - * for(let result of results){ - * console.log(result.barcodeText); - * } - * ``` - * @see {@link TextResult} - * @category Decode - */ - decodeUrl(url: string): Promise; - /** - * Decodes barcodes from the memory buffer containing image pixels in defined format. - * @ignore - */ - _decodeBuffer_Uint8Array(buffer: Uint8Array | Uint8ClampedArray, width: number, height: number, stride: number, format: EnumImagePixelFormat, orientation?: number, config?: any): Promise; - /** - * - * @param buffer - * @param width - * @param height - * @param stride - * @param format - * @param config - * @ignore - */ - _decodeBuffer_Blob(buffer: Blob, width: number, height: number, stride: number, format: EnumImagePixelFormat, orientation?: number, config?: any): Promise; - /** - * Decodes barcodes from raw image data. It is an advanced API, if you don't know what you are doing, use [decode](#decode) instead. - * @param buffer Specifies the raw image represented by a `Uint8Array` , `Uint8ClampedArray` , `ArrayBuffer` , `Blob` or `Buffer` object. - * @param width Image width. - * @param height Image height. - * @param stride `image-width * pixel-byte-length`. - * @param format Pixel format. - * @param config Specifies the oritation of the image data. - * @returns A promise resolving to an array of {@link TextResult} object that contains the barcode results found in this image. - * @example - * ```js - * let results = await reader.decodeBuffer(u8RawImage, 1280, 720, 1280 * 4, Dynamsoft.DBR.EnumImagePixelFormat.IPF_ABGR_8888); - * for (let result of results) { - * console.log(result.barcodeText); - * } - * ``` - * @see {@link TextResult} - * @see {@link EnumImagePixelFormat} - * @category Decode - */ - decodeBuffer(buffer: Uint8Array | Uint8ClampedArray | ArrayBuffer | Blob | Buffer, width: number, height: number, stride: number, format: EnumImagePixelFormat, orientation?: number, config?: any): Promise; - /** @ignore */ - _decodeFileInMemory_Uint8Array(bytes: Uint8Array): Promise; - /** - * Returns the current runtime settings. - * @returns A promise resolving to a {@link RuntimeSettings} object that contains the settings for barcode reading. - * @example - * ```js - * let settings = await reader.getRuntimeSettings(); - * settings.deblurLevel = 5; - * await reader.updateRuntimeSettings(settings); - * ``` - * @see {@link RuntimeSettings} - * @see {@link updateRuntimeSettings} - * @see {@link resetRuntimeSettings} - * @category Runtime Settings - */ - getRuntimeSettings(): Promise; - /** - * Updates runtime settings. - * @param settings a {@link RuntimeSettings} object, or a string represent one of preset templates: - * - * `speed`: fast but may miss a few codes; - * - * `coverage`: slow but try to find all codes, this is the default setting for a `BarcodeReader` instance; - * - * `balance`: between `speed` and `coverage`; - * - * `dense`: optimized for scanning dense barcodes such as the PDF417 on driver's license; - * - * `distance`: optimized for scanning a barcode that is placed far from the device and appear small in the video stream. - * - * Note: If the settings `barcodeFormatIds` , `barcodeFormatIds_2` and `region` have been changed by the customer, changing the template will preserve the previous settings. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await reader.updateRuntimeSettings('balance'); - * let settings = await reader.getRuntimeSettings(); - * settings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED; - * await reader.updateRuntimeSettings(settings); - * ``` - * @see {@link RuntimeSettings} - * @see {@link getRuntimeSettings} - * @see {@link resetRuntimeSettings} - * @category Runtime Settings - */ - updateRuntimeSettings(settings: RuntimeSettings | string): Promise; - /** - * Resets all parameters to default values. - * - * For a `BarcodeReader` instance, it is equivalent to setting the `coverage` template. - * - * For a `BarcodeScanner` instance, it is equivalent to setting the `single` template. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await reader.resetRuntimeSettings(); - * ``` - * @category Runtime Settings - */ - resetRuntimeSettings(): Promise; - /** - * - * @returns - * @ignore - */ - _resetRuntimeSettingsToCppDefault(): Promise; - /** - * Return the current `RuntimeSettings` in the form of a string. - * @returns A promise resolving to a string which represents the current `RuntimeSettings`. - * @example - * ```js - * let strSettings = await reader.outputRuntimeSettingsToString(); - * ``` - * @see {@link RuntimeSettings} - * @see {@link getRuntimeSettings} - * @category Runtime Settings - */ - outputRuntimeSettingsToString(): Promise; - /** - * Initialize runtime settings with the settings in given JSON string. - * @param settings A string representing the template. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await reader.initRuntimeSettingsWithString("{\"Version\":\"3.0\", \"ImageParameter\":{\"Name\":\"IP1\", \"BarcodeFormatIds\":[\"BF_QR_CODE\"], \"ExpectedBarcodesCount\":10}}"); - * ``` - * @see {@link RuntimeSettings} - * @see {@link updateRuntimeSettings} - * @category Runtime Settings - */ - initRuntimeSettingsWithString(settings: any): Promise; - private _decode_Blob; - /** - * - * @param arrayBuffer - * @param config - * @ignore - */ - private _decode_ArrayBuffer; - /** - * - * @param uint8Array - * @param config - * @ignore - */ - private _decode_Uint8Array; - /** - * - * @param image - * @param config - * @ignore - */ - private _decode_Image; - private _decode_Canvas; - /** - * decode video is not multi call safe in an instance, we reuse many thing for speed, so make sure wait util one finish then call next - * @param video - * @param config - * @ignore - */ - _decode_Video(video: HTMLVideoElement, config?: any): Promise; - /**@ignore */ - _decode_DCEFrame(dceFrame: DCEFrame, config?: any): Promise; - /**@ignore */ - _decode_DSImage(dsImage: DSImage, config?: any): Promise; - private _decode_Base64; - private _decode_Url; - private _decode_FilePath; - /** - * The coordinates of results are related to the cropping image gotten from DCE JS. Transform it to the coordinates related to the whole video/image. - * @ignore - */ - static recalculateResultLocation(results: Array<{ - localizationResult: any; - }>, sx: number, sy: number, sWidth: number, sHeight: number, dWidth: number, dHeight: number): void; - /** @ignore */ - static BarcodeReaderException(ag0: any, ag1: any): BarcodeReaderException; - protected _handleRetJsonString(objRet: any): any; - /** - * Sets the argument value for the specified mode parameter. - * @param modeName Specifies the mode which contains one or multiple elements. - * @param index Specifies an element of the mode by its index. - * @param argumentName Specifies the argument. - * @param argumentValue Specifies the value. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await reader.setModeArgument("BinarizationModes", 0, "EnableFillBinaryVacancy", "1"); - * ``` - * @see {@link getModeArgument} - * @category Runtime Settings - */ - setModeArgument(modeName: string, index: number, argumentName: string, argumentValue: string): Promise; - /** - * Returns the argument value for the specified mode parameter. - * @param modeName Specifies the mode which contains one or multiple elements. - * @param index Specifies an element of the mode by its index. - * @param argumentName Specifies the argument. - * @returns A promise resolving to a string which represents the value of the argument. - * @example - * ```js - * let argumentValue = await reader.getModeArgument("BinarizationModes", 0, "EnableFillBinaryVacancy"); - * ``` - * @see {@link setModeArgument} - * @category Runtime Settings - */ - getModeArgument(modeName: string, index: number, argumentName: string): Promise; - /** - * The method is only supported in the full feature edition. - * Returns intermediate results containing the original image, the colour clustered image, the binarized Image, contours, Lines, TextBlocks, etc. - * ```js - * let imResults = await reader.getIntermediateResults(); - * ``` - * @ignore - */ - getIntermediateResults(): Promise; - /** @ignore */ - getIntermediateCanvas(): Promise; - /** - * This event is triggered after the library finishes scanning a image. - * @event onImageRead - * @defaultValue `undefined` - * @param results An array of `TextResult` object that contains the barcode results in this frame. - * @example - * ```js - * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); - * let options = { - * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem - * }; - * await reader.setImageSource(enhancer, options); - * reader.onImageRead = (results) => { - * if (results.length > 0) { - * results.forEach(result => { - * console.log(result.barcodeText); - * }); - * } - * }; - * await reader.startScanning(true); - * ``` - * @see {@link TextResult} - * @see {@link onUniqueRead} - */ - onImageRead?: (results: TextResult[]) => void; - /** - * This event is triggered when a new, unduplicated label is found. - * @event onUniqueRead - * @defaultValue `undefined` - * @param txt A string that holds the barcode text. - * @param txt A {@link TextResult} object that contains more detailed info. - * @example - * ```js - * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); - * let options = { - * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem - * }; - * await reader.setImageSource(enhancer, options); - * reader.onUniqueRead = (txt, result) => { - * console.log(txt); - * }; - * await reader.startScanning(true); - * ``` - * @see {@link TextResult} - * @see {@link onImageRead} - */ - onUniqueRead?: (txt: string, result: TextResult) => void; - /** - * Get current scan settings. - * @returns A promise resolving to a {@link ScanSettings}. - * @example - * ```js - * let scanSettings = await scanner.getScanSettings(); - * scanSettings.intervalTime = 50; - * scanSettings.duplicateForgetTime = 1000; - * await scanner.updateScanSettings(scanSettings); - * ``` - * @see {@link ScanSettings} - * @see {@link updateScanSettings} - */ - getScanSettings(): Promise; - /** - * Changes scan settings with the object passed in. - * @param settings Specifies the new scan settings. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * let scanSettings = await scanner.getScanSettings(); - * scanSettings.intervalTime = 50; - * scanSettings.duplicateForgetTime = 1000; - * await scanner.updateScanSettings(scanSettings); - * ``` - * @see {@link ScanSettings} - * @see {@link getScanSettings} - */ - updateScanSettings(settings: ScanSettings): Promise; - /** @ignore */ - _cloneDecodeResults(results: any): any; - protected _loopReadVideo(): Promise; - /** - * start dce fetching frame loop, and get frame from frame queue - * @ignore - */ - protected _getVideoFrame(): DCEFrame; - /** - * Add drawing items according to results, and add notes to drawing items. - * @param results - * @param notes - * @returns - * @ignore - */ - protected _drawResults(results: Array<{ - localizationResult: any; - resultState?: number; - }>, notes?: Array): void; - /** - * _promiseStartScan.status == "pending"; // camera is openning. - * _promiseStartScan.status == "fulfilled"; // camera is opened. - * _promiseStartScan == null; // camera is closed. - * @ignore - */ - private _promiseStartScan; - /** - * Open the camera and starts continuous scanning of incoming images. - * @param appendOrShowUI this parameter specifies how to handle the UI that comes with the bound CameraEnhancer instance. - * When set to true, if the UI doesn't exist in the DOM tree, the `CameraEnhancer` instance will append it in the DOM and show it; if the UI already exists in the DOM tree but is hidden, it'll be displayed. - * When not set or set to false, it means not to change the original state of that UI: if it doesn't exist in the DOM tree, nothing shows up on the page; if it exists in the DOM tree, it may or may not show up depending on its original state. - * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object which contains the resolution of the video. - * @example - * ```js - * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); - * let options = { - * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem - * }; - * await reader.setImageSource(enhancer, options); - * reader.onUniqueRead = (txt, result) => { - * console.log(txt); - * }; - * await reader.startScanning(true); - * ``` - * @see {@link ScannerPlayCallbackInfo} - * @see {@link stopScanning} - * @see {@link pauseScanning} - * @see {@link resumeScanning} - * @category Open and Close - */ - startScanning(bShowUI?: boolean): Promise; - /** - * Stops continuous scanning and closes the video stream. - * @param hideUI this parameter specifies how to handle the UI that comes with the bound `CameraEnhancer` instance. - * When set to true, if the UI doesn't exist in the DOM tree or it exists but is hidden, nothing is done; if the UI already exists in the DOM tree and is shown, it'll be hidden. - * When not set or set to false, it means not to change the original state of that UI: if it doesn't exist in the DOM tree, nothing happens; if it exists in the DOM tree, it may or may not be hidden depending on its original state. - * @example - * ```js - * let reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - * let enhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(); - * let options = { - * resultsHighlightBaseShapes: Dynamsoft.DCE.DrawingItem - * }; - * await reader.setImageSource(enhancer, options); - * reader.onUniqueRead = (txt, result) => { - * console.log(txt); - * reader.stopScanning(true); - * }; - * await reader.startScanning(true); - * ``` - * @see {@link startScanning} - * @see {@link pauseScanning} - * @see {@link resumeScanning} - * @category Open and Close - */ - stopScanning(bHideUI?: boolean): void; - /** - * Pause continuous scanning but keep the video stream. - * @param options Options to configure how the pause works. - * At present, it only contains one property `keepResultsHighlighted` which, when set to `true`, will keep the barcodes found on the frame (at the time of the pause) highlighted. - * @see {@link resumeScanning} - * @category Pause and Resume - */ - pauseScanning(options?: any): void; - /** - * Resumes continuous scanning. - * @see {@link pauseScanning} - * @category Pause and Resume - */ - resumeScanning(): void; - /** - * Destroy the `BarcodeReader` instance. - * If your page needs to create new instances from time to time, don't forget to destroy unused old instances. - * @see {@link isContextDestroyed} - * @category Initialize and Destroy - */ - destroyContext(): void; -} -//# sourceMappingURL=barcodereader.d.ts.map \ No newline at end of file diff --git a/dist/types/class/barcodescanner.d.ts b/dist/types/class/barcodescanner.d.ts deleted file mode 100644 index 0282361..0000000 --- a/dist/types/class/barcodescanner.d.ts +++ /dev/null @@ -1,953 +0,0 @@ -import { TextResult } from '../interface/textresult'; -import { VideoDeviceInfo } from '../interface/videodeviceinfo'; -import { ScannerPlayCallbackInfo } from '../interface/scannerplaycallbackinfo'; -import BarcodeReader from './barcodereader'; -import { RuntimeSettings } from '../interface/runtimesettings'; -import { Region } from '../interface/region'; -import { DCEFrame } from 'dynamsoft-camera-enhancer'; -import { Warning } from '../interface/warning'; -/** - * The `BarcodeScanner` class is used for video decoding. - * Its instance gets access to a camera via the 'MediaDevices' interface, then uses its built-in UI to show the camera input and perform continuous barcode scanning on the incoming frames. - * @example - * ```js - * let scanner; - * (async()=>{ - * scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - * scanner.onUniqueRead = txt => console.log(txt); - * await scanner.show(); - * })(); - * ``` - * @extends BarcodeReader - */ -export default class BarcodeScanner extends BarcodeReader { - #private; - /** @ignore */ - static set _onLog(value: (message: any) => void); - static get _onLog(): (message: any) => void; - /** - * Returns the version of the library including the detailed version numbers of the engine and the main JavaScript code. - * - * The engine version is only valid after {@link loadWasm} has been called. - * @readonly - */ - static get version(): string; - /** - * A callback which is triggered when the running environment is not ideal. In this version, it may get triggered in two scenarios: - * - * 1. If the page is opened from the disk - * 2. The page is hosted in a HTTP site without SSL - * - * In both cases, the following warning is returned: - * ```js - * { - * id: 2, - * message: "Not connected via SSL (HTTPS), the SDK may not work correctly." - * } - * ``` - * @defaultValue `undefined` - * @see {@link Warning} - */ - static onWarning: (warning: Warning) => void; - protected static _fireHTTPSWarnning(): void; - /** - * Test whether there is an available camera. It is also a trick to speed up the opening of the camera. - * @returns A promise resolving to a object contains the message. - */ - static testCameraAccess(): Promise<{ - ok: boolean; - message: string; - }>; - /** - * A callback which is triggered when the resolution is not ideal (< 720P). - * @defaultValue `undefined` - * @see {@link Warning} - */ - onWarning: (warning: Warning) => void; - private _fireResolutionWarning; - /** - * Returns the HTML element that is used by the `BarcodeScanner` instance. - * @returns The HTML element that is used by the `BarcodeScanner` instance. - * @see {@link setUIElement} - * @category UI - */ - getUIElement(): HTMLElement; - /** - * Specifies an HTML element for the `BarcodeScanner` instance to use as its UI. The structure inside the element determines the appearance of the UI. - * @param elementOrUrl specifies the element or the element url. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```html - *
- * - * ``` - * @see {@link getUIElement} - * @category UI - */ - setUIElement(elementOrUrl: HTMLElement | string): Promise; - /** - * Returns or sets the status of single frame mode. - * If enabled, the video input will not be played and the user can choose to take a picture with the system camera (mobile only) or select an existing image from the photo library for barcode reading. - * - * Because the system camera of a mobile device can provide pictures with better quality, the API is useful when facing complex scenarios such as reading the dense PDF417 code on a driver license. - * - * The single-frame mode can only be enabled or disabled before the video input starts playing (before `scanner.show()` is called). - * @defaultValue In general, the default value is `false`. But if the browser does not support the `MediaDevices`/`getUserMedia`, it will be set as `true` automatically when {@link createInstance} is called. - * @example - * ```js - * let scanner; - * (async()=>{ - * scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - * scanner.singleFrameMode = true; - * await scanner.show(); - * })(); - * ``` - */ - get singleFrameMode(): boolean | "image" | "camera"; - set singleFrameMode(value: boolean | "image" | "camera"); - /** - * Specifies an event handler which fires after the library finishes scanning a frame. - * @event onFrameRead - * @defaultValue `undefined` - * @param results An array of {@link TextResult} object that contains the barcode results in this frame. - * @example - * ```js - * scanner.onFrameRead = results => { - * for(let result of results){ - * console.log(result.barcodeText); - * } - * }; - * ``` - * @see {@link TextResult} - * @see {@link onUniqueRead} - */ - onFrameRead?: (results: TextResult[]) => void; - /** - * @deprecated Use {@link onUniqueRead} instead. - */ - get onUnduplicatedRead(): (txt: string, result: TextResult) => void; - set onUnduplicatedRead(value: (txt: string, result: TextResult) => void); - /** - * Returns `HTMLVideoElement` element that the `BarcodeScanner` instance used. - * @readonly - */ - get video(): HTMLVideoElement; - /** - * Sets or returns the source of the video. - * You can use this property to specify an existing video as the source to play which will be processed the same way as the video feed from a live camera. - * @defaultValue `null` - */ - set videoSrc(source: string | MediaStream | MediaSource | Blob); - get videoSrc(): string | MediaStream | MediaSource | Blob; - /** - * An event that gets triggered whenever a 'Tip' is suggested. - * @event onTipSuggested - * @defaultValue `undefined` - * @param occasion Specifies the occasion for the Tip. - * @param message The 'Tip' message for the occasion. - * @see {@link showTip} - */ - set onTipSuggested(value: (occasion: string, message: string) => void); - get onTipSuggested(): (occasion: string, message: string) => void; - private _assertOpen; - private _barcodeFillStyle; - /** - * Specifies the color used inside the shape which highlights a found barcode. - * @defaultValue `"rgba(254,180,32,0.3)"` - * @see {@link barcodeStrokeStyle} - * @see {@link barcodeLineWidth} - * @see {@link barcodeFillStyleBeforeVerification} - * @see {@link barcodeStrokeStyleBeforeVerification} - * @see {@link barcodeLineWidthBeforeVerification} - * @category UI - */ - set barcodeFillStyle(style: string); - get barcodeFillStyle(): string; - private _barcodeStrokeStyle; - /** - * Specifies the color used to paint the outline of the shape which highlights a found barcode. - * @defaultValue `"rgba(254,180,32,0.9)"` - * @see {@link barcodeFillStyle} - * @see {@link barcodeLineWidth} - * @see {@link barcodeFillStyleBeforeVerification} - * @see {@link barcodeStrokeStyleBeforeVerification} - * @see {@link barcodeLineWidthBeforeVerification} - * @category UI - */ - set barcodeStrokeStyle(style: string); - get barcodeStrokeStyle(): string; - private _barcodeLineWidth; - /** - * Specifies the line width of the outline of the shape which highlights a found barcode. - * @defaultValue `1` - * @see {@link barcodeFillStyle} - * @see {@link barcodeStrokeStyle} - * @see {@link barcodeFillStyleBeforeVerification} - * @see {@link barcodeStrokeStyleBeforeVerification} - * @see {@link barcodeLineWidthBeforeVerification} - * @category UI - */ - set barcodeLineWidth(width: number); - get barcodeLineWidth(): number; - private _barcodeFillStyleBeforeVerification; - /** - * Specifies the color used inside the shape which highlights a found linear barcode which has not been verified. - * @defaultValue `"rgba(248,252,0,0.2)"` - * @see {@link barcodeStrokeStyleBeforeVerification} - * @see {@link barcodeLineWidthBeforeVerification} - * @see {@link barcodeFillStyle} - * @see {@link barcodeStrokeStyle} - * @see {@link barcodeLineWidth} - * @category UI - */ - set barcodeFillStyleBeforeVerification(style: string); - get barcodeFillStyleBeforeVerification(): string; - private _barcodeStrokeStyleBeforeVerification; - /** - * Specifies the color used to paint the outline of the shape which highlights a found linear barcode which has not been verified. - * @defaultValue `"transparent"` - * @see {@link barcodeFillStyleBeforeVerification} - * @see {@link barcodeLineWidthBeforeVerification} - * @see {@link barcodeFillStyle} - * @see {@link barcodeStrokeStyle} - * @see {@link barcodeLineWidth} - * @category UI - */ - set barcodeStrokeStyleBeforeVerification(style: string); - get barcodeStrokeStyleBeforeVerification(): string; - private _barcodeLineWidthBeforeVerification; - /** - * Specifies the line width of the outline of the shape which highlights a found linear barcode which has not been verified. - * @defaultValue `2` - * @see {@link barcodeFillStyleBeforeVerification} - * @see {@link barcodeStrokeStyleBeforeVerification} - * @see {@link barcodeFillStyle} - * @see {@link barcodeStrokeStyle} - * @see {@link barcodeLineWidth} - * @category UI - */ - set barcodeLineWidthBeforeVerification(width: number); - get barcodeLineWidthBeforeVerification(): number; - /** - * Specifies the color used in the square-loop shape between the actual scanning area and the boundary of the video input. This shape only appears when the barcode scanning is limited to a specified region. - * @defaultValue `"rgba(0, 0, 0, 0.5)"` - * @see {@link regionMaskStrokeStyle} - * @see {@link regionMaskLineWidth} - * @category UI - */ - set regionMaskFillStyle(value: string); - get regionMaskFillStyle(): string; - /** - * Specifies the color used to paint the outline of the scanning region. This outline only appears when the barcode scanning is limited to a specified region. - * @defaultValue `"rgb(254, 142, 20)"` - * @see {@link regionMaskFillStyle} - * @see {@link regionMaskLineWidth} - * @category UI - */ - set regionMaskStrokeStyle(value: string); - get regionMaskStrokeStyle(): string; - /** - * Specifies the width of the outline of the scanning region. This outline only appears when the barcode scanning is limited to a specified region. - * @defaultValue `2` - * @see {@link regionMaskFillStyle} - * @see {@link regionMaskStrokeStyle} - * @category UI - */ - set regionMaskLineWidth(value: string); - get regionMaskLineWidth(): string; - protected bFilterRegionInJs: boolean; - protected set region(value: null | Region | Region[]); - protected get region(): null | Region | Region[]; - /** - * Whether to save the original image into a `HTMLCanvasElement` element. The original image refers to the actual image the library tried to read barcodes from. It can be returned by {@link getOriginalImageInACanvas}. - * @defaultValue `false` - * @example - * ```js - * scanner.ifSaveOriginalImageInACanvas = true; - * let results = await scanner.decode(source); - * document.body.append(scanner.getOriginalImageInACanvas()); - * ``` - * @see {@link getOriginalImageInACanvas} - */ - set ifSaveOriginalImageInACanvas(value: boolean); - get ifSaveOriginalImageInACanvas(): boolean; - private createDCEInstance; - /** @ignore */ - set maxCvsSideLength(value: number); - get maxCvsSideLength(): number; - private constructor(); - /** - * Create a `BarcodeScanner` object. - * @returns A promise resolving to the created `BarcodeScanner` object. - * @example - * ```js - * let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - * ``` - * @see {@link destroyContext} - * @category Initialize and Destroy - */ - static createInstance(config?: any): Promise; - /** - * Decode barcodes from the current frame of the video. - * @returns A promise resolving to an array of {@link TextResult} that contains all the barcode results. - * @example - * ```js - * await scanner.showVideo(); - * console.log(await scanner.decodeCurrentFrame()); - * ``` - * @see {@link TextResult} - * @category Decode - */ - decodeCurrentFrame(config?: any): Promise; - /** - * Update runtime settings. - * @param settings a `RuntimeSettings` object, or a string represent one of preset templates: - * - * `speed`: fast but may miss a few codes; - * - * `coverage`: slow but try to find all codes, this is the default setting for a `BarcodeReader` instance; - * - * `balance`: between `speed` and `coverage`; - * - * `single`: optimized for scanning one single barcode from a video input, this is the default setting for a `BarcodeScanner` instance; - * - * `dense`: optimized for scanning dense barcodes such as the PDF417 on driver's license; - * - * `distance`: optimized for scanning a barcode that is placed far from the device and appear small in the video stream. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await scanner.updateRuntimeSettings('balance'); - * let settings = await scanner.getRuntimeSettings(); - * settings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED; - * await scanner.updateRuntimeSettings(settings); - * ``` - * @see {@link RuntimeSettings} - * @see {@link getRuntimeSettings} - * @see {@link resetRuntimeSettings} - * @category Runtime Settings - */ - updateRuntimeSettings(settings: RuntimeSettings | string): Promise; - /** @ignore */ - _bindUI(): void; - /** @ignore */ - _unbindUI(): void; - private _onPlayed; - /** - * This event is triggered when the video stream starts playing. - * @event - * @defaultValue `null` - * @example - * ```js - * scanner.onPlayed = rsl=>{ console.log(rsl.width+'x'+rsl.height) }; - * await scanner.show(); // or open, play, setCurrentCamera, like these. - * ``` - */ - set onPlayed(value: (info: ScannerPlayCallbackInfo) => void); - get onPlayed(): (info: ScannerPlayCallbackInfo) => void; - /** - * Returns infomation of all available cameras on the device. - * @returns A promise resolving to an array of {@link VideoDeviceInfo} objects. - * @example - * ```js - * let cameras = await scanner.getAllCameras(); - * if(cameras.length){ - * await scanner.setCurrentCamera(cameras[0]); - * } - * ``` - * @see {@link VideoDeviceInfo} - * @see {@link getCurrentCamera} - * @category Camera Settings - */ - getAllCameras(): Promise; - /** - * Returns information about the current camera. - * @returns A promise resolving to a {@link VideoDeviceInfo} object. - * @example - * ```js - * let camera = await scanner.getCurrentCamera(); - * ``` - * @see {@link VideoDeviceInfo} - * @see {@link getAllCameras} - * @see {@link setCurrentCamera} - * @category Camera Settings - */ - getCurrentCamera(): Promise; - /** - * Chooses a camera as the video source. - * @param cameraInfoOrDeviceId Specifies the camera. - * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. - * @example - * ```js - * let cameras = await scanner.getAllCameras(); - * if(cameras.length){ - * await scanner.setCurrentCamera(cameras[0]); - * } - * ``` - * @fires {@link onPlayed} - * @see {@link ScannerPlayCallbackInfo} - * @see {@link getCurrentCamera} - * @category Camera Settings - */ - setCurrentCamera(cameraInfoOrDeviceId: any): Promise; - /** - * Returns the resolution of the current video input. - * @returns An array of two numbers representing the resolution. - * @example - * ```js - * let rsl = await scanner.getResolution(); - * console.log(rsl[0] + " x " + rsl[1]); - * ``` - * @see {@link setResolution} - * @category Camera Settings - */ - getResolution(): number[]; - /** - * Sets the resolution of the current video input. If the specified resolution is not exactly supported, the closest resolution will be applied. - * - * If called before `open()` or `show()`, the camera will use the set resolution when it opens. Otherwise, the default resolution is used, which is 1280 x 720 on mobile devices or 1920 x 1080 on desktop. - * @param width Specifies the horizontal resolution. - * @param height Specifies the vertical resolution. - * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. - * @example - * ```js - * await scanner.setResolution(width, height); - * ``` - * @fires {@link onPlayed} - * @see {@link ScannerPlayCallbackInfo} - * @see {@link getResolution} - * @category Camera Settings - */ - setResolution(width: number | number[], height: number): Promise; - /** - * Returns the current video settings. - * @returns A `MediaStreamConstraints` object. - * @see {@link updateVideoSettings} - * @category Camera Settings - */ - getVideoSettings(): MediaStreamConstraints; - /** - * Modify and update video settings. - * @param mediaStreamConstraints Specifies the new video settings. - * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. - * @example - * ```js - * await scanner.updateVideoSettings({ video: {width: {ideal: 1280}, height: {ideal: 720}, facingMode: {ideal: 'environment'}} }); - * ``` - * @see {@link ScannerPlayCallbackInfo} - * @see {@link getVideoSettings} - * @category Camera Settings - */ - updateVideoSettings(mediaStreamConstraints: any): Promise; - /** - * Indicates whether the camera is turned on. - * @returns A boolean indicates whether the camera is turned on. - * @example - * ```js - * await scanner.show(); // or open(), showVideo(), openVideo(); - * console.assert(scanner.isOpen(), "scanner should be opened."); - * await scanner.hide(); // or close(); - * console.assert(!scanner.isOpen(), "scanner should be closed."); - * ``` - * @category Open and Close - */ - isOpen(): boolean; - /** - * Sets the `object-fit` CSS property of the video element. - * @param value Specify the new fit type. At present, only "cover" and "contain" are allowed. - * @see {@link getVideoFit} - */ - setVideoFit(value: string): void; - /** - * Returns the value of the object-fit CSS property of the video element. - * @returns The value of the object-fit CSS property. - * @see {@link setVideoFit} - */ - getVideoFit(): string; - /** - * Whether to show the scan region mask. - * @defaultValue `true` - */ - set ifShowScanRegionMask(value: boolean); - get ifShowScanRegionMask(): boolean; - /** - * Returns or sets whether to save the last used camera and resolution. - * This feature makes use of the `localStorage` of the browser. - * - * Note: This feature only works on mainstream browsers like Chrome, Firefox and Safari. Other browsers may change the device IDs dynamically thus making it impossible to track the camera. - * @defaultValue `false` - */ - set ifSaveLastUsedCamera(value: boolean); - get ifSaveLastUsedCamera(): boolean; - /** - * Returns or sets whether to skip camera inspection at initialization to save time. - * Note that if a previously used camera is already available in the `localStorage`, the inspection is skipped automatically. Read more on {@link ifSaveLastUsedCamera}. - * @defaultValue `false` - */ - set ifSkipCameraInspection(value: boolean); - get ifSkipCameraInspection(): boolean; - /** - * Stops the video and releases the camera. - * @example - * ```js - * scanner.stop() - * // *** a lot of work *** - * await scanner.play(); - * ``` - * @see {@link play} - * @category Play and Pause - */ - stop(): void; - /** - * Pauses the video without releasing the camera. - * @example - * ```js - * scanner.pause(); - * // *** a lot of work *** - * await scanner.play(); - * ``` - * @see {@link play} - * @category Play and Pause - */ - pause(): void; - /** - * Play the video if it is already open but paused or stopped. If the video is already playing, it will start again. - * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. - * @fires [[onPlayed]] - * @example - * ```js - * scanner.pause(); // or scanner.stop() - * // *** a lot of work *** - * await scanner.play(); - * ``` - * @see {@link ScannerPlayCallbackInfo} - * @see {@link stop} - * @see {@link pause} - * @category Play and Pause - */ - play(deviceId?: string, width?: number, height?: number): Promise; - /** - * Pause continuous scanning but keep the video stream. - * @param options Options to configure how the pause works. At present, it only contains one property `keepResultsHighlighted` which, when set to `true`, will keep the barcodes found on the frame (at the time of the pause) highlighted. - * @see {@link resumeScan} - * @category Play and Pause - */ - pauseScan(options?: any): void; - /** - * Resumes the decoding process. - * @see {@link pauseScan} - * @category Play and Pause - */ - resumeScan(): void; - /** - * Inspects and returns the capabilities of the current camera. - * - * Note: At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported). - * Also, it should be called when a camera is open. - * @returns A `MediaTrackCapabilities` object which specifies the values or range of values for each constrainable property of the current camera. - * @example - * ``` - * scanner.getCapabilities() - * // Result sample - * { - * "aspectRatio":{"max":3840,"min":0.000462962962962963}, - * "colorTemperature":{max: 7000, min: 2850, step: 50}, - * "deviceId":"1e...3af7", - * "exposureCompensation": {max: 2.0000040531158447, min: -2.0000040531158447, step: 0.16666699945926666}, - * "exposureMode":["continuous","manual"], - * "facingMode":["environment"], - * "focusMode":["continuous","single-shot","manual"], - * "frameRate":{"max":30,"min":0}, - * "groupId":"71...a935", - * "height":{"max":2160,"min":1}, - * "resizeMode":["none","crop-and-scale"], - * "torch":true, - * "whiteBalanceMode":["continuous","manual"], - * "width":{"max":3840,"min":1}, - * "zoom":{max: 606, min: 100, step: 2} - * } - * ``` - * @category Camera Settings - */ - getCapabilities(): MediaTrackCapabilities; - /** @ignore */ - getCameraSettings(): MediaTrackSettings; - /** @ignore */ - getConstraints(): MediaTrackConstraints; - /** - * @ignore - * Set the camera capabilities. - * Only available when the scanner is open. - * It's a low-level API, usually you can use the wrapped APIs instead. - * ```js - * await scanner.applyConstraints({ frameRate: { ideal:5 } }); - * ``` - */ - applyConstraints(constraints: MediaTrackConstraints): Promise; - /** - * Turns on the torch/flashlight if the current camera supports it. This method should be called when the camera is turned on. - * - * Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. - * @returns A promise that resolves when the operation succeeds. - * @see {@link turnOffTorch} - * @see {@link getCapabilities} - * @category Camera Settings - */ - turnOnTorch(): Promise; - /** - * Turns off the torch/flashlight. - * - * Note: At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. - * @see {@link turnOnTorch} - * @category Camera Settings - */ - turnOffTorch(): Promise; - /** - * Adjusts the color temperature. - * - * Note: At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. - * @param value Specifies the new color temperature. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await scanner.setColorTemperature(5000); - * ``` - * @see {@link getColorTemperature} - * @see {@link getCapabilities} - * @category Camera Settings - */ - setColorTemperature(value: number): Promise; - /** - * Returns the color temperature of the selected camera. This method should be called when the camera is turned on. - * - * Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. - * @returns Color temperature of the selected camera. - * @see {@link setColorTemperature} - * @category Camera Settings - */ - getColorTemperature(): number; - /** - * Sets the exposure compensation index. - * - * Note: At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. - * @param value Specifies the new exposure compensation index. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await scanner.setExposureCompensation(-0.7); - * ``` - * @see {@link getExposureCompensation} - * @see {@link getCapabilities} - * @category Camera Settings - */ - setExposureCompensation(value: number): Promise; - /** - * Returns the exposure compensation index of the selected camera. This method should be called when the camera is turned on. - * - * Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported. - * @returns Exposure compensation index of the selected camera. - * @see {@link setExposureCompensation} - * @category Camera Settings - */ - getExposureCompensation(): number; - /** - * Sets current zoom value. - * - * At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. - * @param settings Specifies the new zoom value. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await scanner.setZoom(2); - * ``` - * @see {@link getZoomSettings} - * @see {@link resetZoom} - * @see {@link getCapabilities} - * @category Camera Settings - */ - setZoom(settings: number | { - factor: number; - centerPoint?: { - x: string; - y: string; - }; - }): Promise; - /** - * Returns the zoom settings. - * @returns An object that describes the zoom settings. As of version 3.2, it contains only the zoom factor. - * @see {@link setZoom} - * @category Camera Settings - */ - getZoomSettings(): { - factor: number; - }; - /** - * Resets the zoom level of the video. - * @returns A promise that resolves when the operation succeeds. - * @see {@link setZoom} - * @category Camera Settings - */ - resetZoom(): Promise; - /** - * Adjusts the frame rate. - * - * At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. - * @param value Specifies the new frame rate. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await scanner.setFrameRate(10); - * ``` - * @see {@link getFrameRate} - * @see {@link getCapabilities} - * @category Camera Settings - */ - setFrameRate(value: number): Promise; - /** - * Returns the real-time frame rate. - * @returns The calculated real-time frame rate. - * @see {@link setFrameRate} - * @category Camera Settings - */ - getFrameRate(): number; - /** - * Sets the focus mode and focus distance of the camera. - * - * At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open. - * @param settings Specifies the focus mode, the available values include `continuous` and `manual`. - * @param distance Specifies the focus distance, only required when the `mode` is set to `manual`. - * @returns A promise that resolves when the operation succeeds. - * @example - * ```js - * await scanner.setFocus("manual", 5); - * ``` - * @see {@link getFocusSettings} - * @see {@link getCapabilities} - * @category Camera Settings - */ - setFocus(settings: string | { - mode: string; - } | { - mode: "manual"; - distance: number; - } | { - mode: "manual"; - area: { - centerPoint: { - x: string; - y: string; - }; - width?: string; - height?: string; - }; - }, distance?: number): Promise; - /** - * @deprecated Use {@link getFocusSettings} instead. - */ - getFocus(): Object; - /** - * Returns the focus settings. - * @returns The current focus settings. - * @see {@link setFocus} - * @category Camera Settings - */ - getFocusSettings(): Object; - protected _loopReadVideo(): Promise; - /** - * start dce fetching frame loop, and get frame from frame queue - * @ignore - */ - protected _getVideoFrame(): DCEFrame; - /** - * Binds UI, turns on the camera and starts decoding. - * - * This method does not change the original state of the UI: if it doesn't exist in the DOM tree, nothing shows up on the page; if it exists in the DOM tree, it may or may not show up depending on its original state. - * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. - * @fires {@link onPlayed} - * @example - * ```js - * await scanner.setUIElement(document.getElementById("my-barcode-scanner")); - * scanner.onUniqueRead = (txt, result) => { alert(txt); console.log(result); }; - * await scanner.open(); - * // await scanner.close(); - * ``` - * @see {@link close} - * @see {@link hide} - * @see {@link ScannerPlayCallbackInfo} - * @category Open and Close - */ - open(): Promise; - /** - * Bind UI, open the camera, but not decode. - * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. - * @fires {@link onPlayed} - * @example - * ```js - * await scanner.setUIElement(document.getElementById("my-barcode-scanner")); - * await scanner.openVideo(); - * console.log(await scanner.decodeCurrentFrame()); - * // await scanner.close(); - * ``` - * @see {@link close} - * @see {@link hide} - * @see {@link ScannerPlayCallbackInfo} - * @category Open and Close - */ - openVideo(): Promise; - /** - * Stops decoding, releases camera, unbinds and hides UI. - * @example - * ```js - * await scanner.open(); - * await scanner.close(); - * ``` - * @example - * ```js - * await scanner.openVideo(); - * await scanner.close(); - * ``` - * @see {@link hide} - * @category Open and Close - */ - close(): void; - /** - * Binds and shows UI, opens the camera and starts decoding. - * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. - * @fires {@link onPlayed} - * @example - * ```js - * await scanner.setUIElement("https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode/dist/dbr.ui.html"); - * scanner.onUniqueRead = (txt, result) => { alert(txt); console.log(result); }; - * await scanner.show(); - * // await scanner.hide(); - * ``` - * @see {@link close} - * @see {@link hide} - * @see {@link ScannerPlayCallbackInfo} - * @category Open and Close - */ - show(): Promise; - /** - * Bind UI, open the camera, but not decode, and remove the UIElement `display` style if the original style is `display:none;`. - * @returns A promise resolving to a {@link ScannerPlayCallbackInfo} object. - * @fires {@link onPlayed} - * @example - * ```js - * await scanner.showVideo() - * console.log(await scanner.decodeCurrentFrame()); - * // await scanner.hide(); - * ``` - * @see {@link close} - * @see {@link hide} - * @see {@link ScannerPlayCallbackInfo} - * @category Open and Close - */ - showVideo(): Promise; - /** - * Stops decoding, releases camera and unbinds and hides UI. - * @example - * ```js - * await scanner.show(); - * await scanner.hidee(); - * ``` - * @example - * ```js - * await scanner.showVideo(); - * await scanner.hide(); - * ``` - * @see {@link close} - * @see {@link ScannerPlayCallbackInfo} - * @category Open and Close - */ - hide(): void; - /** - * Shows a Tip message. - * @param x Specifies the x coordinate of the Tip message. - * @param y Specifies the y coordinate of the Tip message. - * @param width Specifies the width of the Tip message, wrapping if the message is too long. - * @param initialMessage Optional. The initial message. - * @param duration Optional. The time during which a Tip message is displayed. The duration is reset each time the message is updated. Default value is `3000`. - * @param autoShowSuggestedTip Optional. Whether or not the Tip box is updated automatically when a tip is suggested. A tip is usually suggested by another SDK such as Dynamsoft Barcode Reader. - * @example - * ```js - * scanner.showTip(500, 200, 500, "The camera is too far away, please move closer!", 3000, true); - * ``` - * @see {@link hideTip} - */ - showTip(x: number, y: number, width: number, initialMessage?: string, duration?: number, autoShowSuggestedTip?: boolean): void; - /** - * Hides the Tip message. - * @see {@link showTip} - */ - hideTip(): void; - /** - * Changes the Tip message. - * @param message Specifies a new message as the Tip. - */ - updateTipMessage(message: string): void; - /** - * Enables manual camera focus when clicking/tapping on the video. - * - * At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). - * @see {@link disableTapToFocus} - * @see {@link isTapToFocusEnabled} - */ - enableTapToFocus(): Promise; - /** - * Disables manual camera focus when clicking/tapping on the video. - * @see {@link enableTapToFocus} - * @see {@link isTapToFocusEnabled} - */ - disableTapToFocus(): void; - /** - * Returns whether clicking/tapping on the video invokes the camera to focus. - * @returns `true` means clicking/tapping on the video will invoke the camera to focus. `false` means clicking/tapping on the video does nothing. - * @see {@link enableTapToFocus} - * @see {@link disableTapToFocus} - */ - isTapToFocusEnabled(): boolean; - /** - * Converts coordinates of a barcode location to the coordinates relative to the top left point of the entire document. - * - * Note: Call this method only after `scanner` is open. - * @param point The coordinates to convert. - * @returns The converted coordinates. - * @see {@link convertToClientCoordinates} - */ - convertToPageCoordinates(point: { - x: number; - y: number; - }): { - x: number; - y: number; - }; - /** - * Converts coordinates of a barcode location to the coordinates within the application's viewport at which the event occurred (as opposed to the coordinate within the page). - * - * Note: Call this method only after `scanner` is open. - * @param point The coordinates to convert. - * @returns The converted coordinates. - * @see {@link convertToClientCoordinates} - */ - convertToClientCoordinates(point: { - x: number; - y: number; - }): { - x: number; - y: number; - }; - /** - * Destroys the `BarcodeScanner` instance. If your page needs to create a new instance from time to time, don't forget to destroy unused old instances. - * @see {@link isContextDestroyed} - * @category Initialize and Destroy - */ - destroyContext(): void; -} -//# sourceMappingURL=barcodescanner.d.ts.map \ No newline at end of file diff --git a/dist/types/dbr.d.ts b/dist/types/dbr.d.ts deleted file mode 100644 index 1b6b735..0000000 --- a/dist/types/dbr.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -import BarcodeReader from "./class/barcodereader"; -import BarcodeScanner from "./class/barcodescanner"; -import { EnumBarcodeColourMode } from "./enum/enumbarcodecolourmode"; -import { EnumBarcodeComplementMode } from "./enum/enumbarcodecomplementmode"; -import { EnumBarcodeFormat } from "./enum/enumbarcodeformat"; -import { EnumBarcodeFormat_2 } from "./enum/enumbarcodeformat_2"; -import { EnumBinarizationMode } from "./enum/enumbinarizationmode"; -import { EnumClarityCalculationMethod } from "./enum/enumclaritycalculationmethod"; -import { EnumClarityFilterMode } from "./enum/enumclarityfiltermode"; -import { EnumColourClusteringMode } from "./enum/enumcolourclusteringmode"; -import { EnumColourConversionMode } from "./enum/enumcolourconversionmode"; -import { EnumConflictMode } from "./enum/enumconflictmode"; -import { EnumDeblurMode } from "./enum/enumdeblurmode"; -import { EnumDeformationResistingMode } from "./enum/enumdeformationresistingmode"; -import { EnumDPMCodeReadingMode } from "./enum/enumdpmcodereadingmode"; -import { EnumErrorCode } from "./enum/enumerrorcode"; -import { EnumGrayscaleTransformationMode } from "./enum/enumgrayscaletransformationmode"; -import { EnumImagePixelFormat } from "./enum/enumimagepixelformat"; -import { EnumImagePreprocessingMode } from "./enum/enumimagepreprocessingmode"; -import { EnumIMResultDataType } from "./enum/enumimresultdatatype"; -import { EnumIntermediateResultSavingMode } from "./enum/enumintermediateresultsavingmode"; -import { EnumIntermediateResultType } from "./enum/enumintermediateresulttype"; -import { EnumLocalizationMode } from "./enum/enumlocalizationmode"; -import { EnumPDFReadingMode } from "./enum/enumpdfreadingmode"; -import { EnumQRCodeErrorCorrectionLevel } from "./enum/enumqrcodeerrorcorrectionlevel"; -import { EnumRegionPredetectionMode } from "./enum/enumregionpredetectionmode"; -import { EnumResultCoordinateType } from "./enum/enumresultcoordinatetype"; -import { EnumResultType } from "./enum/enumresulttype"; -import { EnumScaleUpMode } from "./enum/enumscaleupmode"; -import { EnumTerminatePhase } from "./enum/enumterminatephase"; -import { EnumTextFilterMode } from "./enum/enumtextfiltermode"; -import { EnumTextResultOrderMode } from "./enum/enumtextresultordermode"; -import { EnumTextureDetectionMode } from "./enum/enumtexturedetectionmode"; -import { TextResult } from "./interface/textresult"; -import { RuntimeSettings } from "./interface/runtimesettings"; -import { ScanSettings } from "./interface/scanSettings"; -import { Region } from "./interface/region"; -import { ImageSource } from "./interface/imagesource"; -import { DSImage } from "./interface/dsimage"; -export { BarcodeReader, BarcodeScanner, EnumBarcodeColourMode, EnumBarcodeComplementMode, EnumBarcodeFormat, EnumBarcodeFormat_2, EnumBinarizationMode, EnumClarityCalculationMethod, EnumClarityFilterMode, EnumColourClusteringMode, EnumColourConversionMode, EnumConflictMode, EnumDeblurMode, EnumDeformationResistingMode, EnumDPMCodeReadingMode, EnumErrorCode, EnumGrayscaleTransformationMode, EnumImagePixelFormat, EnumImagePreprocessingMode, EnumIMResultDataType, EnumIntermediateResultSavingMode, EnumIntermediateResultType, EnumLocalizationMode, EnumPDFReadingMode, EnumQRCodeErrorCorrectionLevel, EnumRegionPredetectionMode, EnumResultCoordinateType, EnumResultType, EnumScaleUpMode, EnumTerminatePhase, EnumTextFilterMode, EnumTextResultOrderMode, EnumTextureDetectionMode, TextResult, RuntimeSettings, ScanSettings, Region, ImageSource, DSImage }; -//# sourceMappingURL=dbr.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/common.d.ts b/dist/types/enum/common.d.ts deleted file mode 100644 index 1d64df0..0000000 --- a/dist/types/enum/common.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -export declare enum EnumLicenseModule { - /**One-D barcodes license module*/ - DM_LM_ONED = "1", - /**QR Code barcodes license module*/ - DM_LM_QR_CODE = "2", - /**PDF417 barcodes license module*/ - DM_LM_PDF417 = "3", - /**Datamatrix barcodes license module*/ - DM_LM_DATAMATRIX = "4", - /**Aztec barcodes license module*/ - DM_LM_AZTEC = "5", - /**MAXICODE barcodes license module*/ - DM_LM_MAXICODE = "6", - /**Patch code barcodes license module*/ - DM_LM_PATCHCODE = "7", - /**GS1 Databar barcodes license module*/ - DM_LM_GS1_DATABAR = "8", - /**GS1 Composite barcodes license module*/ - DM_LM_GS1_COMPOSITE = "9", - /**Postal code barcodes license module*/ - DM_LM_POSTALCODE = "10", - /**DotCode barcodes license module*/ - DM_LM_DOTCODE = "11", - /**Intermediate result license module*/ - DM_LM_INTERMEDIATE_RESULT = "12", - /**Datamatrix DPM(Direct Part Marking) license module*/ - DM_LM_DPM = "13", - /**Nonstandard barcodes license module*/ - DM_LM_NONSTANDARD_BARCODE = "16" -} -export declare enum EnumChargeWay { - /**The charge way automatically determined by the license server.*/ - DM_CW_AUTO = "", - /**Charges by the count of devices.*/ - DM_CW_DEVICE_COUNT = "DeviceCount", - /**Charges by the count of barcode scans.*/ - DM_CW_SCAN_COUNT = "ScanCount", - /**Charges by the count of concurrent devices.*/ - DM_CW_CONCURRENT_DEVICE_COUNT = "ConcurrentDeviceCount", - /**Charges by the count of app domains.*/ - DM_CW_APP_DOMIAN_COUNT = "Domain", - /**Charges by the count of active devices.*/ - DM_CW_ACTIVE_DEVICE_COUNT = "ActiveDeviceCount", - /**Charges by the count of instances.*/ - DM_CW_INSTANCE_COUNT = "InstanceCount", - /**Charges by the count of concurrent instances.*/ - DM_CW_CONCURRENT_INSTANCE_COUNT = "ConcurrentInstanceCount" -} -//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumbarcodecolourmode.d.ts b/dist/types/enum/enumbarcodecolourmode.d.ts deleted file mode 100644 index 9bc1f94..0000000 --- a/dist/types/enum/enumbarcodecolourmode.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -export declare enum EnumBarcodeColourMode { - BICM_DARK_ON_LIGHT = 1, - BICM_LIGHT_ON_DARK = 2, - BICM_DARK_ON_DARK = 4, - BICM_LIGHT_ON_LIGHT = 8, - BICM_DARK_LIGHT_MIXED = 16, - BICM_DARK_ON_LIGHT_DARK_SURROUNDING = 32, - BICM_SKIP = 0, - BICM_REV = 2147483648 -} -//# sourceMappingURL=enumbarcodecolourmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumbarcodecomplementmode.d.ts b/dist/types/enum/enumbarcodecomplementmode.d.ts deleted file mode 100644 index 8a21cf7..0000000 --- a/dist/types/enum/enumbarcodecomplementmode.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum EnumBarcodeComplementMode { - BCM_AUTO = 1, - BCM_GENERAL = 2, - BCM_SKIP = 0, - BCM_REV = 2147483648 -} -//# sourceMappingURL=enumbarcodecomplementmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumbarcodeformat.d.ts b/dist/types/enum/enumbarcodeformat.d.ts deleted file mode 100644 index 9a364c5..0000000 --- a/dist/types/enum/enumbarcodeformat.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -export declare enum EnumBarcodeFormat { - BF_ALL = -29360129, - BF_ONED = 3147775, - BF_GS1_DATABAR = 260096, - BF_CODE_39 = 1, - BF_CODE_128 = 2, - BF_CODE_93 = 4, - BF_CODABAR = 8, - BF_ITF = 16, - BF_EAN_13 = 32, - BF_EAN_8 = 64, - BF_UPC_A = 128, - BF_UPC_E = 256, - BF_INDUSTRIAL_25 = 512, - BF_CODE_39_EXTENDED = 1024, - BF_GS1_DATABAR_OMNIDIRECTIONAL = 2048, - BF_GS1_DATABAR_TRUNCATED = 4096, - BF_GS1_DATABAR_STACKED = 8192, - BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL = 16384, - BF_GS1_DATABAR_EXPANDED = 32768, - BF_GS1_DATABAR_EXPANDED_STACKED = 65536, - BF_GS1_DATABAR_LIMITED = 131072, - BF_PATCHCODE = 262144, - BF_PDF417 = 33554432, - BF_QR_CODE = 67108864, - BF_DATAMATRIX = 134217728, - BF_AZTEC = 268435456, - BF_MAXICODE = 536870912, - BF_MICRO_QR = 1073741824, - BF_MICRO_PDF417 = 524288, - BF_GS1_COMPOSITE = -2147483648, - BF_MSI_CODE = 1048576, - BF_CODE_11 = 2097152, - BF_NULL = 0 -} -//# sourceMappingURL=enumbarcodeformat.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumbarcodeformat_2.d.ts b/dist/types/enum/enumbarcodeformat_2.d.ts deleted file mode 100644 index 9abf14c..0000000 --- a/dist/types/enum/enumbarcodeformat_2.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -export declare enum EnumBarcodeFormat_2 { - BF2_NULL = 0, - BF2_POSTALCODE = 32505856, - BF2_NONSTANDARD_BARCODE = 1, - BF2_USPSINTELLIGENTMAIL = 1048576, - BF2_POSTNET = 2097152, - BF2_PLANET = 4194304, - BF2_AUSTRALIANPOST = 8388608, - BF2_RM4SCC = 16777216, - BF2_DOTCODE = 2, - BF2_PHARMACODE_ONE_TRACK = 4, - BF2_PHARMACODE_TWO_TRACK = 8, - BF2_PHARMACODE = 12, - BF2_ALL = -1 -} -//# sourceMappingURL=enumbarcodeformat_2.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumbinarizationmode.d.ts b/dist/types/enum/enumbinarizationmode.d.ts deleted file mode 100644 index bfa54bc..0000000 --- a/dist/types/enum/enumbinarizationmode.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export declare enum EnumBinarizationMode { - BM_AUTO = 1, - BM_LOCAL_BLOCK = 2, - BM_SKIP = 0, - BM_THRESHOLD = 4, - BM_REV = 2147483648 -} -//# sourceMappingURL=enumbinarizationmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumclaritycalculationmethod.d.ts b/dist/types/enum/enumclaritycalculationmethod.d.ts deleted file mode 100644 index 02f7afd..0000000 --- a/dist/types/enum/enumclaritycalculationmethod.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare enum EnumClarityCalculationMethod { - ECCM_CONTRAST = 1 -} -//# sourceMappingURL=enumclaritycalculationmethod.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumclarityfiltermode.d.ts b/dist/types/enum/enumclarityfiltermode.d.ts deleted file mode 100644 index 21d6193..0000000 --- a/dist/types/enum/enumclarityfiltermode.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare enum EnumClarityFilterMode { - CFM_GENERAL = 1 -} -//# sourceMappingURL=enumclarityfiltermode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumcolourclusteringmode.d.ts b/dist/types/enum/enumcolourclusteringmode.d.ts deleted file mode 100644 index a787ebd..0000000 --- a/dist/types/enum/enumcolourclusteringmode.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum EnumColourClusteringMode { - CCM_AUTO = 1, - CCM_GENERAL_HSV = 2, - CCM_SKIP = 0, - CCM_REV = 2147483648 -} -//# sourceMappingURL=enumcolourclusteringmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumcolourconversionmode.d.ts b/dist/types/enum/enumcolourconversionmode.d.ts deleted file mode 100644 index 6cc6b7d..0000000 --- a/dist/types/enum/enumcolourconversionmode.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export declare enum EnumColourConversionMode { - CICM_GENERAL = 1, - CICM_SKIP = 0, - CICM_REV = 2147483648 -} -//# sourceMappingURL=enumcolourconversionmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumconflictmode.d.ts b/dist/types/enum/enumconflictmode.d.ts deleted file mode 100644 index 08d53d1..0000000 --- a/dist/types/enum/enumconflictmode.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export declare enum EnumConflictMode { - CM_IGNORE = 1, - CM_OVERWRITE = 2 -} -//# sourceMappingURL=enumconflictmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumdeblurmode.d.ts b/dist/types/enum/enumdeblurmode.d.ts deleted file mode 100644 index 48b8e5c..0000000 --- a/dist/types/enum/enumdeblurmode.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -export declare enum EnumDeblurMode { - DM_SKIP = 0, - DM_DIRECT_BINARIZATION = 1, - DM_THRESHOLD_BINARIZATION = 2, - DM_GRAY_EQUALIZATION = 4, - DM_SMOOTHING = 8, - DM_MORPHING = 16, - DM_DEEP_ANALYSIS = 32, - DM_SHARPENING = 64, - DM_BASED_ON_LOC_BIN = 128, - DM_SHARPENING_SMOOTHING = 256 -} -//# sourceMappingURL=enumdeblurmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumdeformationresistingmode.d.ts b/dist/types/enum/enumdeformationresistingmode.d.ts deleted file mode 100644 index 54188d4..0000000 --- a/dist/types/enum/enumdeformationresistingmode.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -export declare enum EnumDeformationResistingMode { - DRM_AUTO = 1, - DRM_GENERAL = 2, - DRM_BROAD_WARP = 4, - DRM_LOCAL_REFERENCE = 8, - DRM_DEWRINKLE = 16, - DRM_SKIP = 0, - DRM_REV = 2147483648 -} -//# sourceMappingURL=enumdeformationresistingmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumdpmcodereadingmode.d.ts b/dist/types/enum/enumdpmcodereadingmode.d.ts deleted file mode 100644 index caa77c0..0000000 --- a/dist/types/enum/enumdpmcodereadingmode.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum EnumDPMCodeReadingMode { - DPMCRM_AUTO = 1, - DPMCRM_GENERAL = 2, - DPMCRM_SKIP = 0, - DPMCRM_REV = 2147483648 -} -//# sourceMappingURL=enumdpmcodereadingmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumerrorcode.d.ts b/dist/types/enum/enumerrorcode.d.ts deleted file mode 100644 index 15e0cf6..0000000 --- a/dist/types/enum/enumerrorcode.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -export declare enum EnumErrorCode { - DBR_SYSTEM_EXCEPTION = 1, - DBR_SUCCESS = 0, - DBR_UNKNOWN = -10000, - DBR_NO_MEMORY = -10001, - DBR_NULL_REFERENCE = -10002, - DBR_LICENSE_INVALID = -10003, - DBR_LICENSE_EXPIRED = -10004, - DBR_FILE_NOT_FOUND = -10005, - DBR_FILETYPE_NOT_SUPPORTED = -10006, - DBR_BPP_NOT_SUPPORTED = -10007, - DBR_INDEX_INVALID = -10008, - DBR_BARCODE_FORMAT_INVALID = -10009, - DBR_CUSTOM_REGION_INVALID = -10010, - DBR_MAX_BARCODE_NUMBER_INVALID = -10011, - DBR_IMAGE_READ_FAILED = -10012, - DBR_TIFF_READ_FAILED = -10013, - DBR_QR_LICENSE_INVALID = -10016, - DBR_1D_LICENSE_INVALID = -10017, - DBR_DIB_BUFFER_INVALID = -10018, - DBR_PDF417_LICENSE_INVALID = -10019, - DBR_DATAMATRIX_LICENSE_INVALID = -10020, - DBR_PDF_READ_FAILED = -10021, - DBR_PDF_DLL_MISSING = -10022, - DBR_PAGE_NUMBER_INVALID = -10023, - DBR_CUSTOM_SIZE_INVALID = -10024, - DBR_CUSTOM_MODULESIZE_INVALID = -10025, - DBR_RECOGNITION_TIMEOUT = -10026, - DBR_JSON_PARSE_FAILED = -10030, - DBR_JSON_TYPE_INVALID = -10031, - DBR_JSON_KEY_INVALID = -10032, - DBR_JSON_VALUE_INVALID = -10033, - DBR_JSON_NAME_KEY_MISSING = -10034, - DBR_JSON_NAME_VALUE_DUPLICATED = -10035, - DBR_TEMPLATE_NAME_INVALID = -10036, - DBR_JSON_NAME_REFERENCE_INVALID = -10037, - DBR_PARAMETER_VALUE_INVALID = -10038, - DBR_DOMAIN_NOT_MATCHED = -10039, - DBR_RESERVEDINFO_NOT_MATCHED = -10040, - DBR_AZTEC_LICENSE_INVALID = -10041, - DBR_LICENSE_DLL_MISSING = -10042, - DBR_LICENSEKEY_NOT_MATCHED = -10043, - DBR_REQUESTED_FAILED = -10044, - DBR_LICENSE_INIT_FAILED = -10045, - DBR_PATCHCODE_LICENSE_INVALID = -10046, - DBR_POSTALCODE_LICENSE_INVALID = -10047, - DBR_DPM_LICENSE_INVALID = -10048, - DBR_FRAME_DECODING_THREAD_EXISTS = -10049, - DBR_STOP_DECODING_THREAD_FAILED = -10050, - DBR_SET_MODE_ARGUMENT_ERROR = -10051, - DBR_LICENSE_CONTENT_INVALID = -10052, - DBR_LICENSE_KEY_INVALID = -10053, - DBR_LICENSE_DEVICE_RUNS_OUT = -10054, - DBR_GET_MODE_ARGUMENT_ERROR = -10055, - DBR_IRT_LICENSE_INVALID = -10056, - DBR_MAXICODE_LICENSE_INVALID = -10057, - DBR_GS1_DATABAR_LICENSE_INVALID = -10058, - DBR_GS1_COMPOSITE_LICENSE_INVALID = -10059, - DBR_PANORAMA_LICENSE_INVALID = -10060, - DBR_DOTCODE_LICENSE_INVALID = -10061, - DBR_PHARMACODE_LICENSE_INVALID = -10062, - DBR_IMAGE_ORIENTATION_INVALID = -10063, - DMERR_NO_LICENSE = -20000, - DMERR_LICENSE_SYNC_FAILED = -20003, - DMERR_TRIAL_LICENSE = -20010, - DMERR_FAILED_TO_REACH_LTS = -20200 -} -//# sourceMappingURL=enumerrorcode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumgrayscaletransformationmode.d.ts b/dist/types/enum/enumgrayscaletransformationmode.d.ts deleted file mode 100644 index 34df120..0000000 --- a/dist/types/enum/enumgrayscaletransformationmode.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum EnumGrayscaleTransformationMode { - GTM_INVERTED = 1, - GTM_ORIGINAL = 2, - GTM_SKIP = 0, - GTM_REV = 2147483648 -} -//# sourceMappingURL=enumgrayscaletransformationmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumimagepixelformat.d.ts b/dist/types/enum/enumimagepixelformat.d.ts deleted file mode 100644 index 4b9826d..0000000 --- a/dist/types/enum/enumimagepixelformat.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -export declare enum EnumImagePixelFormat { - IPF_Binary = 0, - IPF_BinaryInverted = 1, - IPF_GrayScaled = 2, - IPF_NV21 = 3, - IPF_RGB_565 = 4, - IPF_RGB_555 = 5, - IPF_RGB_888 = 6, - IPF_ARGB_8888 = 7, - IPF_RGB_161616 = 8, - IPF_ARGB_16161616 = 9, - IPF_ABGR_8888 = 10, - IPF_ABGR_16161616 = 11, - IPF_BGR_888 = 12 -} -//# sourceMappingURL=enumimagepixelformat.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumimagepreprocessingmode.d.ts b/dist/types/enum/enumimagepreprocessingmode.d.ts deleted file mode 100644 index c20c5cf..0000000 --- a/dist/types/enum/enumimagepreprocessingmode.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -export declare enum EnumImagePreprocessingMode { - IPM_AUTO = 1, - IPM_GENERAL = 2, - IPM_GRAY_EQUALIZE = 4, - IPM_GRAY_SMOOTH = 8, - IPM_SHARPEN_SMOOTH = 16, - IPM_MORPHOLOGY = 32, - IPM_SKIP = 0, - IPM_REV = 2147483648 -} -//# sourceMappingURL=enumimagepreprocessingmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumimresultdatatype.d.ts b/dist/types/enum/enumimresultdatatype.d.ts deleted file mode 100644 index 1522fae..0000000 --- a/dist/types/enum/enumimresultdatatype.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -export declare enum EnumIMResultDataType { - IMRDT_IMAGE = 1, - IMRDT_CONTOUR = 2, - IMRDT_LINESEGMENT = 4, - IMRDT_LOCALIZATIONRESULT = 8, - IMRDT_REGIONOFINTEREST = 16, - IMRDT_QUADRILATERAL = 32 -} -//# sourceMappingURL=enumimresultdatatype.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumintermediateresultsavingmode.d.ts b/dist/types/enum/enumintermediateresultsavingmode.d.ts deleted file mode 100644 index a494b5e..0000000 --- a/dist/types/enum/enumintermediateresultsavingmode.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export declare enum EnumIntermediateResultSavingMode { - IRSM_MEMORY = 1, - IRSM_FILESYSTEM = 2, - IRSM_BOTH = 4 -} -//# sourceMappingURL=enumintermediateresultsavingmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumintermediateresulttype.d.ts b/dist/types/enum/enumintermediateresulttype.d.ts deleted file mode 100644 index 407e8ba..0000000 --- a/dist/types/enum/enumintermediateresulttype.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -export declare enum EnumIntermediateResultType { - IRT_NO_RESULT = 0, - IRT_ORIGINAL_IMAGE = 1, - IRT_COLOUR_CLUSTERED_IMAGE = 2, - IRT_COLOUR_CONVERTED_GRAYSCALE_IMAGE = 4, - IRT_TRANSFORMED_GRAYSCALE_IMAGE = 8, - IRT_PREDETECTED_REGION = 16, - IRT_PREPROCESSED_IMAGE = 32, - IRT_BINARIZED_IMAGE = 64, - IRT_TEXT_ZONE = 128, - IRT_CONTOUR = 256, - IRT_LINE_SEGMENT = 512, - IRT_FORM = 1024, - IRT_SEGMENTATION_BLOCK = 2048, - IRT_TYPED_BARCODE_ZONE = 4096, - IRT_PREDETECTED_QUADRILATERAL = 8192 -} -//# sourceMappingURL=enumintermediateresulttype.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumlocalizationmode.d.ts b/dist/types/enum/enumlocalizationmode.d.ts deleted file mode 100644 index df7fbac..0000000 --- a/dist/types/enum/enumlocalizationmode.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -export declare enum EnumLocalizationMode { - LM_SKIP = 0, - LM_AUTO = 1, - LM_CONNECTED_BLOCKS = 2, - LM_LINES = 8, - LM_STATISTICS = 4, - LM_SCAN_DIRECTLY = 16, - LM_STATISTICS_MARKS = 32, - LM_STATISTICS_POSTAL_CODE = 64, - LM_CENTRE = 128, - LM_ONED_FAST_SCAN = 256, - LM_REV = 2147483648 -} -//# sourceMappingURL=enumlocalizationmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumpdfreadingmode.d.ts b/dist/types/enum/enumpdfreadingmode.d.ts deleted file mode 100644 index da2d8ae..0000000 --- a/dist/types/enum/enumpdfreadingmode.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum EnumPDFReadingMode { - PDFRM_RASTER = 1, - PDFRM_AUTO = 2, - PDFRM_VECTOR = 4, - PDFRM_REV = 2147483648 -} -//# sourceMappingURL=enumpdfreadingmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumqrcodeerrorcorrectionlevel.d.ts b/dist/types/enum/enumqrcodeerrorcorrectionlevel.d.ts deleted file mode 100644 index 20de9e2..0000000 --- a/dist/types/enum/enumqrcodeerrorcorrectionlevel.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum EnumQRCodeErrorCorrectionLevel { - QRECL_ERROR_CORRECTION_H = 0, - QRECL_ERROR_CORRECTION_L = 1, - QRECL_ERROR_CORRECTION_M = 2, - QRECL_ERROR_CORRECTION_Q = 3 -} -//# sourceMappingURL=enumqrcodeerrorcorrectionlevel.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumregionpredetectionmode.d.ts b/dist/types/enum/enumregionpredetectionmode.d.ts deleted file mode 100644 index 5b05c7c..0000000 --- a/dist/types/enum/enumregionpredetectionmode.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -export declare enum EnumRegionPredetectionMode { - RPM_AUTO = 1, - RPM_GENERAL = 2, - RPM_GENERAL_RGB_CONTRAST = 4, - RPM_GENERAL_GRAY_CONTRAST = 8, - RPM_GENERAL_HSV_CONTRAST = 16, - RPM_SKIP = 0, - RPM_REV = 2147483648 -} -//# sourceMappingURL=enumregionpredetectionmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumresultcoordinatetype.d.ts b/dist/types/enum/enumresultcoordinatetype.d.ts deleted file mode 100644 index d67836e..0000000 --- a/dist/types/enum/enumresultcoordinatetype.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export declare enum EnumResultCoordinateType { - RCT_PIXEL = 1, - RCT_PERCENTAGE = 2 -} -//# sourceMappingURL=enumresultcoordinatetype.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumresulttype.d.ts b/dist/types/enum/enumresulttype.d.ts deleted file mode 100644 index 49dd481..0000000 --- a/dist/types/enum/enumresulttype.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum EnumResultType { - RT_STANDARD_TEXT = 0, - RT_RAW_TEXT = 1, - RT_CANDIDATE_TEXT = 2, - RT_PARTIAL_TEXT = 3 -} -//# sourceMappingURL=enumresulttype.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumscaleupmode.d.ts b/dist/types/enum/enumscaleupmode.d.ts deleted file mode 100644 index b614371..0000000 --- a/dist/types/enum/enumscaleupmode.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export declare enum EnumScaleUpMode { - SUM_AUTO = 1, - SUM_LINEAR_INTERPOLATION = 2, - SUM_NEAREST_NEIGHBOUR_INTERPOLATION = 4, - SUM_SKIP = 0, - SUM_REV = 2147483648 -} -//# sourceMappingURL=enumscaleupmode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumterminatephase.d.ts b/dist/types/enum/enumterminatephase.d.ts deleted file mode 100644 index b6c338b..0000000 --- a/dist/types/enum/enumterminatephase.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -export declare enum EnumTerminatePhase { - TP_REGION_PREDETECTED = 1, - TP_IMAGE_PREPROCESSED = 2, - TP_IMAGE_BINARIZED = 4, - TP_BARCODE_LOCALIZED = 8, - TP_BARCODE_TYPE_DETERMINED = 16, - TP_BARCODE_RECOGNIZED = 32 -} -//# sourceMappingURL=enumterminatephase.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumtextfiltermode.d.ts b/dist/types/enum/enumtextfiltermode.d.ts deleted file mode 100644 index 4cacf1a..0000000 --- a/dist/types/enum/enumtextfiltermode.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum EnumTextFilterMode { - TFM_AUTO = 1, - TFM_GENERAL_CONTOUR = 2, - TFM_SKIP = 0, - TFM_REV = 2147483648 -} -//# sourceMappingURL=enumtextfiltermode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumtextresultordermode.d.ts b/dist/types/enum/enumtextresultordermode.d.ts deleted file mode 100644 index 0f35eb5..0000000 --- a/dist/types/enum/enumtextresultordermode.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export declare enum EnumTextResultOrderMode { - TROM_CONFIDENCE = 1, - TROM_POSITION = 2, - TROM_FORMAT = 4, - TROM_SKIP = 0, - TROM_REV = 2147483648 -} -//# sourceMappingURL=enumtextresultordermode.d.ts.map \ No newline at end of file diff --git a/dist/types/enum/enumtexturedetectionmode.d.ts b/dist/types/enum/enumtexturedetectionmode.d.ts deleted file mode 100644 index 941aaac..0000000 --- a/dist/types/enum/enumtexturedetectionmode.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum EnumTextureDetectionMode { - TDM_AUTO = 1, - TDM_GENERAL_WIDTH_CONCENTRATION = 2, - TDM_SKIP = 0, - TDM_REV = 2147483648 -} -//# sourceMappingURL=enumtexturedetectionmode.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/barcodereaderexception.d.ts b/dist/types/interface/barcodereaderexception.d.ts deleted file mode 100644 index 92d2452..0000000 --- a/dist/types/interface/barcodereaderexception.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { EnumErrorCode } from "../enum/enumerrorcode"; -export interface BarcodeReaderException extends Error { - code?: EnumErrorCode; -} -//# sourceMappingURL=barcodereaderexception.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/dsimage.d.ts b/dist/types/interface/dsimage.d.ts deleted file mode 100644 index 1947a46..0000000 --- a/dist/types/interface/dsimage.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export interface DSImage { - data: Uint8Array; - width: number; - height: number; - pixelFormat: string; -} -//# sourceMappingURL=dsimage.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/imagesource.d.ts b/dist/types/interface/imagesource.d.ts deleted file mode 100644 index 210644b..0000000 --- a/dist/types/interface/imagesource.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { DSImage } from "./dsimage"; -export interface ImageSource { - getImage(): Promise | DSImage; -} -//# sourceMappingURL=imagesource.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/localizationresult.d.ts b/dist/types/interface/localizationresult.d.ts deleted file mode 100644 index 1a8322a..0000000 --- a/dist/types/interface/localizationresult.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { EnumResultCoordinateType } from "../enum/enumresultcoordinatetype"; -export interface LocalizationResult { - /** - * The angle of a barcode. Values range from 0 to 360. - */ - angle: number; - /** - * The X coordinate of the left-most point. - */ - x1: number; - /** - * The X coordinate of the second point in a clockwise direction. - */ - x2: number; - /** - * The X coordinate of the third point in a clockwise direction. - */ - x3: number; - /** - * The X coordinate of the fourth point in a clockwise direction. - */ - x4: number; - /** - * The Y coordinate of the left-most point. - */ - y1: number; - /** - * The Y coordinate of the second point in a clockwise direction. - */ - y2: number; - /** - * The Y coordinate of the third point in a clockwise direction. - */ - y3: number; - /** - * The Y coordinate of the fourth point in a clockwise direction. - */ - y4: number; - resultCoordinateType: EnumResultCoordinateType; - transformationMatrix: Array; -} -//# sourceMappingURL=localizationresult.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/region.d.ts b/dist/types/interface/region.d.ts deleted file mode 100644 index c925151..0000000 --- a/dist/types/interface/region.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export interface Region { - regionBottom: number; - regionRight: number; - regionLeft: number; - regionTop: number; - regionMeasuredByPercentage: number | boolean; -} -//# sourceMappingURL=region.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/runtimesettings.d.ts b/dist/types/interface/runtimesettings.d.ts deleted file mode 100644 index 13eb4e9..0000000 --- a/dist/types/interface/runtimesettings.d.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { Region } from "./region"; -import { EnumIntermediateResultType } from "../enum/enumintermediateresulttype"; -import { EnumTerminatePhase } from "../enum/enumterminatephase"; -import { EnumTextResultOrderMode } from "../enum/enumtextresultordermode"; -import { EnumBinarizationMode } from "../enum/enumbinarizationmode"; -import { EnumPDFReadingMode } from "../enum/enumpdfreadingmode"; -import { EnumScaleUpMode } from "../enum/enumscaleupmode"; -import { EnumLocalizationMode } from "../enum/enumlocalizationmode"; -import { EnumBarcodeFormat } from "../enum/enumbarcodeformat"; -import { EnumBarcodeFormat_2 } from "../enum/enumbarcodeformat_2"; -import { EnumResultCoordinateType } from "../enum/enumresultcoordinatetype"; -/** - * @see [C++ RuntimeSettings](https://www.dynamsoft.com/barcode-reader/programming/c-cplusplus/struct/PublicRuntimeSettings.html?src=cpp&&ver=latest) - */ -export interface RuntimeSettings { - /** - * Sets the formats of the barcode in BarcodeFormat group 1 to be read. Barcode formats in BarcodeFormat group 1 can be combined. - * ```js - * let runtimeSettings = await reader.getRuntimeSettings(); - * runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; - * await reader.updateRuntimeSettings(runtimeSettings); - * ``` - */ - barcodeFormatIds: number | EnumBarcodeFormat; - /** - * Sets the formats of the barcode in BarcodeFormat group 2 to be read. Barcode formats in BarcodeFormat group 1 can be combined. - */ - barcodeFormatIds_2: number | EnumBarcodeFormat_2; - /** - * Sets the mode and priority for binarization. - */ - binarizationModes: EnumBinarizationMode[]; - /** - * Sets the degree of blurriness of the barcode. - */ - deblurLevel: number; - /** - * Sets the number of barcodes expected to be detected for each image. - */ - expectedBarcodesCount: number; - /** - * Sets the further modes. - */ - furtherModes: any; - /** - * Sets which types of intermediate result to be kept for further reference. Intermediate result types can be combined. - */ - intermediateResultTypes: EnumIntermediateResultType; - /** - * Sets the mode and priority for localization algorithms. - */ - localizationModes: number[] | EnumLocalizationMode[]; - /** - * Sets the range of barcode text length for barcodes search - */ - minBarcodeTextLength: number; - /** - * The minimum confidence of the result - */ - minResultConfidence: number; - /** - * Not available in JS. Sets the way to detect barcodes from a PDF file when using the DecodeFile method. - */ - PDFReadingMode: EnumPDFReadingMode; - /** - * Sets the region definition including the regionTop, regionLeft, regionRight, regionBottom and regionMeasuredByPercentage. - * - * Experimental feature: - * - * In [BarcodeScanner](../BarcodeScanner.md), `region` can be an array. For example `region = [r0, r1, r2]`, 0th frame use `r0`, 1st use `r1`, 2nd use `r2`, 3rd use `r0`, and then loop like this. - */ - region: Region; - /** - * Specifies the format for the coordinates returned - */ - resultCoordinateType: number | EnumResultCoordinateType; - /** - * Sets whether or not to return the clarity of the barcode zone. - */ - returnBarcodeZoneClarity: number; - /** - * Sets the threshold for the image shrinking - */ - scaleDownThreshold: number; - /** - * Sets the mode and priority to control the sampling methods of scale-up for linear barcode with small module sizes. - */ - scaleUpModes: EnumScaleUpMode[]; - /** - * Sets the phase where the algorithm stops. - */ - terminatePhase: EnumTerminatePhase; - /** - * Sets the mode and priority for the order of the text results returned. - */ - textResultOrderModes: EnumTextResultOrderMode[]; - /** - * Sets the maximum amount of time (in milliseconds) that should be spent searching for a barcode per page. - * It does not include the time taken to load/decode an image (Tiff, PNG, etc) from disk into memory. - */ - timeout: number; -} -//# sourceMappingURL=runtimesettings.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/scanSettings.d.ts b/dist/types/interface/scanSettings.d.ts deleted file mode 100644 index 9b885bc..0000000 --- a/dist/types/interface/scanSettings.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * let scanSettings = await scanner.getScanSettings(); - * scanSettings.intervalTime = 100; // 100ms - * scanSettings.duplicateForgetTime = 3000; // 3s - * await scanner.updateScanSettings(scanSettings); - */ -export interface ScanSettings { - intervalTime?: number; - duplicateForgetTime?: number; - oneDRememberFrameCount?: number; - oneDTrustFrameCount?: number; - /** - * Whether to play sound when the scanner reads a barcode successfully. - * Default value is `never`, which does not play sound. - * Use `frame` to play a sound when any barcode is found within a frame. - * Use `unique` to play a sound only when any unique/unduplicated barcode is found within a frame. - * ```js - * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies - * startPlayButton.addEventListener('click', function() { - * scanner.whenToPlaySoundforSuccessfulRead = 'frame'; - * }); - * ``` - * refer: `favicon bug` https://bugs.chromium.org/p/chromium/issues/detail?id=1069731&q=favicon&can=2 - */ - whenToPlaySoundforSuccessfulRead?: string; - /** - * The sound to play when the scanner get successfull read. - * ```js - * scanner.soundOnSuccessfullRead = new Audio("./pi.mp3"); - * ``` - */ - soundOnSuccessfullRead?: string; - /** - * Whether to vibrate when the scanner reads a barcode successfully. - * Default value is `never`, which does not vibrate. - * Use `frame` to vibrate when any barcode is found within a frame. - * Use `unique` to vibrate only when any unique/unduplicated barcode is found within a frame. - * ```js - * // Can I use? https://caniuse.com/?search=vibrate - * // A user gesture required. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#chrome_enterprise_policies - * startPlayButton.addEventListener('click', function() { - * scanner.whenToVibrateforSuccessfulRead = 'frame'; - * }); - * ``` - */ - whenToVibrateforSuccessfulRead?: string; - /** - * Get or set how long (ms) the vibration lasts. - * @see [[whenToVibrateforSuccessfulRead]] - */ - vibrateDuration?: number; - captureAndDecodeInParallel?: boolean; - autoZoom?: boolean; - autoFocus?: boolean; - autoSuggestTip?: boolean; -} -//# sourceMappingURL=scanSettings.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/scannerplaycallbackinfo.d.ts b/dist/types/interface/scannerplaycallbackinfo.d.ts deleted file mode 100644 index f8fcdb3..0000000 --- a/dist/types/interface/scannerplaycallbackinfo.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface ScannerPlayCallbackInfo { - height: number; - width: number; - deviceId: string; -} -//# sourceMappingURL=scannerplaycallbackinfo.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/textresult.d.ts b/dist/types/interface/textresult.d.ts deleted file mode 100644 index 3a31400..0000000 --- a/dist/types/interface/textresult.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { LocalizationResult } from './localizationresult'; -import { EnumBarcodeFormat } from "../enum/enumbarcodeformat"; -/** - * @see [C++ TextResult](https://www.dynamsoft.com/barcode-reader/programming/c-cplusplus/struct/TextResult.html?src=cpp&&ver=latest) -*/ -export interface TextResult { - /** - * The barcode text. - */ - barcodeText: string; - /** - * The barcode format. - */ - barcodeFormat: number | EnumBarcodeFormat; - /** - * Barcode type in string. - */ - barcodeFormatString: string; - /** - * The barcode content in a byte array. - */ - barcodeBytes: number[]; - /** - * The corresponding localization result. - */ - localizationResult: LocalizationResult; -} -//# sourceMappingURL=textresult.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/videodeviceinfo.d.ts b/dist/types/interface/videodeviceinfo.d.ts deleted file mode 100644 index f64ca1c..0000000 --- a/dist/types/interface/videodeviceinfo.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export interface VideoDeviceInfo { - deviceId: string; - label: string; - /** @ignore */ - _checked: boolean; -} -//# sourceMappingURL=videodeviceinfo.d.ts.map \ No newline at end of file diff --git a/dist/types/interface/warning.d.ts b/dist/types/interface/warning.d.ts deleted file mode 100644 index 020ae27..0000000 --- a/dist/types/interface/warning.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface Warning { - id: number; - message: string; -} -//# sourceMappingURL=warning.d.ts.map \ No newline at end of file diff --git a/dist/types/utils/geometric.d.ts b/dist/types/utils/geometric.d.ts deleted file mode 100644 index acf1c3e..0000000 --- a/dist/types/utils/geometric.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare type PointInit = { - x: number; - y: number; -}; -export declare function inPolygon(points: PointInit[], x: number, y: number): boolean; -export declare function isLineSegmentCross(p1: number[], p2: number[], q1: number[], q2: number[]): boolean; -export {}; -//# sourceMappingURL=geometric.d.ts.map \ No newline at end of file diff --git a/legal.txt b/legal.txt deleted file mode 100644 index 7a7d056..0000000 --- a/legal.txt +++ /dev/null @@ -1,1039 +0,0 @@ -Legal Notices: - -This SDK contains parts of following softwares which are used under license. - -=================================================================================== -Zlib. - -Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly - Mark Adler -=================================================================================== - - - -=================================================================================== -LibTiff - -Copyright (c) 1988-1997 Sam Leffler -Copyright (c) 1991-1997 Silicon Graphics, Inc. - -Permission to use, copy, modify, distribute, and sell this software and -its documentation for any purpose is hereby granted without fee, provided -that (i) the above copyright notices and this permission notice appear in -all copies of the software and related documentation, and (ii) the names of -Sam Leffler and Silicon Graphics may not be used in any advertising or -publicity relating to the software without the specific, prior written -permission of Sam Leffler and Silicon Graphics. - -THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, -EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY -WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. - -IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR -ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY -KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA -OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, -AND ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION -WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -=================================================================================== - - - -=================================================================================== -LibJPEG - -In plain English: - -1. We don't promise that this software works. (But if you find any bugs, - please let us know!) -2. You can use this software for whatever you want. You don't have to pay us. -3. You may not pretend that you wrote this software. If you use it in a - program, you must acknowledge somewhere in your documentation that - you've used the IJG code. - -In legalese: - -The authors make NO WARRANTY or representation, either express or implied, -with respect to this software, its quality, accuracy, merchantability, or -fitness for a particular purpose. This software is provided "AS IS", and you, -its user, assume the entire risk as to its quality and accuracy. - -This software is copyright (C) 1991-2010, Thomas G. Lane, Guido Vollbeding. -All Rights Reserved except as specified below. - -Permission is hereby granted to use, copy, modify, and distribute this -software (or portions thereof) for any purpose, without fee, subject to these -conditions: -(1) If any part of the source code for this software is distributed, then this -README file must be included, with this copyright and no-warranty notice -unaltered; and any additions, deletions, or changes to the original files -must be clearly indicated in accompanying documentation. -(2) If only executable code is distributed, then the accompanying -documentation must state that "this software is based in part on the work of -the Independent JPEG Group". -(3) Permission for use of this software is granted only if the user accepts -full responsibility for any undesirable consequences; the authors accept -NO LIABILITY for damages of any kind. - -These conditions apply to any software derived from or based on the IJG code, -not just to the unmodified library. If you use our work, you ought to -acknowledge us. - -Permission is NOT granted for the use of any IJG author's name or company name -in advertising or publicity relating to this software or products derived from -it. This software may be referred to only as "the Independent JPEG Group's -software". - -We specifically permit and encourage the use of this software as the basis of -commercial products, provided that all warranty or liability claims are -assumed by the product vendor. - - -ansi2knr.c is included in this distribution by permission of L. Peter Deutsch, -sole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA. -ansi2knr.c is NOT covered by the above copyright and conditions, but instead -by the usual distribution terms of the Free Software Foundation; principally, -that you must include source code if you redistribute it. (See the file -ansi2knr.c for full details.) However, since ansi2knr.c is not needed as part -of any program generated from the IJG code, this does not limit you more than -the foregoing paragraphs do. - -The Unix configuration script "configure" was produced with GNU Autoconf. -It is copyright by the Free Software Foundation but is freely distributable. -The same holds for its supporting scripts (config.guess, config.sub, -ltmain.sh). Another support script, install-sh, is copyright by X Consortium -but is also freely distributable. - -The IJG distribution formerly included code to read and write GIF files. -To avoid entanglement with the Unisys LZW patent, GIF reading support has -been removed altogether, and the GIF writer has been simplified to produce -"uncompressed GIFs". This technique does not use the LZW algorithm; the -resulting GIF files are larger than usual, but are readable by all standard -GIF decoders. - -We are required to state that - "The Graphics Interchange Format(c) is the Copyright property of - CompuServe Incorporated. GIF(sm) is a Service Mark property of - CompuServe Incorporated." - -libjpeg-turbo - -this software is based in part on the work of the Independent JPEG Group. -=================================================================================== - - - -=================================================================================== -LibPNG - - -This copy of the libpng notices is provided for your convenience. In case of -any discrepancy between this copy and the notices in the file png.h that is -included in the libpng distribution, the latter shall prevail. - -COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: - -If you modify libpng you may insert additional notices immediately following -this sentence. - -This code is released under the libpng license. - -libpng versions 1.0.7, July 1, 2000 through 1.6.32, August 24, 2017 are -Copyright (c) 2000-2002, 2004, 2006-2017 Glenn Randers-Pehrson, are -derived from libpng-1.0.6, and are distributed according to the same -disclaimer and license as libpng-1.0.6 with the following individuals -added to the list of Contributing Authors: - - Simon-Pierre Cadieux - Eric S. Raymond - Mans Rullgard - Cosmin Truta - Gilles Vollant - James Yu - Mandar Sahastrabuddhe - Google Inc. - Vadim Barkov - -and with the following additions to the disclaimer: - - There is no warranty against interference with your enjoyment of the - library or against infringement. There is no warranty that our - efforts or the library will fulfill any of your particular purposes - or needs. This library is provided with all faults, and the entire - risk of satisfactory quality, performance, accuracy, and effort is with - the user. - -Some files in the "contrib" directory and some configure-generated -files that are distributed with libpng have other copyright owners and -are released under other open source licenses. - -libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are -Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from -libpng-0.96, and are distributed according to the same disclaimer and -license as libpng-0.96, with the following individuals added to the list -of Contributing Authors: - - Tom Lane - Glenn Randers-Pehrson - Willem van Schaik - -libpng versions 0.89, June 1996, through 0.96, May 1997, are -Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88, -and are distributed according to the same disclaimer and license as -libpng-0.88, with the following individuals added to the list of -Contributing Authors: - - John Bowler - Kevin Bracey - Sam Bushell - Magnus Holmgren - Greg Roelofs - Tom Tanner - -Some files in the "scripts" directory have other copyright owners -but are released under this license. - -libpng versions 0.5, May 1995, through 0.88, January 1996, are -Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc. - -For the purposes of this copyright and license, "Contributing Authors" -is defined as the following set of individuals: - - Andreas Dilger - Dave Martindale - Guy Eric Schalnat - Paul Schmidt - Tim Wegner - -The PNG Reference Library is supplied "AS IS". The Contributing Authors -and Group 42, Inc. disclaim all warranties, expressed or implied, -including, without limitation, the warranties of merchantability and of -fitness for any purpose. The Contributing Authors and Group 42, Inc. -assume no liability for direct, indirect, incidental, special, exemplary, -or consequential damages, which may result from the use of the PNG -Reference Library, even if advised of the possibility of such damage. - -Permission is hereby granted to use, copy, modify, and distribute this -source code, or portions hereof, for any purpose, without fee, subject -to the following restrictions: - - 1. The origin of this source code must not be misrepresented. - - 2. Altered versions must be plainly marked as such and must not - be misrepresented as being the original source. - - 3. This Copyright notice may not be removed or altered from any - source or altered source distribution. - -The Contributing Authors and Group 42, Inc. specifically permit, without -fee, and encourage the use of this source code as a component to -supporting the PNG file format in commercial products. If you use this -source code in a product, acknowledgment is not required but would be -appreciated. - -END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE. - -TRADEMARK: - -The name "libpng" has not been registered by the Copyright owner -as a trademark in any jurisdiction. However, because libpng has -been distributed and maintained world-wide, continually since 1995, -the Copyright owner claims "common-law trademark protection" in any -jurisdiction where common-law trademark is recognized. - -OSI CERTIFICATION: - -Libpng is OSI Certified Open Source Software. OSI Certified Open Source is -a certification mark of the Open Source Initiative. OSI has not addressed -the additional disclaimers inserted at version 1.0.7. - -EXPORT CONTROL: - -The Copyright owner believes that the Export Control Classification -Number (ECCN) for libpng is EAR99, which means not subject to export -controls or International Traffic in Arms Regulations (ITAR) because -it is open source, publicly available software, that does not contain -any encryption software. See the EAR, paragraphs 734.3(b)(3) and -734.7(b). - -Glenn Randers-Pehrson -glennrp at users.sourceforge.net -April 1, 2017 -=================================================================================== - - - -=================================================================================== -Giflib - -The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -=================================================================================== - - - -=================================================================================== -Google's open-source ZXing ("Zebra Crossing") - -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, -and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by -the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all -other entities that control, are controlled by, or are under common -control with that entity. For the purposes of this definition, -"control" means (i) the power, direct or indirect, to cause the -direction or management of such entity, whether by contract or -otherwise, or (ii) ownership of fifty percent (50%) or more of the -outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity -exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, -including but not limited to software source code, documentation -source, and configuration files. - -"Object" form shall mean any form resulting from mechanical -transformation or translation of a Source form, including but -not limited to compiled object code, generated documentation, -and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or -Object form, made available under the License, as indicated by a -copyright notice that is included in or attached to the work -(an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object -form, that is based on (or derived from) the Work and for which the -editorial revisions, annotations, elaborations, or other modifications -represent, as a whole, an original work of authorship. For the purposes -of this License, Derivative Works shall not include works that remain -separable from, or merely link (or bind by name) to the interfaces of, -the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including -the original version of the Work and any modifications or additions -to that Work or Derivative Works thereof, that is intentionally -submitted to Licensor for inclusion in the Work by the copyright owner -or by an individual or Legal Entity authorized to submit on behalf of -the copyright owner. For the purposes of this definition, "submitted" -means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, -and issue tracking systems that are managed by, or on behalf of, the -Licensor for the purpose of discussing and improving the Work, but -excluding communication that is conspicuously marked or otherwise -designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity -on behalf of whom a Contribution has been received by Licensor and -subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of -this License, each Contributor hereby grants to You a perpetual, -worldwide, non-exclusive, no-charge, royalty-free, irrevocable -copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the -Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of -this License, each Contributor hereby grants to You a perpetual, -worldwide, non-exclusive, no-charge, royalty-free, irrevocable -(except as stated in this section) patent license to make, have made, -use, offer to sell, sell, import, and otherwise transfer the Work, -where such license applies only to those patent claims licensable -by such Contributor that are necessarily infringed by their -Contribution(s) alone or by combination of their Contribution(s) -with the Work to which such Contribution(s) was submitted. If You -institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work -or a Contribution incorporated within the Work constitutes direct -or contributory patent infringement, then any patent licenses -granted to You under this License for that Work shall terminate -as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the -Work or Derivative Works thereof in any medium, with or without -modifications, and in Source or Object form, provided that You -meet the following conditions: - -(a) You must give any other recipients of the Work or -Derivative Works a copy of this License; and - -(b) You must cause any modified files to carry prominent notices -stating that You changed the files; and - -(c) You must retain, in the Source form of any Derivative Works -that You distribute, all copyright, patent, trademark, and -attribution notices from the Source form of the Work, -excluding those notices that do not pertain to any part of -the Derivative Works; and - -(d) If the Work includes a "NOTICE" text file as part of its -distribution, then any Derivative Works that You distribute must -include a readable copy of the attribution notices contained -within such NOTICE file, excluding those notices that do not -pertain to any part of the Derivative Works, in at least one -of the following places: within a NOTICE text file distributed -as part of the Derivative Works; within the Source form or -documentation, if provided along with the Derivative Works; or, -within a display generated by the Derivative Works, if and -wherever such third-party notices normally appear. The contents -of the NOTICE file are for informational purposes only and -do not modify the License. You may add Your own attribution -notices within Derivative Works that You distribute, alongside -or as an addendum to the NOTICE text from the Work, provided -that such additional attribution notices cannot be construed -as modifying the License. - -You may add Your own copyright statement to Your modifications and -may provide additional or different license terms and conditions -for use, reproduction, or distribution of Your modifications, or -for any such Derivative Works as a whole, provided Your use, -reproduction, and distribution of the Work otherwise complies with -the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, -any Contribution intentionally submitted for inclusion in the Work -by You to the Licensor shall be under the terms and conditions of -this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify -the terms of any separate license agreement you may have executed -with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade -names, trademarks, service marks, or product names of the Licensor, -except as required for reasonable and customary use in describing the -origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or -agreed to in writing, Licensor provides the Work (and each -Contributor provides its Contributions) on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -implied, including, without limitation, any warranties or conditions -of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A -PARTICULAR PURPOSE. You are solely responsible for determining the -appropriateness of using or redistributing the Work and assume any -risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, -whether in tort (including negligence), contract, or otherwise, -unless required by applicable law (such as deliberate and grossly -negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, -incidental, or consequential damages of any character arising as a -result of this License or out of the use or inability to use the -Work (including but not limited to damages for loss of goodwill, -work stoppage, computer failure or malfunction, or any and all -other commercial damages or losses), even if such Contributor -has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing -the Work or Derivative Works thereof, You may choose to offer, -and charge a fee for, acceptance of support, warranty, indemnity, -or other liability obligations and/or rights consistent with this -License. However, in accepting such obligations, You may act only -on Your own behalf and on Your sole responsibility, not on behalf -of any other Contributor, and only if You agree to indemnify, -defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason -of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - -To apply the Apache License to your work, attach the following -boilerplate notice, with the fields enclosed by brackets "[]" -replaced with your own identifying information. (Don't include -the brackets!) The text should be enclosed in the appropriate -comment syntax for the file format. We also recommend that a -file or class name and description of purpose be included on the -same "printed page" as the copyright notice for easier -identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -=================================================================================== - - - -=================================================================================== -OpenCV - -License Agreement -For Open Source Computer Vision Library -(3-clause BSD License) - -Copyright (C) 2000-2015, Intel Corporation, all rights reserved. -Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. -Copyright (C) 2009-2015, NVIDIA Corporation, all rights reserved. -Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -Copyright (C) 2015, OpenCV Foundation, all rights reserved. -Copyright (C) 2015, Itseez Inc., all rights reserved. -Third party copyrights are property of their respective owners. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of -the use of this software, even if advised of the possibility of such damage. -=================================================================================== - - - -=================================================================================== -JsonCpp library - -The JsonCpp library's source code, including accompanying documentation, -tests and demonstration applications, are licensed under the following -conditions... - -The author (Baptiste Lepilleur) explicitly disclaims copyright in all -jurisdictions which recognize such a disclaimer. In such jurisdictions, -this software is released into the Public Domain. - -In jurisdictions which do not recognize Public Domain property (e.g. Germany as of -2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is -released under the terms of the MIT License (see below). - -In jurisdictions which recognize Public Domain property, the user of this -software may choose to accept it either as 1) Public Domain, 2) under the -conditions of the MIT License (see below), or 3) under the terms of dual -Public Domain/MIT License conditions described here, as they choose. - -The MIT License is about as close to Public Domain as a license can get, and is -described in clear, concise terms at: - - http://en.wikipedia.org/wiki/MIT_License - -The full text of the MIT License follows: - -======================================================================== -Copyright (c) 2007-2010 Baptiste Lepilleur - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, copy, -modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -======================================================================== -(END LICENSE TEXT) - -The MIT license is compatible with both the GPL and commercial -software, affording one all of the rights of Public Domain with the -minor nuisance of being required to keep the above copyright notice -and license text in the source code. Note also that by accepting the -Public Domain "license" you can re-license your copy using whatever -license you like. -=================================================================================== - - - -=================================================================================== -Libcurl - -COPYRIGHT AND PERMISSION NOTICE - -Copyright (c) 1996 - 2015, Daniel Stenberg, daniel@haxx.se. - -All rights reserved. - -Permission to use, copy, modify, and distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. - -Except as contained in this notice, the name of a copyright holder shall not -be used in advertising or otherwise to promote the sale, use or other dealings -in this Software without prior written authorization of the copyright holder. -=================================================================================== - - - -=================================================================================== -Caffe - -COPYRIGHT - -All contributions by the University of California: -Copyright (c) 2014-2017 The Regents of the University of California (Regents) -All rights reserved. - -All other contributions: -Copyright (c) 2014-2017, the respective contributors -All rights reserved. - -Caffe uses a shared copyright model: each contributor holds copyright over -their contributions to Caffe. The project versioning records all such -contribution and copyright details. If a contributor wants to further mark -their specific copyright on a particular contribution, they should indicate -their copyright solely in the commit message of the change when it is -committed. - -LICENSE - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -CONTRIBUTION AGREEMENT - -By contributing to the BVLC/caffe repository through pull-request, comment, -or otherwise, the contributor releases their content to the -license and copyright terms herein. -=================================================================================== - - - -=================================================================================== -Protocol Buffers - -This license applies to all parts of Protocol Buffers except the following: - - - Atomicops support for generic gcc, located in - src/google/protobuf/stubs/atomicops_internals_generic_gcc.h. - This file is copyrighted by Red Hat Inc. - - - Atomicops support for AIX/POWER, located in - src/google/protobuf/stubs/atomicops_internals_power.h. - This file is copyrighted by Bloomberg Finance LP. - -Copyright 2014, Google Inc. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Code generated by the Protocol Buffer compiler is owned by the owner -of the input file used when generating it. This code is not -standalone and requires a support library to be linked with it. This -support library is itself covered by the above license. -=================================================================================== - - - -=================================================================================== -Boost - -Boost Software License - Version 1.0 - August 17th, 2003 - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -=================================================================================== - - - -=================================================================================== -OpenBLAS - -Copyright (c) 2011-2014, The OpenBLAS Project -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - 3. Neither the name of the OpenBLAS project nor the names of - its contributors may be used to endorse or promote products - derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -=================================================================================== - - - -=================================================================================== -GFlags - -Copyright (c) 2006, Google Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -=================================================================================== - - - -=================================================================================== -GLog - -Copyright (c) 2008, Google Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -A function gettimeofday in utilities.cc is based on - -http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/COPYING&q=GetSystemTimeAsFileTime%20license:bsd - -The license of this code is: - -Copyright (c) 2003-2008, Jouni Malinen and contributors -All Rights Reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -3. Neither the name(s) of the above-listed copyright holder(s) nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -=================================================================================== - -=================================================================================== -howler - -Copyright (c) 2013-2020 James Simpson and GoldFire Studios, Inc. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -=================================================================================== - -=================================================================================== -showdown - -MIT License -Copyright (c) 2018,2021 ShowdownJS -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -=================================================================================== - -=================================================================================== -highlight.js - -BSD 3-Clause License - -Copyright (c) 2006, Ivan Sagalaev. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -=================================================================================== - -=================================================================================== -markdown-to-html-github-style(https://github.com/KrauseFx/markdown-to-html-github-style) - -MIT License - -Copyright (c) 2019 Felix Krause - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -=================================================================================== - -=================================================================================== -localForage - --- Offline Storage, Improved -Version 1.7.3 -https://localforage.github.io/localForage -(c) 2013-2017 Mozilla, Apache License 2.0 -=================================================================================== - -=================================================================================== -Protocol Buffers - -This license applies to all parts of Protocol Buffers except the following: - - - Atomicops support for generic gcc, located in - src/google/protobuf/stubs/atomicops_internals_generic_gcc.h. - This file is copyrighted by Red Hat Inc. - - - Atomicops support for AIX/POWER, located in - src/google/protobuf/stubs/atomicops_internals_power.h. - This file is copyrighted by Bloomberg Finance LP. - -Copyright 2014, Google Inc. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Code generated by the Protocol Buffer compiler is owned by the owner -of the input file used when generating it. This code is not -standalone and requires a support library to be linked with it. This -support library is itself covered by the above license. -=================================================================================== \ No newline at end of file diff --git a/package.json b/package.json index fb6e2d0..4a3909c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dynamsoft-javascript-barcode", - "version": "9.6.32", + "version": "9.6.42", "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": [ @@ -9,8 +9,8 @@ "/dist/*.html", "/dist/*.wasm", "/dist/**/*.d.ts", - "/Api Reference.url", - "/legal.txt", + "/API Reference.url", + "/LEGAL.txt", "/samples.url" ], "homepage": "https://www.dynamsoft.com/barcode-reader/sdk-javascript", @@ -18,16 +18,17 @@ "module": "./dist/dbr.pure.esm.js", "exports": { "import": { - "types": "./dist/types/dbr.d.ts", + "types": "./dist/dbr.d.ts", "default": "./dist/dbr.pure.esm.js" }, "require": { - "types": "./dist/types/dbr.d.ts", + "types": "./dist/dbr.d.ts", "default": "./dist/dbr.pure.js" } }, "sideEffects": false, - "types": "./dist/types/dbr.d.ts", + "type": "module", + "types": "./dist/dbr.d.ts", "publishConfig": { "registry": "https://registry.npmjs.org/", "tag": "latest" @@ -64,7 +65,7 @@ "build:doc": "typedoc", "build-dev": "rollup -c --environment BUILD:development", "build": "rollup -c --environment BUILD:production", - "update:readme": "updateReadme --package=dynamsoft-barcode-reader --version=auto --branch=9.6.32 --path=programming/javascript/user-guide/index.md", + "update:readme": "updateReadme --package=dynamsoft-barcode-reader --version=auto --branch=preview --html", "update:prod": "updatePackage --package=dynamsoft-javascript-barcode --version=auto --env=production --tag=latest", "update:beta": "updatePackage --package=dynamsoft-javascript-barcode --version=auto --env=beta --tag=beta", "update:iv": "updatePackage --package=dynamsoft-javascript-barcode --version=auto --env=internalVersion --tag=iv", @@ -72,48 +73,30 @@ "updateLink:npm": "updateLink --source=npm", "updateLink:zip": "updateLink --source=zip", "updateLink:github": "updateLink --source=github", - "updateDCE:prod": "updateImportedPkg --package=dynamsoft-camera-enhancer --dev=false", - "updateDCE:dev": "updateImportedPkg --package=dynamsoft-camera-enhancer --dev=true", + "updateDCE:prod": "updateImportedPkg --package=dynamsoft-camera-enhancer --no-dev", + "updateDCE:dev": "updateImportedPkg --package=dynamsoft-camera-enhancer --dev", "makeZip": "makeZip --package=dynamsoft-barcode-reader --version=auto --sampleBranch=9.x --structure=old", "easyPublish": "npm run update:dev && npm run build-dev && npm publish" }, "devDependencies": { - "@dynamsoft/rd2-scripts": "^0.0.80", - "@rollup/plugin-node-resolve": "13.0.5", - "@rollup/plugin-replace": "3.0.0", - "@rollup/plugin-typescript": "8.3.0", - "@scannerproxy/browser-info": "^1.0.7", - "@scannerproxy/curscript-path": "^1.0.3", - "@scannerproxy/dlsjs": "^2.0.9", - "@types/node": "16.11.2", - "@types/node-fetch": "2.6.1", - "@types/node-localstorage": "1.3.0", - "detect-browser-node-ssr": "^2.0.0", - "fs-extra": "8.1.0", - "highlight.js": "^9.15.6", + "@dynamsoft/rd2-scripts": "0.1.17", + "@rollup/plugin-node-resolve": "^15.0.1", + "@rollup/plugin-replace": "^5.0.5", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.6", + "@scannerproxy/browser-info": "^2.0.8", + "@scannerproxy/curscript-path": "^2.0.4", + "@scannerproxy/dlsjs": "^3.0.20", + "detect-browser-node-ssr": "^3.0.2", + "fs-extra": "^8.1.0", "mutable-promise": "^1.1.13", - "rollup": "2.58.0", - "rollup-plugin-terser": "7.0.2", - "showdown": "^1.9.0", - "tslib": "2.3.1", - "typedoc": "0.22.6", - "typedoc-plugin-missing-exports": "0.22.3", - "typescript": "4.3.5" - }, - "peerDependencies": { - "node-fetch": "^2.6.5", - "node-localstorage": "^2.2.1" - }, - "peerDependenciesMeta": { - "node-fetch": { - "optional": true - }, - "node-localstorage": { - "optional": true - } + "rollup": "^3.29.4", + "rollup-plugin-dts": "^6.1.0", + "tslib": "^2.6.2", + "typescript": "^4.9.5" }, "dependencies": { "dm-howler": "^2.2.4", - "dynamsoft-camera-enhancer": "^3.3.9" + "dynamsoft-camera-enhancer": "3.3.10-beta-202404222209" } } diff --git a/samples.url b/samples.url index e2a82ba..a460ba7 100644 --- a/samples.url +++ b/samples.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.32 \ No newline at end of file +URL=https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.42 \ No newline at end of file