From d1530ec65edd54ab08d3abb3892253175011fe8d Mon Sep 17 00:00:00 2001 From: DMGithubPublisher Date: Thu, 12 Oct 2023 10:54:41 +0800 Subject: [PATCH] 3.3.8 --- Api Reference.url | 2 +- README.md | 4 ++-- dist/dce.esm.js | 4 ++-- dist/dce.js | 4 ++-- dist/dce.mjs | 4 ++-- package.json | 2 +- samples.url | 2 +- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Api Reference.url b/Api Reference.url index 30e890d..fbc83fa 100644 --- a/Api Reference.url +++ b/Api Reference.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/api-reference/?ver=3.3.7 \ No newline at end of file +URL=https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/api-reference/?ver=3.3.8 \ No newline at end of file diff --git a/README.md b/README.md index 06d7630..5a56fbd 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ The simplest way to include the SDK is to use either the [jsDelivr](https://jsde ``` -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dce/dynamsoft-camera-enhancer-js/dynamsoft-camera-enhancer-js-3.3.7/dist/dce.js](https://download2.dynamsoft.com/dce/dynamsoft-camera-enhancer-js/dynamsoft-camera-enhancer-js-3.3.7/dist/dce.js) +> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dce/dynamsoft-camera-enhancer-js/dynamsoft-camera-enhancer-js-3.3.8/dist/dce.js](https://download2.dynamsoft.com/dce/dynamsoft-camera-enhancer-js/dynamsoft-camera-enhancer-js-3.3.8/dist/dce.js) #### Host the SDK yourself @@ -74,7 +74,7 @@ The following shows a few ways to download the SDK. Depending on how you downloaded the SDK and where you put it. You can typically include it like this: ```html - + ``` or diff --git a/dist/dce.esm.js b/dist/dce.esm.js index 8ce0679..f3e0cf4 100644 --- a/dist/dce.esm.js +++ b/dist/dce.esm.js @@ -4,8 +4,8 @@ * @website https://www.dynamsoft.com * @copyright Copyright 2023, Dynamsoft Corporation * @author Dynamsoft - * @version 3.3.7 (js 20231010) + * @version 3.3.8 (js 20231011) * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest */ -import{fabric as e}from"dm-fabric";const t="undefined"==typeof self;let i,s,r,a,o;if("undefined"!=typeof navigator&&(i=navigator,s=i.userAgent,r=i.platform,a=i.mediaDevices),!t){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:i.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:r,search:"Win"},Mac:{str:r},Linux:{str:r}};let a="unknownBrowser",n=0,h="unknownOS";for(let t in e){const i=e[t]||{};let r=i.str||s,o=i.search||t,h=i.verStr||s,l=i.verSearch||t;if(l instanceof Array||(l=[l]),-1!=r.indexOf(o)){a=t;for(let e of l){let t=h.indexOf(e);if(-1!=t){n=parseFloat(h.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let r=i.str||s,a=i.search||e;if(-1!=r.indexOf(a)){h=e;break}}"Linux"==h&&-1!=s.indexOf("Windows NT")&&(h="HarmonyOS"),o={browser:a,version:n,OS:h}}t&&(o={browser:"ssr",version:0,OS:"ssr"});const n="undefined"!=typeof WebAssembly&&s&&!(/Safari/.test(s)&&!/Chrome/.test(s)&&/\(.+\s11_2_([2-6]).*\)/.test(s)),h=!("undefined"==typeof Worker),l=!(!a||!a.getUserMedia),d=async()=>{let e=!1;if(l)try{(await a.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 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"./"})();class g{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(),s=this.mapEvent_Callbacks.get(i);if(!s)throw new Error(`Event '${e}' does not exist.`);let r=s.get(t);r||(r=e=>{const i=e.e;if(!i)return void(t&&t.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const s={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let e,t,r,a;const o=i.target.getBoundingClientRect();e=o.left,t=o.top,r=e+window.scrollX,a=t+window.scrollY;const n=this._drawingLayer.fabricCanvas.lowerCanvasEl.width,h=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,l=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),d=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),c=l/d,g=n/h,u=this._drawingLayer._getObjectFit();let _,f,m,p,w=1;if("contain"===u)c0?s-1:r,f),actionName:"modifyPolygon",pointIndex:s}),t}),{})}_extendSet(t,i){if("vertices"===t){const t=this._fabricObject;if(t.group){const e=t.group;t.points=i.map((t=>({x:t.x-e.left-e.width/2,y:t.y-e.top-e.height/2}))),e.addWithUpdate()}else t.points=i;const s=t.points.length-1;return t.controls=t.points.reduce((function(t,i,r){return t["p"+r]=new e.Control({positionHandler:u,actionHandler:m(r>0?r-1:s,f),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}_extendGet(t){if("vertices"===t){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 s of i.points){let r=s.x-i.pathOffset.x,a=s.y-i.pathOffset.y;const o=e.util.transformPoint({x:r,y:a},i.calcTransformMatrix());t.push({x:o.x,y:o.y})}return t}}}const w=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 s=0;si&&(i=r.length))}if(-1===i)break;for(let s=0;s=e[s].length-1)continue;let r=" ".repeat(i+2-e[s][t].length);e[s][t]=e[s][t].concat(r)}}})(t),(e=>{let t="";for(let i=0;iw?(f=u,m=u/p,{x:a.x*s.width,y:(a.y-(_-m)/2)*s.width}):(f=_*p,m=_,{x:(a.x-(u-f)/2)*s.height,y:a.y*s.height}):"cover"===d?p>w?{x:(c-s.height*u)/2+a.x*s.height,y:a.y*s.height}:{x:a.x*s.width,y:(g-s.width*_)/2+a.y*s.width}:{x:a.x*s.width,y:a.y*s.height}}return s={width:1,height:1},{x:a.x*s.width,y:a.y*s.height}},e.Canvas.prototype._onTouchStart=function(t){var i=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),i&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var s=this.upperCanvasEl,r=this._getEventPrefix();e.util.addListener(e.document,"touchend",this._onTouchEnd,{passive:!1}),e.util.addListener(e.document,"touchmove",this._onMouseMove,{passive:!1}),e.util.removeListener(s,r+"down",this._onMouseDown)},e.Textbox.prototype._wrapLine=function(t,i,s,r){const a=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),o=!(!a||!a.length);var n=0,h=this.splitByGrapheme||o,l=[],d=[],c=h?e.util.string.graphemeSplit(t):t.split(this._wordJoiners),g="",u=0,_=h?"":" ",f=0,m=0,p=0,w=!0,v=this._getWidthOfCharSpacing();r=r||0;0===c.length&&c.push([]),s-=r;for(var y=0;ys&&!w?(l.push(d),d=[],n=f,w=!0):n+=v,w||h||d.push(_),d=d.concat(g),m=h?0:this._measureWord([_],i,u),u++,w=!1,f>p&&(p=f);return y&&l.push(d),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),l});class y{constructor(t,i,s,r){let a,o;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 e.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(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 s of t){const t=s.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 s of t){const t=s.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{const t=[];for(let s of i)e.hasDrawingItem(s)&&t.push(s);t.length>0&&e.onSelectionChange&&e.onSelectionChange([],t)}),0)}})),this.fabricCanvas.on("selection:updated",(function(e){const t=e.selected,i=e.deselected,s=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!s.includes(t)&&s.push(t)}for(let e of i){const t=e.getDrawingItem()._drawingLayer;t&&!s.includes(t)&&s.push(t)}for(let e of s){const s=[],r=[];for(let i of t){const t=i.getDrawingItem();t._drawingLayer===e&&s.push(t)}for(let t of i){const i=t.getDrawingItem();i._drawingLayer===e&&r.push(i)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(s,r)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas),this.id=i,this._mapDrawingStyles=s,i){case 1:a=s.get(1),o=s.get(5);break;case 2:a=s.get(2),o=s.get(6);break;case 3:a=s.get(3),o=s.get(7);break;default:a=s.get(4),o=s.get(8)}for(let e of g.arrMediaTypes)this.mapMediaType_Style.set(e,{default:a,selected:o})}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);const t=e._mapStyle.get(e.styleSelector);return t||null}_changeMediaTypeCurStyleInStyleSelector(e,t,i,s){let r;switch(e){case"rect":r=this.fabricCanvas.getObjects("rect");break;case"arc":r=this.fabricCanvas.getObjects("circle");break;case"polygon":r=this.fabricCanvas.getObjects("polygon");break;case"image":r=this.fabricCanvas.getObjects("image");break;case"text":r=this.fabricCanvas.getObjects("textbox");break;case"line":r=this.fabricCanvas.getObjects("line");break;case"path":r=this.fabricCanvas.getObjects("path")}for(let e of r){if(!this._arrFabricObject.includes(e))continue;const s=e.getDrawingItem();s.styleSelector===t&&this._changeItemStyle(s,i,!0)}s||this.fabricCanvas.renderAll()}_changeItemStyle(e,t,i){if(!e||!t)return;const s=e._getFabricObject();"number"==typeof e.styleId&&(t=this._getDrawingStyle(e.styleId)),s.strokeWidth=t.lineWidth,"fill"===t.paintMode?(s.fill=t.fillStyle,s.stroke=t.fillStyle):"stroke"===t.paintMode?(s.fill="transparent",s.stroke=t.strokeStyle):"strokeAndFill"===t.paintMode&&(s.fill=t.fillStyle,s.stroke=t.strokeStyle),s.fontFamily&&(s.fontFamily=t.fontFamily),s.fontSize&&(s.fontSize=t.fontSize),s.group||(s.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(e,t,i){if(!e||!t)return;const s=e.getChildItems();if("add"===i){if(s.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 s=()=>{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",s),t._on("deselected",r),t._funcChangeStyleToSelected=s,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,i,!0)}e._fabricObject.addWithUpdate(t._getFabricObject())}else{if("remove"!==i)return;if(!s.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 s=this.fabricCanvas.getObjects();let r,a;if(s.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===e._mediaType){r=e.getChildItems();for(let e of r)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(r){for(let e of r){const t=this.mapMediaType_Style.get(e._mediaType);for(let i of g.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)a=this._getDrawingStyle(e.styleId);else{a=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},s=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e._on("selected",i),e._on("deselected",s),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,a,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of g.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)a=this._getDrawingStyle(e.styleId);else{a=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected)},s=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default)};e._on("selected",i),e._on("deselected",s),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=s}this._changeItemStyle(e,a)}e._zIndex=this.id,e._drawingLayer=this,e._drawingLayerId=this.id;const o=this._arrFabricObject.length;let n=s.length;if(o)n=s.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 s=new y(e,t,this._mapDrawingStyles,{enableRetinaScaling:!1});return s._manager=this,this._arrDrawingLayer.push(s),this._switchPointerEvent(),s}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 S{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,s){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");s&&(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,s){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");return i||(i=[]),s?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 s=i.indexOf(t);-1!==s&&i.splice(s,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 C{static multiply(e,t){const i=[];for(let s=0;s<3;s++){const r=t.slice(3*s,3*s+3);for(let t=0;t<3;t++){const s=[e[t],e[t+3],e[t+6]].reduce(((e,t,i)=>e+t*r[i]),0);i.push(s)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,t,i){return C.multiply(e,[1,0,0,0,1,0,t,i,1])}static rotate(e,t){var i=Math.cos(t),s=Math.sin(t);return C.multiply(e,[i,-s,0,s,i,0,0,0,1])}static scale(e,t,i){return C.multiply(e,[t,0,0,0,i,0,0,0,1])}}var E;!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"}(E||(E={}));const L=(e,t,i,s)=>{let r=t+Math.round((e-t)/i)*i;return s&&(r=Math.min(r,s)),r};class I{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 s;return t||(i=await(s=e,new Promise(((e,t)=>{let i=URL.createObjectURL(s),r=new Image;r.dbrObjUrl=i,r.src=i,r.onload=()=>{e(r)},r.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})(t),s=i instanceof HTMLImageElement?i.naturalWidth:i.width,r=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=s,this._imgHeight=r;const a=e=>{const t=Date.now();if(0===s||0===r)return null;if(e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");const i=this._scanRegion,a=this.getFrameSize(s,r,i,this.maxCvsSideLength);if(!a)return null;let o=!0;s===a.sWidth&&r===a.sHeight&&(o=!1);const n=this.mapPixelFormatString_Enum.get(this.framePixelFormat.toLowerCase()),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:a.sx,sy:a.sy,width:a.dWidth,height:a.dHeight,colorMode:null,pixelFormat:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:a.sWidth,_sHeight:a.sHeight,_bUseWebGL:null},l=this._getImageData(e,s,r,a,null,{pixelFormat:n});if(!l)return null;const d=Date.now();if(I._onLog&&I._onLog("DCE: _getVideoData(region?) END: "+d),h.data=l.data,h.pixelFormat=h.colorMode=l.pixelFormat,h._bUseWebGL=l._bUseWebGL,h.timeSpent=d-t,h.timeStamp=d,l.pixelFormat===E.GREY)h.stride=h.width;else h.stride=4*h.width;return 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==s&&t.height==r||(t.width=s,t.height=r);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=a(i)}catch(e){throw e}const n=this.mapCameraEvents.get("singleframeacquired");for(let e of n)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",E.GREY],["grey32",E.GREY32],["rgba",E.RGBA],["rbga",E.RBGA],["grba",E.GRBA],["gbra",E.GBRA],["brga",E.BRGA],["bgra",E.BGRA]]),this.shaderPixelFormat=E.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,s,r;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 a=this.getVideoFit(),o=this._video.videoWidth,n=this._video.videoHeight,h=this._elContainer.getBoundingClientRect(),l=h.left,d=h.top,c=window.getComputedStyle(this._elContainer),g=parseFloat(c.width),u=parseFloat(c.height),_=g/u,f=o/n;let m=1;if("contain"===a)if(f>_){m=g/o,s=(t-l)/m;r=(i-d-(u-g/f)/2)/m}else{m=u/n,r=(i-d)/m;s=(t-l-(g-u*f)/2)/m}else{if("cover"!==a)throw new Error("Unsupported object-fit.");if(f>_){m=u/n,r=(i-d)/m;s=(t-l+(u*f-g)/2)/m}else{m=g/o,s=(t-l)/m;r=(i-d+(g/f-u)/2)/m}}const p={x:s+"px",y:r+"px"},w=2*Math.round(Math.min(o,n)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",v=w;await this._setLocalFocus(p,w,v,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;e.width=this.width,e.height=this.height;if("grey"===(this.pixelFormat||this.colorMode)){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}await this.setResolution(e,t),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this._isSingleFrameModeEnabled())if("visible"===document.visibilityState){if(I._onLog&&I._onLog("DCE: document visible."),this._bOpen&&this._vc_bPlayingVideoBeforeHide)if(this.videoSrc)this._video.play();else if(this._video.srcObject){const e=this._video.srcObject.getTracks()[0];this._video.srcObject.active&&e&&!e.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(I._onLog&&I._onLog("DCE: document hidden."),["iPhone","iPad","Mac"].includes(o.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let e of this._arrScanRegionOverlays)e&&(e.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&(e.style.display="",this._updateScanRegionOverlay(e));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this._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:n,worker:h,getUserMedia:l,camera:await d(),browser:o.browser,version:o.version,OS:o.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");I._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 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){I._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=I._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",I.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,s,r;if(this._isSingleFrameModeEnabled()?(i=this._imgWidth,s=this._imgHeight,r="contain"):(i=null===(e=this._video)||void 0===e?void 0:e.videoWidth,s=null===(t=this._video)||void 0===t?void 0:t.videoHeight,r=this.getVideoFit()),!i||!s)throw new Error("Invalid content dimensions.");return{width:i,height:s,objectFit:r}}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:s,objectFit:r}=t;if(i<=0||s<=0)return e.width=0,void(e.height=0);const a=this._getRegionInPixels(i,s,this._scanRegion),o=this.getFrameSize(i,s,this._scanRegion,this.maxCvsSideLength),n=o.dWidth,h=o.dHeight;e.width==n&&e.height==h||(e.width=n,e.height=h);const l=window.getComputedStyle(this._elContainer),d=parseFloat(l.width),c=parseFloat(l.height),g=d/c,u=i/s;let _,f,m,p,w=1;"contain"===r?(u>g?(w=d/i,_=0,f=(c-s*w)/2):(w=c/s,_=(d-i*w)/2,f=0),_+=a.regionLeft*w,f+=a.regionTop*w,m=(a.regionRight-a.regionLeft)*w,p=(a.regionBottom-a.regionTop)*w):"cover"===r?(u>g?(w=c/s,_=a.regionLeft*w-(i*w-d)/2,f=a.regionTop*w):(w=d/i,_=a.regionLeft*w,f=a.regionTop*w-(s*w-c)/2),m=(a.regionRight-a.regionLeft)*w,p=(a.regionBottom-a.regionTop)*w):(_=0,f=0,m=0,p=0),e.style.position="absolute",e.style.left=_+"px",e.style.top=f+"px",e.style.width=m+"px",e.style.height=p+"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 s=["rectangle","focus"],r=["crossline","crosshair"];let a=!1,o=!1;for(let e of i)e=e.toLowerCase(),s.includes(e)&&!a&&(a=!0,this._decoratorType.push(e)),r.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 s=i.regionRight-i.regionLeft,r=i.regionBottom-i.regionTop;if(t.width==s&&t.height==r||(t.width=s,t.height=r),s<=0||r<=0)return;const a=t.getContext("2d");a.clearRect(0,0,t.width,t.height);const o=this._decoratorArea.x/100*s,n=this._decoratorArea.y/100*r,h=this._decoratorArea.width/100*s,l=this._decoratorArea.height/100*r;for(let e of this._decoratorType){if("rectangle"===e){a.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,a.fillRect(0,0,t.width,t.height),a.clearRect(Math.round(o),Math.round(n),Math.round(h),Math.round(l)),a.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,a.fillRect(Math.round(o),Math.round(n),Math.round(h),Math.round(l)),a.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,a.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const e=a.lineWidth/2;a.strokeRect(Math.round(o-e),Math.round(n-e),Math.round(h+a.lineWidth),Math.round(l+a.lineWidth))}if("focus"===e){a.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,a.fillRect(0,0,t.width,t.height),a.clearRect(Math.round(o),Math.round(n),Math.round(h),Math.round(l)),a.fillStyle=this._viewDecoratorInfo.focus.fillStyle,a.fillRect(Math.round(o),Math.round(n),Math.round(h),Math.round(l)),a.lineWidth=this._viewDecoratorInfo.focus.lineWidth,a.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const e=a.lineWidth/2,i=[0,.25,.75,1],s=[0,.25,.75,1];a.beginPath();for(let e=0;e{const e=parseFloat(window.getComputedStyle(this._elContainer).width),t=parseFloat(window.getComputedStyle(this._elContainer).height);let a,o={regionBottom:s,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===r?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 I;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,I.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{I.onWarning&&I.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((()=>{I.onWarning&&I.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 b,t}static async playVideo(e,t,i){return new Promise(((s,r)=>{e||r(new Error("Invalid video element.")),t||r(new Error("Invalid source.")),e.onloadedmetadata=async()=>{e.onloadedmetadata=null,await e.play(),s(e)},"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,void 0!==i&&setTimeout((()=>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"],s=["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"],r=e.filter((e=>{const i=e.label.toLowerCase();return t.some((e=>i.includes(e)))}));if(!r.length)return null;const a=r.find((e=>{const t=e.label.toLowerCase();return i.some((e=>t.includes(e)))}));if(a)return a.deviceId;const o=r.find((e=>{const t=e.label.toLowerCase();return s.some((e=>t.includes(e)))}));return o?o.deviceId:r[0].deviceId}static findBestRearCamera(e){if(!e||!e.length)return null;if(["iPhone","iPad","Mac"].includes(o.OS))return I.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(o.OS)?e[e.length-1].deviceId:null}_isSingleFrameModeEnabled(){return 0!=this.singleFrameMode}async play(e,t,i,s){let r;if(this._video&&this.videoSrc){I._onLog&&(r=Date.now(),I._onLog("DCE: start loading static video: "+r));const e=await I.playVideo(this._video,this.videoSrc,4e3);if(I._onLog&&I._onLog("DCE: finish loading static video. Costs: "+(Date.now()-r)),!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 s&&s.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 a=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,a{var r;try{this._video&&this._video.srcObject&&this.stop(),I._onLog&&I._onLog("DCE: ======before video========");const a=()=>{if(!this._video)throw l&&l.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},n=this.getVideoSettings();let h,l;if("boolean"==typeof n.video&&(n.video={}),e)delete n.video.facingMode,n.video.deviceId={exact:e};else if(n.video.deviceId);else if(this._lastDeviceId)delete n.video.facingMode,n.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&I.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete n.video.facingMode,n.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&&(n.video.width=e,n.video.height=t)}else if(this.ifSkipCameraInspection);else if(n.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=n.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){h=!0;const e=I.findBestRearCamera(this._allCameras);e&&(delete n.video.facingMode,n.video.deviceId={exact:e})}}t&&(n.video.width={ideal:t}),i&&(n.video.height={ideal:i}),I._onLog&&I._onLog("DCE: ======try getUserMedia========");let d=[0,500],c=null;const g=async e=>{for(let t of d){t&&await new Promise((e=>setTimeout(e,t))),a();try{I._onLog&&I._onLog("DCE: ask "+JSON.stringify(e)),l=await navigator.mediaDevices.getUserMedia(e);break}catch(e){if(a(),"NotFoundError"===e.name||"NotAllowedError"===e.name)throw e;c=e,I._onLog&&I._onLog("DCE: "+e.message||e)}}a()};let u;if(await g(n),!l){if(I._onLog&&I._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(n)),"object"==typeof u.video){["iPhone","iPad"].includes(o.OS)?(t>=1280||i>=1280?u.video.width=1280:t>=640||i>=640?u.video.width=640:(t<640||i<640)&&(u.video.width=320),delete u.video.height):h&&!n.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0}I._onLog&&I._onLog("DCE: "+u),await g(u)}if(l||(d=[1e3,2e3],await g(n)),l||await g(u),!l)throw c;const _=()=>{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 s of this._allCameras)if(e.deviceId===s.deviceId){s._checked=!0,s.label=t.label,i=s;break}}this._currentCamera=i};if(await this.getAllCameras(!1),a(),h&&!this.ifSkipCameraInspection){_();const e=I.findBestRearCamera(this._allCameras),t=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;e&&e!=t&&(l.getTracks().forEach((e=>{e.stop()})),d=[0,500,1e3,2e3],n.video.deviceId={exact:e},await g(n))}I._onLog&&I._onLog("DCE: ======play video========"),a(),await I.playVideo(this._video,l,4e3),a(),I._onLog&&I._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=f,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),I._onLog&&I._onLog("DCE: got "+f),_(),this._renderSelCameraInfo();const m={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(m.deviceId&&(this._lastDeviceId=m.deviceId,this.ifSaveLastUsedCamera&&I.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),n.video.width&&n.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(n.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(n.video.height))))),!s||!s.notTriggerPlayedEvent){const e=this.mapCameraEvents.get("played");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(m));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return this.promisePlay=null,m}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}})(),I._onLog&&(r=Date.now(),I._onLog("DCE: start opening camera: "+r));const n=await this.promisePlay;return I._onLog&&I._onLog("DCE: finish opening camera. Costs: "+(Date.now()-r)),this.playCallbackInfo=JSON.parse(JSON.stringify(n)),this._recordedStates.videoPlaying=!0,n}async resume(){this._assertOpen(),this._video&&(await this._video.play(),this._recordedStates.videoPlaying=!0),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}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','','',''].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 e of this.extraBindings)try{e(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(o.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(I.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&&(I._onLog&&I._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&&(I._onLog&&I._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=[],s=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&s.push(e);for(let e=0;e{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}if(s!==a.width||r!==a.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(a));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return a}getResolution(){if(this._bOpen)return[this._video.videoWidth,this._video.videoHeight];{let e=0,t=0;const i=this.videoSettings.video.width,s=this.videoSettings.video.height;return i&&(e=i.exact||i.ideal||i),s&&(t=s.exact||s.ideal||s),[e,t]}}async setResolution(e,t){let i,s;if(e instanceof Array?(i=e[0],s=e[1]):(i=e,s=t),this.videoSettings.video.width={ideal:i},this.videoSettings.video.height={ideal:s},!this._bOpen||this._video.paused)return null;const r=this._video.videoWidth,a=this._video.videoHeight,o=await this.play(null,i,s);if(r!==o.width||a!==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 s="";const r=(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},a=async(e,t,i)=>{const s={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(s)}catch(e){return null}if(!r)return null;const a=r.getVideoTracks();let o=null;try{const e=a[0].getSettings();o={width:e.width,height:e.height}}catch(e){const t=document.createElement("video");t.srcObject=r,o={width:t.videoWidth,height:t.videoHeight},t.srcObject=null}return a.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(s=o.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:o.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!s)return null;let n=this._mapCameraResolutions.get(s);if(n&&!e)return this._mapCameraResolutions.get(s);this._mapCameraResolutions.set(s,[]),n=this._mapCameraResolutions.get(s);for(let e of this._predefinedResolutions){const t=await a(s,e.width,e.height);t&&!r(s,t)&&n.push([t.width,t.height])}return n}if(this._currentCamera){s=this._currentCamera.deviceId;let t=this._mapCameraResolutions.get(s);if(t&&!e)return this._mapCameraResolutions.get(s);this._mapCameraResolutions.set(s,[]),t=this._mapCameraResolutions.get(s);let i=this._videoTrack;for(let e of this._predefinedResolutions){await i.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const a=i.getSettings(),o={width:a.width,height:a.height};r(s,o)||t.push([o.width,o.height])}return this._video.srcObject.getTracks().forEach((e=>{e.stop()})),await this.play(s,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 s=i.indexOf(t);-1!==s&&i.splice(s,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=L(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 s=0,r=0;if(e.x.endsWith("px"))s=parseFloat(e.x);else{if(!e.x.endsWith("%"))throw new Error("Invalid scale center.");s=parseFloat(e.x)/100*t}if(e.y.endsWith("px"))r=parseFloat(e.y);else{if(!e.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(e.y)/100*i}if(NaN==s||NaN==r)throw new Error("Invalid scale center.");this._scaleCenter={x:s,y:r}}_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.");if(!this._videoTrack)return null;return this._getHardwareScale()*this._softwareScale}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;return{factor:this._getHardwareScale()*this._softwareScale}}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,s=this.getCapabilities().focusDistance;if(!i)throw Error("Not supported.");if(!i.includes(e))throw Error("Unsupported mode.");if(t>=0){if(!s)throw Error("Manual focus unsupported.");return ts.max&&(t=s.max),t=L(t,s.min,s.step,s.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(),s=i.focusMode,r=i.focusDistance;if(!s)throw Error("Not supported.");if("string"!=typeof e.mode)throw Error("Invalid focus mode.");const a=e.mode.toLowerCase();if(!s.includes(a))throw Error("Unsupported focus mode.");if("manual"!==a)return this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:a}]});if(!r)throw Error("Manual focus unsupported.");if(e.hasOwnProperty("distance")){let t=e.distance;return tr.max&&(t=r.max),t=L(t,r.min,r.step,r.max),this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:a,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,s=e.area.height;if(!i||!s){const e=this._video.videoWidth,t=this._video.videoHeight;i||(i=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),s||(s=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:s},await this._setLocalFocus(t,i,s)}}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 s;t=L(t,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:"manual",focusDistance:t}]}),i(e),s=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,s)})),i(e);let r=e.focusL-e.focusW/2,a=e.focusT-e.focusH/2,o=e.focusW,n=e.focusH;if(r>=this.video.videoWidth||a>=this.video.videoHeight)throw new Error("Invalid area.");r+o>this.video.videoWidth&&(o=this.video.videoWidth-r),a+n>this.video.videoHeight&&(n=this.video.videoHeight-a);const h=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:r,sy:a,sWidth:o,sHeight:n,dWidth:o,dHeight:n},null,{pixelFormat:E.RGBA});if(!h)return this._setFocusAndGetContract(e,t);const l=h.data;let d=0;for(let e=0,t=l.length-8;eo&&od)return await this._doFocusDetail(e,a,o,s,r,l,d)}else{let n=await this._setFocusAndGetContract(e,l);if(o>n)return await this._doFocusDetail(e,a,o,s,r,l,n);if(o==n)return await this._doFocusDetail(e,a,o,l,n);let d=await this._setFocusAndGetContract(e,h);if(d>o&&o{try{(null==t||tthis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let s=L(Math.sqrt(i*(t||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=L(Math.sqrt((t||this._focusParameters.fds.step)*s),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=L(Math.sqrt(s*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await this._setFocusAndGetContract(e,a),n=await this._setFocusAndGetContract(e,r),h=await this._setFocusAndGetContract(e,s);if(n>h&&ho&&n>o){let t=await this._setFocusAndGetContract(e,i);const r=await this._doFocusDetail(e,s,h,i,t,a,o);return this._focusParameters.isDoingFocus=0,r}if(n==h&&hh){const t=await this._doFocusDetail(e,s,h,a,o);return this._focusParameters.isDoingFocus=0,t}return g(e,t,i)}catch(e){if("DeprecatedTaskError"!==e.name)throw e}};return g(c,s,r)}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,s=window.getComputedStyle(this._elContainer),r=parseFloat(s.width),a=parseFloat(s.height),o=e/i;if(r/an?o/(i/e):a/(s/e));const d=l*(1-1/e)*(i/2-this._scaleCenter.x),c=l*(1-1/e)*(s/2-this._scaleCenter.y);this._video.style.transform=`translate(${d}px, ${c}px) scale(${e})`}this._updateVideoContainerStyle()}}getFrameSize(e,t,i,s){if(!e||!t)return null;let r,a,o,n,h=e,l=t;const d={regionLeft:0,regionTop:0,regionRight:h,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(d.regionLeft=i.regionLeft*h/100,d.regionTop=i.regionTop*l/100,d.regionRight=i.regionRight*h/100,d.regionBottom=i.regionBottom*l/100):(d.regionLeft=i.regionLeft,d.regionTop=i.regionTop,d.regionRight=i.regionRight,d.regionBottom=i.regionBottom),r=Math.round(d.regionLeft),a=Math.round(d.regionTop),h=Math.round(d.regionRight-d.regionLeft),l=Math.round(d.regionBottom-d.regionTop)):(r=0,a=0,h=Math.round(h),l=Math.round(l));const c=Math.max(h,l);if(s&&s>0&&c>s){const e=s/c;h>l?(o=s,n=Math.round(l*e)):(o=Math.round(h*e),n=s)}else o=h,n=l;return o<=0||n<=0?null:{sx:r,sy:a,sWidth:h,sHeight:l,dWidth:o,dHeight:n}}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,s,r,a,o){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!i||!s)return null;if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let n;I._onLog&&(n=Date.now(),I._onLog("DCE: _drawImage(), START: "+n));let h=0,l=0,d=i,c=s,g=0,u=0,_=i,f=s;r&&(r.sx&&(h=Math.round(r.sx)),r.sy&&(l=Math.round(r.sy)),r.sWidth&&(d=Math.round(r.sWidth)),r.sHeight&&(c=Math.round(r.sHeight)),r.dx&&(g=Math.round(r.dx)),r.dy&&(u=Math.round(r.dy)),r.dWidth&&(_=Math.round(r.dWidth)),r.dHeight&&(f=Math.round(r.dHeight)));let m=E.RGBA;o&&o.pixelFormat&&(m=o.pixelFormat);const p=e;if(o&&o.bUseWebGL){I._onLog&&I._onLog("DCE: _drawImage() in WebGL."),(p.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();e.bindBuffer(e.ARRAY_BUFFER,i);return 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},s=(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},r=(e,t,i)=>{const s=e.createShader(t);if(e.shaderSource(s,i),e.compileShader(s),!e.getShaderParameter(s,e.COMPILE_STATUS)){const t=new Error(`An error occured compiling the shader: ${e.getShaderInfoLog(s)}.`);throw t.name="WebGLError",t}return s},a="\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(m)&&(o=m.slice(0,3));const n=`\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=s(e,[r(e,e.VERTEX_SHADER,a),r(e,e.FRAGMENT_SHADER,n)]);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=m}const r=(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 s=e.RGBA,r=e.RGBA,a=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,s,r,a,i)},w=(e,t,a,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),r(e,a.positions,t.attribLocations.vertexPosition),r(e,a.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,[E.GREY,E.GREY32].includes(m)?1:0);let n,p,w=C.translate(C.identity(),-1,-1);w=C.scale(w,2,2),w=C.scale(w,1/e.canvas.width,1/e.canvas.height),n=C.translate(w,g,u),n=C.scale(n,_,f),e.uniformMatrix3fv(t.uniformLocations.uMatrix,!1,n),p=C.translate(C.identity(),h/i,l/s),p=C.scale(p,d/i,c/s),e.uniformMatrix3fv(t.uniformLocations.uTextureMatrix,!1,p),e.drawArrays(e.TRIANGLES,0,6)};let v;if(o(e,this._webGLTexture,t),w(e,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),a){if(a.length<_*f*4)throw new Error("Unexpected size of the 'bufferContainer'.");v=a}else v=new Uint8Array(_*f*4);if(e.readPixels(g,u,_,f,e.RGBA,e.UNSIGNED_BYTE,v),255!==v[3]){I._onLog&&I._onLog("DCE: WebGL drawing incorrect."),this._bWebGLSupported=!1;const e=new Error("WebGL error: incorrect WebGL drawing.");throw e.name="WebGLError",e}return I._onLog&&I._onLog("DCE: _drawImage() in WebGL end. Costs: "+(Date.now()-n)),{context:e,pixelFormat:m===E.GREY?E.GREY32:m,_bUseWebGL:!0}}{I._onLog&&I._onLog("DCE: _drawImage() in context2d."),p.ctx2d||(p.ctx2d=p.getContext("2d",{willReadFrequently:!0}));const e=p.ctx2d;if(!e)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(p.widtht||s.sy>i||s.sx+s.sWidth>t||s.sy+s.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;I._onLog&&(o=Date.now(),I._onLog("DCE: _getImageData(), START: "+o));const n=Math.round(s.sx),h=Math.round(s.sy),l=Math.round(s.sWidth),d=Math.round(s.sHeight),c=Math.round(s.dWidth),g=Math.round(s.dHeight);let u=E.RGBA;a&&a.pixelFormat&&(u=a.pixelFormat);let _,f,m,p=this._bWebGLSupported;a&&0==a.bUseWebGL&&(p=!1),p?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),_=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),_=this._reusedCvs);try{if(p)if(I._onLog&&I._onLog("DCE: _getImageData() in WebGL."),r)if(u===E.GREY){if(m=new Uint8Array(c*g*4),f=this._drawImage(_,e,t,i,{sx:n,sy:h,sWidth:l,sHeight:d,dWidth:c,dHeight:g},m,{pixelFormat:u,bUseWebGL:p}),m=this._transformPixelFormat(m,f.pixelFormat,u),r){if(r.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=()=>{I._onLog&&I._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(I._onLog&&I._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),I._onLog&&I._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()?(I._onLog&&I._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this._isSingleFrameModeEnabled())throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,I._onLog&&I._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(I._onLog&&I._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,s,r=3e3,a=!0){this._assertOpen(),this._tipArgs.x=e,this._tipArgs.y=t,this._tipArgs.width=i,this._tipArgs.autoShowSuggestedTip=!!a,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 v(s||"",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 S(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 s=this._cvsOriginalImage;s||(s=document.createElement("canvas"),s.style.position="absolute",s.style.width="100%",s.style.height="100%",s.style.left="0",s.style.top="0",s.style.backgroundColor="white",s.style.objectFit="contain",this._cvsOriginalImage=s),s.width===t&&s.height===i||(s.width=t,s.height=i);const r=s.getContext("2d");r.clearRect(0,0,s.width,s.height),e instanceof Uint8Array||e instanceof Uint8ClampedArray?(e instanceof Uint8Array&&(e=new Uint8ClampedArray(e.buffer)),r.putImageData(new ImageData(e,t,i),0,0)):e instanceof HTMLCanvasElement&&r.drawImage(e,0,0),document.body.contains(s)&&""===s.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,s,r,a,o,n=t.left,h=t.top,l=n+window.scrollX,d=h+window.scrollY;this._isSingleFrameModeEnabled()?(i=this._cvsSingleFrameMode.width,s=this._cvsSingleFrameMode.height,r=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).width),a=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,s=this.video.videoHeight,r=parseFloat(window.getComputedStyle(this._elContainer).width),a=parseFloat(window.getComputedStyle(this._elContainer).height),o=this.videoFit);const c=r/a,g=i/s;let u,_,f,m,p=1;if("contain"===o)c({x:t.x-e.left-e.width/2,y:t.y-e.top-e.height/2}))),e.addWithUpdate()}else s.points=i;const r=s.points.length-1;return s.controls=s.points.reduce((function(t,i,s){return t["p"+s]=new e.Control({positionHandler:u,actionHandler:m(s>0?s-1:r,f),actionName:"modifyPolygon",pointIndex:s}),t}),{}),s._setPositionDimensions({}),!0}}_extendGet(t){if("startPoint"===t||"endPoint"===t){const i=[],s=this._fabricObject;if(s.selectable&&!s.group)for(let e in s.oCoords)i.push({x:s.oCoords[e].x,y:s.oCoords[e].y});else for(let t of s.points){let r=t.x-s.pathOffset.x,a=t.y-s.pathOffset.y;const o=e.util.transformPoint({x:r,y:a},s.calcTransformMatrix());i.push({x:o.x,y:o.y})}return"startPoint"===t?i[0]:i[1]}}},DT_Group:class extends g{constructor(t){super(new e.Group(t.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()))}}};export{I as CameraEnhancer,x as DrawingItem}; +import{fabric as e}from"dm-fabric";const t="undefined"==typeof self;let i,s,r,a,o;if("undefined"!=typeof navigator&&(i=navigator,s=i.userAgent,r=i.platform,a=i.mediaDevices),!t){const e={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:i.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},t={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:r,search:"Win"},Mac:{str:r},Linux:{str:r}};let a="unknownBrowser",n=0,h="unknownOS";for(let t in e){const i=e[t]||{};let r=i.str||s,o=i.search||t,h=i.verStr||s,l=i.verSearch||t;if(l instanceof Array||(l=[l]),-1!=r.indexOf(o)){a=t;for(let e of l){let t=h.indexOf(e);if(-1!=t){n=parseFloat(h.substring(t+e.length+1));break}}break}}for(let e in t){const i=t[e]||{};let r=i.str||s,a=i.search||e;if(-1!=r.indexOf(a)){h=e;break}}"Linux"==h&&-1!=s.indexOf("Windows NT")&&(h="HarmonyOS"),o={browser:a,version:n,OS:h}}t&&(o={browser:"ssr",version:0,OS:"ssr"});const n="undefined"!=typeof WebAssembly&&s&&!(/Safari/.test(s)&&!/Chrome/.test(s)&&/\(.+\s11_2_([2-6]).*\)/.test(s)),h=!("undefined"==typeof Worker),l=!(!a||!a.getUserMedia),d=async()=>{let e=!1;if(l)try{(await a.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 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"./"})();class g{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(),s=this.mapEvent_Callbacks.get(i);if(!s)throw new Error(`Event '${e}' does not exist.`);let r=s.get(t);r||(r=e=>{const i=e.e;if(!i)return void(t&&t.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const s={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let e,t,r,a;const o=i.target.getBoundingClientRect();e=o.left,t=o.top,r=e+window.scrollX,a=t+window.scrollY;const n=this._drawingLayer.fabricCanvas.lowerCanvasEl.width,h=this._drawingLayer.fabricCanvas.lowerCanvasEl.height,l=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).width),d=parseFloat(window.getComputedStyle(this._drawingLayer.fabricCanvas.lowerCanvasEl).height),c=l/d,g=n/h,u=this._drawingLayer._getObjectFit();let _,f,m,p,w=1;if("contain"===u)c0?s-1:r,f),actionName:"modifyPolygon",pointIndex:s}),t}),{})}_extendSet(t,i){if("vertices"===t){const t=this._fabricObject;if(t.group){const e=t.group;t.points=i.map((t=>({x:t.x-e.left-e.width/2,y:t.y-e.top-e.height/2}))),e.addWithUpdate()}else t.points=i;const s=t.points.length-1;return t.controls=t.points.reduce((function(t,i,r){return t["p"+r]=new e.Control({positionHandler:u,actionHandler:m(r>0?r-1:s,f),actionName:"modifyPolygon",pointIndex:r}),t}),{}),t._setPositionDimensions({}),!0}}_extendGet(t){if("vertices"===t){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 s of i.points){let r=s.x-i.pathOffset.x,a=s.y-i.pathOffset.y;const o=e.util.transformPoint({x:r,y:a},i.calcTransformMatrix());t.push({x:o.x,y:o.y})}return t}}}const w=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 s=0;si&&(i=r.length))}if(-1===i)break;for(let s=0;s=e[s].length-1)continue;let r=" ".repeat(i+2-e[s][t].length);e[s][t]=e[s][t].concat(r)}}})(t),(e=>{let t="";for(let i=0;iw?(f=u,m=u/p,{x:a.x*s.width,y:(a.y-(_-m)/2)*s.width}):(f=_*p,m=_,{x:(a.x-(u-f)/2)*s.height,y:a.y*s.height}):"cover"===d?p>w?{x:(c-s.height*u)/2+a.x*s.height,y:a.y*s.height}:{x:a.x*s.width,y:(g-s.width*_)/2+a.y*s.width}:{x:a.x*s.width,y:a.y*s.height}}return s={width:1,height:1},{x:a.x*s.width,y:a.y*s.height}},e.Canvas.prototype._onTouchStart=function(t){var i=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),i&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var s=this.upperCanvasEl,r=this._getEventPrefix();e.util.addListener(e.document,"touchend",this._onTouchEnd,{passive:!1}),e.util.addListener(e.document,"touchmove",this._onMouseMove,{passive:!1}),e.util.removeListener(s,r+"down",this._onMouseDown)},e.Textbox.prototype._wrapLine=function(t,i,s,r){const a=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),o=!(!a||!a.length);var n=0,h=this.splitByGrapheme||o,l=[],d=[],c=h?e.util.string.graphemeSplit(t):t.split(this._wordJoiners),g="",u=0,_=h?"":" ",f=0,m=0,p=0,w=!0,v=this._getWidthOfCharSpacing();r=r||0;0===c.length&&c.push([]),s-=r;for(var y=0;ys&&!w?(l.push(d),d=[],n=f,w=!0):n+=v,w||h||d.push(_),d=d.concat(g),m=h?0:this._measureWord([_],i,u),u++,w=!1,f>p&&(p=f);return y&&l.push(d),p+r>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+r),l});class y{constructor(t,i,s,r){let a,o;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 e.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(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 s of t){const t=s.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 s of t){const t=s.getDrawingItem();t._drawingLayer===e&&i.push(t)}setTimeout((()=>{const t=[];for(let s of i)e.hasDrawingItem(s)&&t.push(s);t.length>0&&e.onSelectionChange&&e.onSelectionChange([],t)}),0)}})),this.fabricCanvas.on("selection:updated",(function(e){const t=e.selected,i=e.deselected,s=[];for(let e of t){const t=e.getDrawingItem()._drawingLayer;t&&!s.includes(t)&&s.push(t)}for(let e of i){const t=e.getDrawingItem()._drawingLayer;t&&!s.includes(t)&&s.push(t)}for(let e of s){const s=[],r=[];for(let i of t){const t=i.getDrawingItem();t._drawingLayer===e&&s.push(t)}for(let t of i){const i=t.getDrawingItem();i._drawingLayer===e&&r.push(i)}setTimeout((()=>{e.onSelectionChange&&e.onSelectionChange(s,r)}),0)}})),this.fabricCanvas.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas),this.id=i,this._mapDrawingStyles=s,i){case 1:a=s.get(1),o=s.get(5);break;case 2:a=s.get(2),o=s.get(6);break;case 3:a=s.get(3),o=s.get(7);break;default:a=s.get(4),o=s.get(8)}for(let e of g.arrMediaTypes)this.mapMediaType_Style.set(e,{default:a,selected:o})}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);const t=e._mapStyle.get(e.styleSelector);return t||null}_changeMediaTypeCurStyleInStyleSelector(e,t,i,s){let r;switch(e){case"rect":r=this.fabricCanvas.getObjects("rect");break;case"arc":r=this.fabricCanvas.getObjects("circle");break;case"polygon":r=this.fabricCanvas.getObjects("polygon");break;case"image":r=this.fabricCanvas.getObjects("image");break;case"text":r=this.fabricCanvas.getObjects("textbox");break;case"line":r=this.fabricCanvas.getObjects("line");break;case"path":r=this.fabricCanvas.getObjects("path")}for(let e of r){if(!this._arrFabricObject.includes(e))continue;const s=e.getDrawingItem();s.styleSelector===t&&this._changeItemStyle(s,i,!0)}s||this.fabricCanvas.renderAll()}_changeItemStyle(e,t,i){if(!e||!t)return;const s=e._getFabricObject();"number"==typeof e.styleId&&(t=this._getDrawingStyle(e.styleId)),s.strokeWidth=t.lineWidth,"fill"===t.paintMode?(s.fill=t.fillStyle,s.stroke=t.fillStyle):"stroke"===t.paintMode?(s.fill="transparent",s.stroke=t.strokeStyle):"strokeAndFill"===t.paintMode&&(s.fill=t.fillStyle,s.stroke=t.strokeStyle),s.fontFamily&&(s.fontFamily=t.fontFamily),s.fontSize&&(s.fontSize=t.fontSize),s.group||(s.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(e,t,i){if(!e||!t)return;const s=e.getChildItems();if("add"===i){if(s.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 s=()=>{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",s),t._on("deselected",r),t._funcChangeStyleToSelected=s,t._funcChangeStyleToDefault=r}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,i,!0)}e._fabricObject.addWithUpdate(t._getFabricObject())}else{if("remove"!==i)return;if(!s.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 s=this.fabricCanvas.getObjects();let r,a;if(s.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===e._mediaType){r=e.getChildItems();for(let e of r)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(r){for(let e of r){const t=this.mapMediaType_Style.get(e._mediaType);for(let i of g.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)a=this._getDrawingStyle(e.styleId);else{a=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected,!0)},s=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default,!0)};e._on("selected",i),e._on("deselected",s),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,a,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const t=this.mapMediaType_Style.get(e._mediaType);for(let i of g.arrStyleSelectors)e._mapStyle.set(i,t[i]);if(e.styleId)a=this._getDrawingStyle(e.styleId);else{a=t.default;const i=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).selected)},s=()=>{this._changeItemStyle(e,this.mapMediaType_Style.get(e._mediaType).default)};e._on("selected",i),e._on("deselected",s),e._funcChangeStyleToSelected=i,e._funcChangeStyleToDefault=s}this._changeItemStyle(e,a)}e._zIndex=this.id,e._drawingLayer=this,e._drawingLayerId=this.id;const o=this._arrFabricObject.length;let n=s.length;if(o)n=s.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 s=new y(e,t,this._mapDrawingStyles,{enableRetinaScaling:!1});return s._manager=this,this._arrDrawingLayer.push(s),this._switchPointerEvent(),s}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 S{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,s){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");s&&(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,s){if(!this._arrUsers.includes(e))throw new Error("Unregistered user.");return i||(i=[]),s?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 s=i.indexOf(t);-1!==s&&i.splice(s,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 C{static multiply(e,t){const i=[];for(let s=0;s<3;s++){const r=t.slice(3*s,3*s+3);for(let t=0;t<3;t++){const s=[e[t],e[t+3],e[t+6]].reduce(((e,t,i)=>e+t*r[i]),0);i.push(s)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(e,t,i){return C.multiply(e,[1,0,0,0,1,0,t,i,1])}static rotate(e,t){var i=Math.cos(t),s=Math.sin(t);return C.multiply(e,[i,-s,0,s,i,0,0,0,1])}static scale(e,t,i){return C.multiply(e,[t,0,0,0,i,0,0,0,1])}}var L;!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"}(L||(L={}));const E=(e,t,i,s)=>{let r=t+Math.round((e-t)/i)*i;return s&&(r=Math.min(r,s)),r};class I{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 s;return t||(i=await(s=e,new Promise(((e,t)=>{let i=URL.createObjectURL(s),r=new Image;r.dbrObjUrl=i,r.src=i,r.onload=()=>{e(r)},r.onerror=e=>{t(new Error("Can't convert blob to image : "+(e instanceof Event?e.type:e)))}})))),i})(t),s=i instanceof HTMLImageElement?i.naturalWidth:i.width,r=i instanceof HTMLImageElement?i.naturalHeight:i.height;this._imgWidth=s,this._imgHeight=r;const a=e=>{const t=Date.now();if(0===s||0===r)return null;if(e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");const i=this._scanRegion,a=this.getFrameSize(s,r,i,this.maxCvsSideLength);if(!a)return null;let o=!0;s===a.sWidth&&r===a.sHeight&&(o=!1);const n=this.mapPixelFormatString_Enum.get(this.framePixelFormat.toLowerCase()),h={data:null,region:i?JSON.parse(JSON.stringify(i)):null,sx:a.sx,sy:a.sy,width:a.dWidth,height:a.dHeight,colorMode:null,pixelFormat:null,timeSpent:null,timeStamp:null,isCropped:o,toCanvas:this._toCanvas,_sWidth:a.sWidth,_sHeight:a.sHeight,_bUseWebGL:null},l=this._getImageData(e,s,r,a,null,{pixelFormat:n});if(!l)return null;const d=Date.now();if(I._onLog&&I._onLog("DCE: _getVideoData(region?) END: "+d),h.data=l.data,h.pixelFormat=h.colorMode=l.pixelFormat,h._bUseWebGL=l._bUseWebGL,h.timeSpent=d-t,h.timeStamp=d,l.pixelFormat===L.GREY)h.stride=h.width;else h.stride=4*h.width;return 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==s&&t.height==r||(t.width=s,t.height=r);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=a(i)}catch(e){throw e}const n=this.mapCameraEvents.get("singleframeacquired");for(let e of n)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",L.GREY],["grey32",L.GREY32],["rgba",L.RGBA],["rbga",L.RBGA],["grba",L.GRBA],["gbra",L.GBRA],["brga",L.BRGA],["bgra",L.BGRA]]),this.shaderPixelFormat=L.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,s,r;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 a=this.getVideoFit(),o=this._video.videoWidth,n=this._video.videoHeight,h=this._elContainer.getBoundingClientRect(),l=h.left,d=h.top,c=window.getComputedStyle(this._elContainer),g=parseFloat(c.width),u=parseFloat(c.height),_=g/u,f=o/n;let m=1;if("contain"===a)if(f>_){m=g/o,s=(t-l)/m;r=(i-d-(u-g/f)/2)/m}else{m=u/n,r=(i-d)/m;s=(t-l-(g-u*f)/2)/m}else{if("cover"!==a)throw new Error("Unsupported object-fit.");if(f>_){m=u/n,r=(i-d)/m;s=(t-l+(u*f-g)/2)/m}else{m=g/o,s=(t-l)/m;r=(i-d+(g/f-u)/2)/m}}const p={x:s+"px",y:r+"px"},w=2*Math.round(Math.min(o,n)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",v=w;await this._setLocalFocus(p,w,v,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;e.width=this.width,e.height=this.height;if("grey"===(this.pixelFormat||this.colorMode)){t=new Uint8ClampedArray(this.width*this.height*4);for(let e=0;e{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let e,t;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];e=i.getAttribute("data-width"),t=i.getAttribute("data-height")}await this.setResolution(e,t),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this._isSingleFrameModeEnabled())if("visible"===document.visibilityState){if(I._onLog&&I._onLog("DCE: document visible."),this._bOpen&&this._vc_bPlayingVideoBeforeHide)if(this.videoSrc)this._video.play();else if(this._video.srcObject){const e=this._video.srcObject.getTracks()[0];this._video.srcObject.active&&e&&!e.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(I._onLog&&I._onLog("DCE: document hidden."),["iPhone","iPad","Mac"].includes(o.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let e of this._arrScanRegionOverlays)e&&(e.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let e of this._arrScanRegionOverlays)e&&(e.style.display="",this._updateScanRegionOverlay(e));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this._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:n,worker:h,getUserMedia:l,camera:await d(),browser:o.browser,version:o.version,OS:o.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");I._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 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){I._defaultUIElementURL=e}static get defaultUIElementURL(){var e;return null===(e=I._defaultUIElementURL)||void 0===e?void 0:e.replace("@engineResourcePath/",I.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,s,r;if(this._isSingleFrameModeEnabled()?(i=this._imgWidth,s=this._imgHeight,r="contain"):(i=null===(e=this._video)||void 0===e?void 0:e.videoWidth,s=null===(t=this._video)||void 0===t?void 0:t.videoHeight,r=this.getVideoFit()),!i||!s)throw new Error("Invalid content dimensions.");return{width:i,height:s,objectFit:r}}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:s,objectFit:r}=t;if(i<=0||s<=0)return e.width=0,void(e.height=0);const a=this._getRegionInPixels(i,s,this._scanRegion),o=this.getFrameSize(i,s,this._scanRegion,this.maxCvsSideLength),n=o.dWidth,h=o.dHeight;e.width==n&&e.height==h||(e.width=n,e.height=h);const l=window.getComputedStyle(this._elContainer),d=parseFloat(l.width),c=parseFloat(l.height),g=d/c,u=i/s;let _,f,m,p,w=1;"contain"===r?(u>g?(w=d/i,_=0,f=(c-s*w)/2):(w=c/s,_=(d-i*w)/2,f=0),_+=a.regionLeft*w,f+=a.regionTop*w,m=(a.regionRight-a.regionLeft)*w,p=(a.regionBottom-a.regionTop)*w):"cover"===r?(u>g?(w=c/s,_=a.regionLeft*w-(i*w-d)/2,f=a.regionTop*w):(w=d/i,_=a.regionLeft*w,f=a.regionTop*w-(s*w-c)/2),m=(a.regionRight-a.regionLeft)*w,p=(a.regionBottom-a.regionTop)*w):(_=0,f=0,m=0,p=0),e.style.position="absolute",e.style.left=_+"px",e.style.top=f+"px",e.style.width=m+"px",e.style.height=p+"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 s=["rectangle","focus"],r=["crossline","crosshair"];let a=!1,o=!1;for(let e of i)e=e.toLowerCase(),s.includes(e)&&!a&&(a=!0,this._decoratorType.push(e)),r.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 s=i.regionRight-i.regionLeft,r=i.regionBottom-i.regionTop;if(t.width==s&&t.height==r||(t.width=s,t.height=r),s<=0||r<=0)return;const a=t.getContext("2d");a.clearRect(0,0,t.width,t.height);const o=this._decoratorArea.x/100*s,n=this._decoratorArea.y/100*r,h=this._decoratorArea.width/100*s,l=this._decoratorArea.height/100*r;for(let e of this._decoratorType){if("rectangle"===e){a.fillStyle=this._viewDecoratorInfo.rectangle.maskFillStyle,a.fillRect(0,0,t.width,t.height),a.clearRect(Math.round(o),Math.round(n),Math.round(h),Math.round(l)),a.fillStyle=this._viewDecoratorInfo.rectangle.fillStyle,a.fillRect(Math.round(o),Math.round(n),Math.round(h),Math.round(l)),a.lineWidth=this._viewDecoratorInfo.rectangle.lineWidth,a.strokeStyle=this._viewDecoratorInfo.rectangle.strokeStyle;const e=a.lineWidth/2;a.strokeRect(Math.round(o-e),Math.round(n-e),Math.round(h+a.lineWidth),Math.round(l+a.lineWidth))}if("focus"===e){a.fillStyle=this._viewDecoratorInfo.focus.maskFillStyle,a.fillRect(0,0,t.width,t.height),a.clearRect(Math.round(o),Math.round(n),Math.round(h),Math.round(l)),a.fillStyle=this._viewDecoratorInfo.focus.fillStyle,a.fillRect(Math.round(o),Math.round(n),Math.round(h),Math.round(l)),a.lineWidth=this._viewDecoratorInfo.focus.lineWidth,a.strokeStyle=this._viewDecoratorInfo.focus.strokeStyle;const e=a.lineWidth/2,i=[0,.25,.75,1],s=[0,.25,.75,1];a.beginPath();for(let e=0;e{const e=parseFloat(window.getComputedStyle(this._elContainer).width),t=parseFloat(window.getComputedStyle(this._elContainer).height);let a,o={regionBottom:s,regionRight:i,regionLeft:0,regionTop:0,regionMeasuredByPercentage:!1};return"cover"===r?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 I;("string"==typeof e||e instanceof String)&&(e=JSON.parse(e));for(let i in e)t[i]=e[i];return this._hasEngineResourceLoaded=!0,I.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{I.onWarning&&I.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((()=>{I.onWarning&&I.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 b,t}static async playVideo(e,t,i){return new Promise(((s,r)=>{e||r(new Error("Invalid video element.")),t||r(new Error("Invalid source.")),e.onloadedmetadata=async()=>{e.onloadedmetadata=null,await e.play(),s(e)},"string"==typeof t||t instanceof String?e.src=t:e.srcObject=t,void 0!==i&&setTimeout((()=>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"],s=["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"],r=e.filter((e=>{const i=e.label.toLowerCase();return t.some((e=>i.includes(e)))}));if(!r.length)return null;const a=r.find((e=>{const t=e.label.toLowerCase();return i.some((e=>t.includes(e)))}));if(a)return a.deviceId;const o=r.find((e=>{const t=e.label.toLowerCase();return s.some((e=>t.includes(e)))}));return o?o.deviceId:r[0].deviceId}static findBestRearCamera(e){if(!e||!e.length)return null;if(["iPhone","iPad","Mac"].includes(o.OS))return I.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(o.OS)?e[e.length-1].deviceId:null}_isSingleFrameModeEnabled(){return 0!=this.singleFrameMode}async play(e,t,i,s){let r;if(this._video&&this.videoSrc){I._onLog&&(r=Date.now(),I._onLog("DCE: start loading static video: "+r));const e=await I.playVideo(this._video,this.videoSrc,4e3);if(I._onLog&&I._onLog("DCE: finish loading static video. Costs: "+(Date.now()-r)),!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 s&&s.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 a=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,a{var r;try{this._video&&this._video.srcObject&&this.stop(),I._onLog&&I._onLog("DCE: ======before video========");const a=()=>{if(!this._video)throw l&&l.getTracks().forEach((e=>{e.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},n=this.getVideoSettings();let h,l;if("boolean"==typeof n.video&&(n.video={}),e)delete n.video.facingMode,n.video.deviceId={exact:e};else if(n.video.deviceId);else if(this._lastDeviceId)delete n.video.facingMode,n.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&I.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete n.video.facingMode,n.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&&(n.video.width=e,n.video.height=t)}else if(this.ifSkipCameraInspection);else if(n.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let e=n.video.facingMode;if(e instanceof Array&&e.length&&(e=e[0]),e=e.exact||e.ideal||e,"environment"===e){h=!0;const e=I.findBestRearCamera(this._allCameras);e&&(delete n.video.facingMode,n.video.deviceId={exact:e})}}t&&(n.video.width={ideal:t}),i&&(n.video.height={ideal:i}),I._onLog&&I._onLog("DCE: ======try getUserMedia========");let d=[0,500],c=null;const g=async e=>{for(let t of d){t&&await new Promise((e=>setTimeout(e,t))),a();try{I._onLog&&I._onLog("DCE: ask "+JSON.stringify(e)),l=await navigator.mediaDevices.getUserMedia(e);break}catch(e){if(a(),"NotFoundError"===e.name||"NotAllowedError"===e.name)throw e;c=e,I._onLog&&I._onLog("DCE: "+e.message||e)}}a()};let u;if(await g(n),!l){if(I._onLog&&I._onLog("DCE: ======try getUserMedia again========"),u=JSON.parse(JSON.stringify(n)),"object"==typeof u.video){["iPhone","iPad"].includes(o.OS)?(t>=1280||i>=1280?u.video.width=1280:t>=640||i>=640?u.video.width=640:(t<640||i<640)&&(u.video.width=320),delete u.video.height):h&&!n.video.deviceId?(delete u.video.facingMode,this._allCameras.length&&(u.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):u.video=!0}I._onLog&&I._onLog("DCE: "+u),await g(u)}if(l||(d=[1e3,2e3],await g(n)),l||await g(u),!l)throw c;const _=()=>{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 s of this._allCameras)if(e.deviceId===s.deviceId){s._checked=!0,s.label=t.label,i=s;break}}this._currentCamera=i};if(await this.getAllCameras(!1),a(),h&&!this.ifSkipCameraInspection){_();const e=I.findBestRearCamera(this._allCameras),t=null===(r=this._currentCamera)||void 0===r?void 0:r.deviceId;e&&e!=t&&(l.getTracks().forEach((e=>{e.stop()})),d=[0,500,1e3,2e3],n.video.deviceId={exact:e},await g(n))}I._onLog&&I._onLog("DCE: ======play video========"),a(),await I.playVideo(this._video,l,4e3),a(),I._onLog&&I._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const f=this._video.videoWidth+"x"+this._video.videoHeight;this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",this._video.videoWidth),this._optGotRsl.setAttribute("data-height",this._video.videoHeight),this._optGotRsl.innerText=f,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),I._onLog&&I._onLog("DCE: got "+f),_(),this._renderSelCameraInfo();const m={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(m.deviceId&&(this._lastDeviceId=m.deviceId,this.ifSaveLastUsedCamera&&I.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),n.video.width&&n.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(n.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(n.video.height))))),!s||!s.notTriggerPlayedEvent){const e=this.mapCameraEvents.get("played");for(let t of e){if(!t)continue;const e=JSON.parse(JSON.stringify(m));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return this.promisePlay=null,m}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}})(),I._onLog&&(r=Date.now(),I._onLog("DCE: start opening camera: "+r));const n=await this.promisePlay;return I._onLog&&I._onLog("DCE: finish opening camera. Costs: "+(Date.now()-r)),this.playCallbackInfo=JSON.parse(JSON.stringify(n)),this._recordedStates.videoPlaying=!0,n}async resume(){this._assertOpen(),this._video&&(await this._video.play(),this._recordedStates.videoPlaying=!0),this.ifShowScanRegionLaser&&this.showScanRegionLaser()}pause(){this._assertOpen(),this._video&&(this._video.pause(),this._recordedStates.videoPlaying=!1),this.ifShowScanRegionLaser&&this.hideScanRegionLaser()}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','','',''].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 e of this.extraBindings)try{e(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(o.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(I.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&&(I._onLog&&I._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&&(I._onLog&&I._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=[],s=[];if(this._allCameras)for(let e of this._allCameras)e._checked&&s.push(e);for(let e=0;e{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}if(s!==a.width||r!==a.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(a));setTimeout((()=>{this.isDisposed&&this.disposed||t.apply(this,[e])}),0)}}return a}getResolution(){if(this._bOpen)return[this._video.videoWidth,this._video.videoHeight];{let e=0,t=0;const i=this.videoSettings.video.width,s=this.videoSettings.video.height;return i&&(e=i.exact||i.ideal||i),s&&(t=s.exact||s.ideal||s),[e,t]}}async setResolution(e,t){let i,s;if(e instanceof Array?(i=e[0],s=e[1]):(i=e,s=t),this.videoSettings.video.width={ideal:i},this.videoSettings.video.height={ideal:s},!this._bOpen||this._video.paused)return null;const r=this._video.videoWidth,a=this._video.videoHeight,o=await this.play(null,i,s);if(r!==o.width||a!==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 s="";const r=(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},a=async(e,t,i)=>{const s={video:{deviceId:{exact:e},width:{ideal:t},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(s)}catch(e){return null}if(!r)return null;const a=r.getVideoTracks();let o=null;try{const e=a[0].getSettings();o={width:e.width,height:e.height}}catch(e){const t=document.createElement("video");t.srcObject=r,o={width:t.videoWidth,height:t.videoHeight},t.srcObject=null}return a.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(s=o.hasOwnProperty("exact")?this.videoSettings.video.deviceId.exact:o.hasOwnProperty("ideal")?this.videoSettings.video.deviceId.ideal:this.videoSettings.video.deviceId,!s)return null;let n=this._mapCameraResolutions.get(s);if(n&&!e)return this._mapCameraResolutions.get(s);this._mapCameraResolutions.set(s,[]),n=this._mapCameraResolutions.get(s);for(let e of this._predefinedResolutions){const t=await a(s,e.width,e.height);t&&!r(s,t)&&n.push([t.width,t.height])}return n}if(this._currentCamera){s=this._currentCamera.deviceId;let t=this._mapCameraResolutions.get(s);if(t&&!e)return this._mapCameraResolutions.get(s);this._mapCameraResolutions.set(s,[]),t=this._mapCameraResolutions.get(s);let i=this._videoTrack;for(let e of this._predefinedResolutions){await i.applyConstraints({width:{ideal:e.width},height:{ideal:e.height}});const a=i.getSettings(),o={width:a.width,height:a.height};r(s,o)||t.push([o.width,o.height])}return this._video.srcObject.getTracks().forEach((e=>{e.stop()})),await this.play(s,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 s=i.indexOf(t);-1!==s&&i.splice(s,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=E(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 s=0,r=0;if(e.x.endsWith("px"))s=parseFloat(e.x);else{if(!e.x.endsWith("%"))throw new Error("Invalid scale center.");s=parseFloat(e.x)/100*t}if(e.y.endsWith("px"))r=parseFloat(e.y);else{if(!e.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(e.y)/100*i}if(NaN==s||NaN==r)throw new Error("Invalid scale center.");this._scaleCenter={x:s,y:r}}_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.");if(!this._videoTrack)return null;return this._getHardwareScale()*this._softwareScale}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;return{factor:this._getHardwareScale()*this._softwareScale}}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,s=this.getCapabilities().focusDistance;if(!i)throw Error("Not supported.");if(!i.includes(e))throw Error("Unsupported mode.");if(t>=0){if(!s)throw Error("Manual focus unsupported.");return ts.max&&(t=s.max),t=E(t,s.min,s.step,s.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(),s=i.focusMode,r=i.focusDistance;if(!s)throw Error("Not supported.");if("string"!=typeof e.mode)throw Error("Invalid focus mode.");const a=e.mode.toLowerCase();if(!s.includes(a))throw Error("Unsupported focus mode.");if("manual"!==a)return this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:a}]});if(!r)throw Error("Manual focus unsupported.");if(e.hasOwnProperty("distance")){let t=e.distance;return tr.max&&(t=r.max),t=E(t,r.min,r.step,r.max),this._focusParameters._focusArea=null,await this._videoTrack.applyConstraints({advanced:[{focusMode:a,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,s=e.area.height;if(!i||!s){const e=this._video.videoWidth,t=this._video.videoHeight;i||(i=2*Math.round(Math.min(e,t)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),s||(s=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:s},await this._setLocalFocus(t,i,s)}}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 s;t=E(t,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await this._videoTrack.applyConstraints({advanced:[{focusMode:"manual",focusDistance:t}]}),i(e),s=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,s)})),i(e);let r=e.focusL-e.focusW/2,a=e.focusT-e.focusH/2,o=e.focusW,n=e.focusH;if(r>=this.video.videoWidth||a>=this.video.videoHeight)throw new Error("Invalid area.");r+o>this.video.videoWidth&&(o=this.video.videoWidth-r),a+n>this.video.videoHeight&&(n=this.video.videoHeight-a);const h=this._getImageData(this.video,this.video.videoWidth,this.video.videoHeight,{sx:r,sy:a,sWidth:o,sHeight:n,dWidth:o,dHeight:n},null,{pixelFormat:L.RGBA});if(!h)return this._setFocusAndGetContract(e,t);const l=h.data;let d=0;for(let e=0,t=l.length-8;eo&&od)return await this._doFocusDetail(e,a,o,s,r,l,d)}else{let n=await this._setFocusAndGetContract(e,l);if(o>n)return await this._doFocusDetail(e,a,o,s,r,l,n);if(o==n)return await this._doFocusDetail(e,a,o,l,n);let d=await this._setFocusAndGetContract(e,h);if(d>o&&o{try{(null==t||tthis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let s=E(Math.sqrt(i*(t||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=E(Math.sqrt((t||this._focusParameters.fds.step)*s),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=E(Math.sqrt(s*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),o=await this._setFocusAndGetContract(e,a),n=await this._setFocusAndGetContract(e,r),h=await this._setFocusAndGetContract(e,s);if(n>h&&ho&&n>o){let t=await this._setFocusAndGetContract(e,i);const r=await this._doFocusDetail(e,s,h,i,t,a,o);return this._focusParameters.isDoingFocus=0,r}if(n==h&&hh){const t=await this._doFocusDetail(e,s,h,a,o);return this._focusParameters.isDoingFocus=0,t}return g(e,t,i)}catch(e){if("DeprecatedTaskError"!==e.name)throw e}};return g(c,s,r)}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,s=window.getComputedStyle(this._elContainer),r=parseFloat(s.width),a=parseFloat(s.height),o=e/i;if(r/an?o/(i/e):a/(s/e));const d=l*(1-1/e)*(i/2-this._scaleCenter.x),c=l*(1-1/e)*(s/2-this._scaleCenter.y);this._video.style.transform=`translate(${d}px, ${c}px) scale(${e})`}this._updateVideoContainerStyle()}}getFrameSize(e,t,i,s){if(!e||!t)return null;let r,a,o,n,h=e,l=t;const d={regionLeft:0,regionTop:0,regionRight:h,regionBottom:l,regionMeasuredByPercentage:!1};i?(i.regionMeasuredByPercentage?(d.regionLeft=i.regionLeft*h/100,d.regionTop=i.regionTop*l/100,d.regionRight=i.regionRight*h/100,d.regionBottom=i.regionBottom*l/100):(d.regionLeft=i.regionLeft,d.regionTop=i.regionTop,d.regionRight=i.regionRight,d.regionBottom=i.regionBottom),r=Math.round(d.regionLeft),a=Math.round(d.regionTop),h=Math.round(d.regionRight-d.regionLeft),l=Math.round(d.regionBottom-d.regionTop)):(r=0,a=0,h=Math.round(h),l=Math.round(l));const c=Math.max(h,l);if(s&&s>0&&c>s){const e=s/c;h>l?(o=s,n=Math.round(l*e)):(o=Math.round(h*e),n=s)}else o=h,n=l;return o<=0||n<=0?null:{sx:r,sy:a,sWidth:h,sHeight:l,dWidth:o,dHeight:n}}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,s,r,a,o){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(!i||!s)return null;if(t instanceof HTMLVideoElement&&4!==t.readyState||t instanceof HTMLImageElement&&!t.complete)throw new Error("The source is not loaded.");let n;I._onLog&&(n=Date.now(),I._onLog("DCE: _drawImage(), START: "+n));let h=0,l=0,d=i,c=s,g=0,u=0,_=i,f=s;r&&(r.sx&&(h=Math.round(r.sx)),r.sy&&(l=Math.round(r.sy)),r.sWidth&&(d=Math.round(r.sWidth)),r.sHeight&&(c=Math.round(r.sHeight)),r.dx&&(g=Math.round(r.dx)),r.dy&&(u=Math.round(r.dy)),r.dWidth&&(_=Math.round(r.dWidth)),r.dHeight&&(f=Math.round(r.dHeight)));let m=L.RGBA;o&&o.pixelFormat&&(m=o.pixelFormat);const p=e;if(!o||!o.bUseWebGL){I._onLog&&I._onLog("DCE: _drawImage() in context2d."),p.ctx2d||(p.ctx2d=p.getContext("2d",{willReadFrequently:!0}));const e=p.ctx2d;if(!e)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(p.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();e.bindBuffer(e.ARRAY_BUFFER,i);return 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},s=(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},r=(e,t,i)=>{const s=e.createShader(t);if(e.shaderSource(s,i),e.compileShader(s),!e.getShaderParameter(s,e.COMPILE_STATUS)){const t=new Error(`An error occured compiling the shader: ${e.getShaderInfoLog(s)}.`);throw t.name="WebGLError",t}return s},a="\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(m)&&(o=m.slice(0,3));const n=`\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,e.VERTEX_SHADER,a),l=s(e,[h,r(e,e.FRAGMENT_SHADER,n)]);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=m}const r=(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 s=e.RGBA,r=e.RGBA,a=e.UNSIGNED_BYTE;e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,s,r,a,i)},w=(e,t,a,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),r(e,a.positions,t.attribLocations.vertexPosition),r(e,a.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,[L.GREY,L.GREY32].includes(m)?1:0);let n,p,w=C.translate(C.identity(),-1,-1);w=C.scale(w,2,2),w=C.scale(w,1/e.canvas.width,1/e.canvas.height),n=C.translate(w,g,u),n=C.scale(n,_,f),e.uniformMatrix3fv(t.uniformLocations.uMatrix,!1,n),p=C.translate(C.identity(),h/i,l/s),p=C.scale(p,d/i,c/s),e.uniformMatrix3fv(t.uniformLocations.uTextureMatrix,!1,p),e.drawArrays(e.TRIANGLES,0,6)};let v;if(o(e,this._webGLTexture,t),w(e,this._webGLProgramInfo,this._webGLBuffers,this._webGLTexture),a){if(a.length<_*f*4)throw new Error("Unexpected size of the 'bufferContainer'.");v=a}else v=new Uint8Array(_*f*4);if(e.readPixels(g,u,_,f,e.RGBA,e.UNSIGNED_BYTE,v),255!==v[3]){I._onLog&&I._onLog("DCE: WebGL drawing incorrect."),this._bWebGLSupported=!1;const e=new Error("WebGL error: incorrect WebGL drawing.");throw e.name="WebGLError",e}return I._onLog&&I._onLog("DCE: _drawImage() in WebGL end. Costs: "+(Date.now()-n)),{context:e,pixelFormat:m===L.GREY?L.GREY32:m,_bUseWebGL:!0}}catch(e){throw this._bWebGLSupported=!1,e.name="WebGLError",e}}_readCvsData(e,t,i){let s,r=0,a=0,o=e.canvas.width,n=e.canvas.height;if(t&&(t.x&&(r=t.x),t.y&&(a=t.y),t.width&&(o=t.width),t.height&&(n=t.height)),e instanceof WebGLRenderingContext){const t=e;if(i){if(i.lengtht||s.sy>i||s.sx+s.sWidth>t||s.sy+s.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;I._onLog&&(o=Date.now(),I._onLog("DCE: _getImageData(), START: "+o));const n=Math.round(s.sx),h=Math.round(s.sy),l=Math.round(s.sWidth),d=Math.round(s.sHeight),c=Math.round(s.dWidth),g=Math.round(s.dHeight);let u=L.RGBA;a&&a.pixelFormat&&(u=a.pixelFormat);let _,f,m,p=this._bWebGLSupported;a&&0==a.bUseWebGL&&(p=!1),p?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),_=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),_=this._reusedCvs);try{if(p)if(I._onLog&&I._onLog("DCE: _getImageData() in WebGL."),r)if(u===L.GREY){if(m=new Uint8Array(c*g*4),f=this._drawImage(_,e,t,i,{sx:n,sy:h,sWidth:l,sHeight:d,dWidth:c,dHeight:g},m,{pixelFormat:u,bUseWebGL:p}),m=this._transformPixelFormat(m,f.pixelFormat,u),r){if(r.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=()=>{I._onLog&&I._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(I._onLog&&I._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),I._onLog&&I._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()?(I._onLog&&I._onLog("DCE: second timeout executes: "+Date.now()),t(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};e&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(t(),i()):0===this.refreshInterval?t():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this._isSingleFrameModeEnabled())throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,I._onLog&&I._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(I._onLog&&I._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,s,r=3e3,a=!0){this._assertOpen(),this._tipArgs.x=e,this._tipArgs.y=t,this._tipArgs.width=i,this._tipArgs.autoShowSuggestedTip=!!a,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 v(s||"",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 S(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 s=this._cvsOriginalImage;s||(s=document.createElement("canvas"),s.style.position="absolute",s.style.width="100%",s.style.height="100%",s.style.left="0",s.style.top="0",s.style.backgroundColor="white",s.style.objectFit="contain",this._cvsOriginalImage=s),s.width===t&&s.height===i||(s.width=t,s.height=i);const r=s.getContext("2d");r.clearRect(0,0,s.width,s.height),e instanceof Uint8Array||e instanceof Uint8ClampedArray?(e instanceof Uint8Array&&(e=new Uint8ClampedArray(e.buffer)),r.putImageData(new ImageData(e,t,i),0,0)):e instanceof HTMLCanvasElement&&r.drawImage(e,0,0),document.body.contains(s)&&""===s.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,s,r,a,o,n=t.left,h=t.top,l=n+window.scrollX,d=h+window.scrollY;this._isSingleFrameModeEnabled()?(i=this._cvsSingleFrameMode.width,s=this._cvsSingleFrameMode.height,r=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).width),a=parseFloat(window.getComputedStyle(this._cvsSingleFrameMode).height),o="contain"):(i=this.video.videoWidth,s=this.video.videoHeight,r=parseFloat(window.getComputedStyle(this._elContainer).width),a=parseFloat(window.getComputedStyle(this._elContainer).height),o=this.videoFit);const c=r/a,g=i/s;let u,_,f,m,p=1;if("contain"===o)c({x:t.x-e.left-e.width/2,y:t.y-e.top-e.height/2}))),e.addWithUpdate()}else s.points=i;const r=s.points.length-1;return s.controls=s.points.reduce((function(t,i,s){return t["p"+s]=new e.Control({positionHandler:u,actionHandler:m(s>0?s-1:r,f),actionName:"modifyPolygon",pointIndex:s}),t}),{}),s._setPositionDimensions({}),!0}}_extendGet(t){if("startPoint"===t||"endPoint"===t){const i=[],s=this._fabricObject;if(s.selectable&&!s.group)for(let e in s.oCoords)i.push({x:s.oCoords[e].x,y:s.oCoords[e].y});else for(let t of s.points){let r=t.x-s.pathOffset.x,a=t.y-s.pathOffset.y;const o=e.util.transformPoint({x:r,y:a},s.calcTransformMatrix());i.push({x:o.x,y:o.y})}return"startPoint"===t?i[0]:i[1]}}},DT_Group:class extends g{constructor(t){super(new e.Group(t.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()))}}};export{I as CameraEnhancer,x as DrawingItem}; diff --git a/dist/dce.js b/dist/dce.js index 5936269..4fae082 100644 --- a/dist/dce.js +++ b/dist/dce.js @@ -4,8 +4,8 @@ * @website https://www.dynamsoft.com * @copyright Copyright 2023, Dynamsoft Corporation * @author Dynamsoft - * @version 3.3.7 (js 20231010) + * @version 3.3.8 (js 20231011) * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft=t.Dynamsoft||{},t.Dynamsoft.DCE={}))}(this,(function(t){"use strict";var e={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,p,m,v,_,y,b,w,C,S,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 O(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 E(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),p=g.vector,m=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(m/2),f=new x.Point(p.x*d*s.x,p.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(p.x*d*s.x,p.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,p=-d*t*.5-u*e*.5,m=-d*e*.5+u*t*.5,v=(i=Math.abs(i))*i,_=(s=Math.abs(s))*s,y=m*m,b=p*p,w=v*_-v*y-_*b,C=0;if(w<0){var S=Math.sqrt(1-w/(v*_));i*=S,s*=S}else C=(o===a?-1:1)*Math.sqrt(w/(v*y+_*b));var T=C*i*m/s,O=-C*s*p/i,E=d*T-u*O+.5*t,D=u*T+d*O+.5*e,M=n(1,0,(p-T)/i,(m-O)/s),I=n((p-T)/i,(m-O)/s,(-p-T)/i,(-m-O)/s);0===a&&I>0?I-=2*l:1===a&&I<0&&(I+=2*l);for(var F=Math.ceil(Math.abs(I/l*2)),P=[],k=I/F,L=8/3*Math.sin(k/4)*Math.sin(k/4)/Math.sin(k/2),A=M+k,R=0;RC)for(var T=1,O=p.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,b=Math.max,w=Math.abs,C=[],S=[[],[]];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),w(c)<1e-12){if(w(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(m=u*u-4*d*c)<0||(0<(g=(-u+(v=_(m)))/(2*c))&&g<1&&C.push(g),0<(p=(-u-v)/(2*c))&&p<1&&C.push(p));for(var O,E,D,M=C.length,I=M;M--;)O=(D=1-(f=C[M]))*D*D*e+3*D*D*f*r+3*D*f*f*s+f*f*f*a,S[0][M]=O,E=D*D*D*i+3*D*D*f*n+3*D*f*f*o+f*f*f*h,S[1][M]=E;S[0][I]=e,S[1][I]=i,S[0][I+1]=a,S[1][I+1]=h;var F=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:b.apply(null,S[0]),y:b.apply(null,S[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=F),F},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*([^\)]+)\)/,p=function(t){return t},d?p=function(t,e){return t.style.opacity=e,t}:f&&(p=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?p(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?p(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,p=i.easing||n,m="startValue"in i&&i.startValue.length>0,v="startValue"in i?i.startValue:0,_="endValue"in i?i.endValue:100,y=i.byValue||(m?v.map((function(t,e){return _[e]-v[e]})):_-v);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,b=m?v.map((function(t,e){return p(r,v[e],y[e],c)})):p(r,v,y,c),w=m?Math.abs((b[0]-v[0])/y[0]):Math.abs((b-v)/y);if(s.currentValue=m?b.slice():b,s.completionRate=w,s.durationRate=n,!o){if(!f(b,w,n))return e>u?(s.currentValue=m?_.slice():_,s.completionRate=1,s.durationRate=1,d(m?_.slice():_,1,1),g(_,1,1),void h()):(d(b,w,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 _=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,p=t.getAttribute("y")||0,m=t.getAttribute("preserveAspectRatio")||"",v=!l||!(l=l.match(_)),y=!d||!f||"100%"===d||"100%"===f,b=v&&y,w={},C="",S=0,x=0;if(w.width=0,w.height=0,w.toBeParsed=b,v&&(g||p)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(p)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),b)return w;if(v)return w.width=s(d),w.height=s(f),w;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),w.minX=i,w.minY=r,w.viewBoxWidth=n,w.viewBoxHeight=o,y?(w.width=n,w.height=o):(w.width=s(d),w.height=s(f),c=w.width/n,u=w.height/o),"none"!==(m=e.util.parsePreserveAspectRatioAttribute(m)).alignX&&("meet"===m.meetOrSlice&&(u=c=c>u?u:c),"slice"===m.meetOrSlice&&(u=c=c>u?c:u),S=w.width-n*c,x=w.height-o*c,"Mid"===m.alignX&&(S/=2),"Mid"===m.alignY&&(x/=2),"Min"===m.alignX&&(S=0),"Min"===m.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===p)return w;if((g||p)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(p)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(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),w}function b(t,e){var i="xlink:href",r=v(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&b(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 p(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function m(t){return t.originX===l&&t.originY===l}function v(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function _(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 b(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,_(i,r,n,s)),o}}function w(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 C(t){return t.flipX!==t.flipY}function S(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=w(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),C(l)&&(n=-n));var p=g!==n;if(p){var m=l._getTransformedDimensions().y;l.set("skewX",n),S(l,"skewY","scaleY","y",m)}return p}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=w(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),C(l)&&(n=-n));var p=g!==n;if(p){var m=l._getTransformedDimensions().x;l.set("skewY",n),S(l,"skewX","scaleX","x",m)}return p}function O(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,_=f.lockScalingY,y=n.by,b=p(t,f),C=v(f,y,b),S=e.gestureScale;if(C)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=w(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(),b&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=e.original,O=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*O,a=T.scaleY*O}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);m(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var E=f.scaleX,D=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!_&&f.set("scaleY",a)),E!==f.scaleX||D!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=p(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),v(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=b("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,p=Math.floor(c/d)*d;Math.abs(c-p)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),C(h)&&(n=n===s?a:s)),e.originX=n,b("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=w(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),C(a)&&(n=n===o?h:o)),e.originY=n,b("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",_(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=b,n.getLocalPoint=w,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),p=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(p),l=f*e.util.sin(p)}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 m=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,p=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,p=-i.top),new x.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:p})}})}(),v=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:v(this.offsetX,r),offsetY:v(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:e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e:e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e:e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:e,selected:n}):t.length>0&&this.fire("selection:cleared",{e: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: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: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(_(r,s),_(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(),p=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=p,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,p=f||g,m=0,v=0,_=!1;if(f){var y=this._cacheCanvas.width,b=this._cacheCanvas.height,w=l>y||c>b;_=w||(l<.9*y||c<.9*b)&&y>h&&b>h,w&&!a.capped&&(l>h||c>h)&&(m=.1*l,v=.1*c)}return this instanceof e.Text&&this.path&&(p=!0,_=!0,m+=this.getHeightOfLine(0)*this.zoomX,v+=this.getHeightOfLine(0)*this.zoomY),!!p&&(_?(o.width=Math.ceil(l+m),o.height=Math.ceil(c+v)):(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,p={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),p.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),p.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+p.x,u=f.height+p.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var m=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(m.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(m.width/2,m.height/2),"center","center");var v=this.canvas;m.add(this);var _=m.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",v),n&&(this.group=n),this.set(r).setCoords(),m._objects=[],m.dispose(),m=null,_},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),b=x.util.degreesToRadians,w={left:-.5,center:0,right:.5},C={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=w[e]:e-=.5,"string"==typeof r?r=w[r]:r-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof n?n=C[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,b(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,b(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,-b(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=b(this.angle),n=this.getScaledWidth(),s=x.util.cos(r)*n,o=x.util.sin(r)*n;e="string"==typeof this.originX?w[this.originX]:this.originX-.5,i="string"==typeof t?w[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=[],p=t.indexOf("COMMON_PARTS"),m=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()," ",m?'transform="'+m+'" ':""].join(""),t[p]=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),p=o(s*r,u-f),m=-n/2,v=-s/2,_=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=E);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),O.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=O}},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:O,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=b||o<0||o>=y||(h=4*(a*y+o),l=m[f*v+d],e+=p[h]*l,i+=p[h+1]*l,r+=p[h+2]*l,S||(n+=p[h+3]*l));C[s]=e,C[s+1]=i,C[s+2]=r,C[s+3]=S?p[s+3]:n}t.imageData=w},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,p=e.filterBackend.resources,m=0,v=0,_=i,y=0;for(p.sliceByTwo||(p.sliceByTwo=document.createElement("canvas")),((a=p.sliceByTwo).width<1.5*i||a.height=e)){P=r(1e3*s(x-w.x)),b[P]||(b[P]={});for(var L=C.y-y;L<=C.y+y;L++)L<0||L>=o||(k=r(1e3*s(L-w.y)),b[P][k]||(b[P][k]=f(n(i(P*m,2)+i(k*v,2))/1e3)),(T=b[P][k])>0&&(E+=T,D+=T*c[O=4*(L*e+x)],M+=T*c[O+1],I+=T*c[O+2],F+=T*c[O+3]))}d[O=4*(S*a+h)]=D/E,d[O+1]=M/E,d[O+2]=I/E,d[O+3]=F/E}return++h1&&k<-1||(y=2*k*k*k-3*k*k+1)>0&&(T+=y*f[3+(P=4*(F+E*e))],w+=y,f[P+3]<255&&(y=y*f[P+3]/250),C+=y*f[P],S+=y*f[P+1],x+=y*f[P+2],b+=y)}p[_]=C/b,p[_+1]=S/b,p[_+2]=x/b,p[_+3]=T/w}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,p=this._textLines.length;g=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 E=_+s+u;"rtl"===this.direction&&(E=this.width-E-d),l&&v&&(t.fillStyle=v,t.fillRect(E,c+C*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,v=m,r=n,o=a}else d+=f.kernedWidth;E=_+s+u,"rtl"===this.direction&&(E=this.width-E-d),t.fillStyle=m,g&&m&&t.fillRect(E,c+C*r+o,d-w,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),p=0,m=0;if(u===a&&(p=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var _=t.left+f+p,y=m-p,b=g,w=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",b=1,w=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(_=this.width-_-y),e.fillRect(_,t.top+t.topOffset+w,y,b),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")}}(),S=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,p=c.clientWidth/u,m=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=p,h.y*=m,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=S(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:S(r[i-1])}:n?this.styles[t+i]={0:S(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?S(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]=S(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(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),p=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,p=f.length-1;g<=p;g++)h=g===p||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&&!m?(a.push(h),h=[],s=f,m=!0):s+=v,m||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,m=!1,f>p&&(p=f);return _&&a.push(h),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+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 r(t){var n=i[t];if(void 0!==n)return n.exports;var s=i[t]={exports:{}};return e[t](s,s.exports,r),s.exports}r.d=(t,e)=>{for(var i in e)r.o(e,i)&&!r.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var n={};(()=>{let t;r.d(n,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?r(653).fabric:{version:"5.2.1"}})();var s=n.R;const o="undefined"==typeof self;let a,h,l,c,u;if("undefined"!=typeof navigator&&(a=navigator,h=a.userAgent,l=a.platform,c=a.mediaDevices),!o){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:a.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:l,search:"Win"},Mac:{str:l},Linux:{str:l}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||h,o=n.search||e,a=n.verStr||h,l=n.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(o)){i=e;for(let t of l){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||h,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=h.indexOf("Windows NT")&&(n="HarmonyOS"),u={browser:i,version:r,OS:n}}o&&(u={browser:"ssr",version:0,OS:"ssr"});const d="undefined"!=typeof WebAssembly&&h&&!(/Safari/.test(h)&&!/Chrome/.test(h)&&/\(.+\s11_2_([2-6]).*\)/.test(h)),f=!("undefined"==typeof Worker),g=!(!c||!c.getUserMedia),p=async()=>{let t=!1;if(g)try{(await c.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===u.browser&&u.version>66||"Safari"===u.browser&&u.version>13||"OPR"===u.browser&&u.version>43||"Edge"===u.browser&&u.version;const m=(()=>{if(!o&&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 v{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,b),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 s.Control({positionHandler:_,actionHandler:w(r>0?r-1:i,b),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 o=s.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:o.x,y:o.y})}return t}}}const S=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;i_?(p=f,m=f/v,{x:n.x*i.width,y:(n.y-(g-m)/2)*i.width}):(p=g*v,m=g,{x:(n.x-(f-p)/2)*i.height,y:n.y*i.height}):"cover"===c?v>_?{x:(u-i.height*f)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(d-i.width*g)/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}},s.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();s.util.addListener(s.document,"touchend",this._onTouchEnd,{passive:!1}),s.util.addListener(s.document,"touchmove",this._onMouseMove,{passive:!1}),s.util.removeListener(i,r+"down",this._onMouseDown)},s.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),o=!(!n||!n.length);var a=0,h=this.splitByGrapheme||o,l=[],c=[],u=h?s.util.string.graphemeSplit(t):t.split(this._wordJoiners),d="",f=0,g=h?"":" ",p=0,m=0,v=0,_=!0,y=this._getWidthOfCharSpacing();r=r||0;0===u.length&&u.push([]),i-=r;for(var b=0;bi&&!_?(l.push(c),c=[],a=p,_=!0):a+=y,_||h||c.push(g),c=c.concat(d),m=h?0:this._measureWord([g],e,f),f++,_=!1,p>v&&(v=p);return b&&l.push(c),v+r>this.dynamicMinWidth&&(this.dynamicMinWidth=v-y+r),l});class T{constructor(t,e,i,r){let n,o;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 s.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),o=i.get(5);break;case 2:n=i.get(2),o=i.get(6);break;case 3:n=i.get(3),o=i.get(7);break;default:n=i.get(4),o=i.get(8)}for(let t of v.arrMediaTypes)this.mapMediaType_Style.set(t,{default:n,selected:o})}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);const e=t._mapStyle.get(t.styleSelector);return e||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 v.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 v.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 T(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 E{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 D{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 D.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 D.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return D.multiply(t,[e,0,0,0,i,0,0,0,1])}}var M;!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"}(M||(M={}));const I=(t,e,i,r)=>{let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class F{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();if(F._onLog&&F._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===M.GREY)h.stride=h.width;else h.stride=4*h.width;return 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",M.GREY],["grey32",M.GREY32],["rgba",M.RGBA],["rbga",M.RBGA],["grba",M.GRBA],["gbra",M.GBRA],["brga",M.BRGA],["bgra",M.BGRA]]),this.shaderPixelFormat=M.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,p=o/a;let m=1;if("contain"===s)if(p>g){m=d/o,r=(e-l)/m;n=(i-c-(f-d/p)/2)/m}else{m=f/a,n=(i-c)/m;r=(e-l-(d-f*p)/2)/m}else{if("cover"!==s)throw new Error("Unsupported object-fit.");if(p>g){m=f/a,n=(i-c)/m;r=(e-l+(f*p-d)/2)/m}else{m=d/o,r=(e-l)/m;n=(i-c+(d/p-f)/2)/m}}const v={x:r+"px",y:n+"px"},_=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=_;await this._setLocalFocus(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;t.width=this.width,t.height=this.height;if("grey"===(this.pixelFormat||this.colorMode)){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let t,e;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];t=i.getAttribute("data-width"),e=i.getAttribute("data-height")}await this.setResolution(t,e),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this._isSingleFrameModeEnabled())if("visible"===document.visibilityState){if(F._onLog&&F._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];this._video.srcObject.active&&t&&!t.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(F._onLog&&F._onLog("DCE: document hidden."),["iPhone","iPad","Mac"].includes(u.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let t of this._arrScanRegionOverlays)t&&(t.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&(t.style.display="",this._updateScanRegionOverlay(t));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this._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:d,worker:f,getUserMedia:g,camera:await p(),browser:u.browser,version:u.version,OS:u.OS}))()}static set engineResourcePath(t){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");F._engineResourcePath=(t=>{if(null==t&&(t="./"),!o){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){F._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=F._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",F.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?(_=c/i,g=0,p=(u-r*_)/2):(_=u/r,g=(c-i*_)/2,p=0),g+=s.regionLeft*_,p+=s.regionTop*_,m=(s.regionRight-s.regionLeft)*_,v=(s.regionBottom-s.regionTop)*_):"cover"===n?(f>d?(_=u/r,g=s.regionLeft*_-(i*_-c)/2,p=s.regionTop*_):(_=c/i,g=s.regionLeft*_,p=s.regionTop*_-(r*_-u)/2),m=(s.regionRight-s.regionLeft)*_,v=(s.regionBottom-s.regionTop)*_):(g=0,p=0,m=0,v=0),t.style.position="absolute",t.style.left=g+"px",t.style.top=p+"px",t.style.width=m+"px",t.style.height=v+"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 F;("string"==typeof t||t instanceof String)&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return this._hasEngineResourceLoaded=!0,F.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{F.onWarning&&F.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((()=>{F.onWarning&&F.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 O,e}static async playVideo(t,e,i){return new Promise(((r,n)=>{t||n(new Error("Invalid video element.")),e||n(new Error("Invalid source.")),t.onloadedmetadata=async()=>{t.onloadedmetadata=null,await t.play(),r(t)},"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,void 0!==i&&setTimeout((()=>n(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(u.OS))return F.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(u.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){F._onLog&&(n=Date.now(),F._onLog("DCE: start loading static video: "+n));const t=await F.playVideo(this._video,this.videoSrc,4e3);if(F._onLog&&F._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(),F._onLog&&F._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&&F.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=F.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}),F._onLog&&F._onLog("DCE: ======try getUserMedia========");let l=[0,500],c=null;const d=async t=>{for(let e of l){e&&await new Promise((t=>setTimeout(t,e))),s();try{F._onLog&&F._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,F._onLog&&F._onLog("DCE: "+t.message||t)}}s()};let f;if(await d(o),!h){if(F._onLog&&F._onLog("DCE: ======try getUserMedia again========"),f=JSON.parse(JSON.stringify(o)),"object"==typeof f.video){["iPhone","iPad"].includes(u.OS)?(e>=1280||i>=1280?f.video.width=1280:e>=640||i>=640?f.video.width=640:(e<640||i<640)&&(f.video.width=320),delete f.video.height):a&&!o.video.deviceId?(delete f.video.facingMode,this._allCameras.length&&(f.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):f.video=!0}F._onLog&&F._onLog("DCE: "+f),await d(f)}if(h||(l=[1e3,2e3],await d(o)),h||await d(f),!h)throw c;const g=()=>{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){g();const t=F.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 d(o))}F._onLog&&F._onLog("DCE: ======play video========"),s(),await F.playVideo(this._video,h,4e3),s(),F._onLog&&F._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const p=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=p,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),F._onLog&&F._onLog("DCE: got "+p),g(),this._renderSelCameraInfo();const m={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(m.deviceId&&(this._lastDeviceId=m.deviceId,this.ifSaveLastUsedCamera&&F.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(m));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return this.promisePlay=null,m}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}})(),F._onLog&&(n=Date.now(),F._onLog("DCE: start opening camera: "+n));const o=await this.promisePlay;return F._onLog&&F._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','','',''].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 t of this.extraBindings)try{t(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(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((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(F.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&&(F._onLog&&F._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&&(F._onLog&&F._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=I(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.");if(!this._videoTrack)return null;return this._getHardwareScale()*this._softwareScale}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;return{factor:this._getHardwareScale()*this._softwareScale}}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=I(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=I(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=I(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:M.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=I(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=I(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=I(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;F._onLog&&(a=Date.now(),F._onLog("DCE: _drawImage(), START: "+a));let h=0,l=0,c=i,u=r,d=0,f=0,g=i,p=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&&(p=Math.round(n.dHeight)));let m=M.RGBA;o&&o.pixelFormat&&(m=o.pixelFormat);const v=t;if(o&&o.bUseWebGL){F._onLog&&F._onLog("DCE: _drawImage() in WebGL."),(v.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();t.bindBuffer(t.ARRAY_BUFFER,i);return 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(m)&&(o=m.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=m}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)},_=(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,[M.GREY,M.GREY32].includes(m)?1:0);let a,v,_=D.translate(D.identity(),-1,-1);_=D.scale(_,2,2),_=D.scale(_,1/t.canvas.width,1/t.canvas.height),a=D.translate(_,d,f),a=D.scale(a,g,p),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,a),v=D.translate(D.identity(),h/i,l/r),v=D.scale(v,c/i,u/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};let y;if(o(t,this._webGLTexture,e),_(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;F._onLog&&(o=Date.now(),F._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=M.RGBA;s&&s.pixelFormat&&(f=s.pixelFormat);let g,p,m,v=this._bWebGLSupported;s&&0==s.bUseWebGL&&(v=!1),v?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),g=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),g=this._reusedCvs);try{if(v)if(F._onLog&&F._onLog("DCE: _getImageData() in WebGL."),n)if(f===M.GREY){if(m=new Uint8Array(u*d*4),p=this._drawImage(g,t,e,i,{sx:a,sy:h,sWidth:l,sHeight:c,dWidth:u,dHeight:d},m,{pixelFormat:f,bUseWebGL:v}),m=this._transformPixelFormat(m,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=()=>{F._onLog&&F._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(F._onLog&&F._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),F._onLog&&F._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()?(F._onLog&&F._onLog("DCE: second timeout executes: "+Date.now()),e(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};t&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(e(),i()):0===this.refreshInterval?e():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this._isSingleFrameModeEnabled())throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,F._onLog&&F._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(F._onLog&&F._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 x(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 E(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,v=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 s.Control({positionHandler:_,actionHandler:w(i>0?i-1:r,b),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 o=s.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:o.x,y:o.y})}return"startPoint"===t?e[0]:e[1]}}},DT_Group:class extends v{constructor(t){super(new s.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()))}}};t.CameraEnhancer=F,t.DrawingItem=P,Object.defineProperty(t,"__esModule",{value:!0})})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft=t.Dynamsoft||{},t.Dynamsoft.DCE={}))}(this,(function(t){"use strict";var e={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,p,m,v,_,y,b,w,C,S,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 O(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 E(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),p=g.vector,m=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(m/2),f=new x.Point(p.x*d*s.x,p.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(p.x*d*s.x,p.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,p=-d*t*.5-u*e*.5,m=-d*e*.5+u*t*.5,v=(i=Math.abs(i))*i,_=(s=Math.abs(s))*s,y=m*m,b=p*p,w=v*_-v*y-_*b,C=0;if(w<0){var S=Math.sqrt(1-w/(v*_));i*=S,s*=S}else C=(o===a?-1:1)*Math.sqrt(w/(v*y+_*b));var T=C*i*m/s,O=-C*s*p/i,E=d*T-u*O+.5*t,D=u*T+d*O+.5*e,M=n(1,0,(p-T)/i,(m-O)/s),I=n((p-T)/i,(m-O)/s,(-p-T)/i,(-m-O)/s);0===a&&I>0?I-=2*l:1===a&&I<0&&(I+=2*l);for(var F=Math.ceil(Math.abs(I/l*2)),P=[],k=I/F,L=8/3*Math.sin(k/4)*Math.sin(k/4)/Math.sin(k/2),A=M+k,R=0;RC)for(var T=1,O=p.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,b=Math.max,w=Math.abs,C=[],S=[[],[]];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),w(c)<1e-12){if(w(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(m=u*u-4*d*c)<0||(0<(g=(-u+(v=_(m)))/(2*c))&&g<1&&C.push(g),0<(p=(-u-v)/(2*c))&&p<1&&C.push(p));for(var O,E,D,M=C.length,I=M;M--;)O=(D=1-(f=C[M]))*D*D*e+3*D*D*f*r+3*D*f*f*s+f*f*f*a,S[0][M]=O,E=D*D*D*i+3*D*D*f*n+3*D*f*f*o+f*f*f*h,S[1][M]=E;S[0][I]=e,S[1][I]=i,S[0][I+1]=a,S[1][I+1]=h;var F=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:b.apply(null,S[0]),y:b.apply(null,S[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=F),F},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*([^\)]+)\)/,p=function(t){return t},d?p=function(t,e){return t.style.opacity=e,t}:f&&(p=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?p(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?p(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,p=i.easing||n,m="startValue"in i&&i.startValue.length>0,v="startValue"in i?i.startValue:0,_="endValue"in i?i.endValue:100,y=i.byValue||(m?v.map((function(t,e){return _[e]-v[e]})):_-v);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,b=m?v.map((function(t,e){return p(r,v[e],y[e],c)})):p(r,v,y,c),w=m?Math.abs((b[0]-v[0])/y[0]):Math.abs((b-v)/y);if(s.currentValue=m?b.slice():b,s.completionRate=w,s.durationRate=n,!o){if(!f(b,w,n))return e>u?(s.currentValue=m?_.slice():_,s.completionRate=1,s.durationRate=1,d(m?_.slice():_,1,1),g(_,1,1),void h()):(d(b,w,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 _=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,p=t.getAttribute("y")||0,m=t.getAttribute("preserveAspectRatio")||"",v=!l||!(l=l.match(_)),y=!d||!f||"100%"===d||"100%"===f,b=v&&y,w={},C="",S=0,x=0;if(w.width=0,w.height=0,w.toBeParsed=b,v&&(g||p)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(p)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),b)return w;if(v)return w.width=s(d),w.height=s(f),w;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),w.minX=i,w.minY=r,w.viewBoxWidth=n,w.viewBoxHeight=o,y?(w.width=n,w.height=o):(w.width=s(d),w.height=s(f),c=w.width/n,u=w.height/o),"none"!==(m=e.util.parsePreserveAspectRatioAttribute(m)).alignX&&("meet"===m.meetOrSlice&&(u=c=c>u?u:c),"slice"===m.meetOrSlice&&(u=c=c>u?c:u),S=w.width-n*c,x=w.height-o*c,"Mid"===m.alignX&&(S/=2),"Mid"===m.alignY&&(x/=2),"Min"===m.alignX&&(S=0),"Min"===m.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===p)return w;if((g||p)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(p)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(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),w}function b(t,e){var i="xlink:href",r=v(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&b(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 p(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function m(t){return t.originX===l&&t.originY===l}function v(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function _(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 b(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,_(i,r,n,s)),o}}function w(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 C(t){return t.flipX!==t.flipY}function S(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=w(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),C(l)&&(n=-n));var p=g!==n;if(p){var m=l._getTransformedDimensions().y;l.set("skewX",n),S(l,"skewY","scaleY","y",m)}return p}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=w(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),C(l)&&(n=-n));var p=g!==n;if(p){var m=l._getTransformedDimensions().x;l.set("skewY",n),S(l,"skewX","scaleX","x",m)}return p}function O(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,_=f.lockScalingY,y=n.by,b=p(t,f),C=v(f,y,b),S=e.gestureScale;if(C)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=w(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(),b&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=e.original,O=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*O,a=T.scaleY*O}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);m(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var E=f.scaleX,D=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!_&&f.set("scaleY",a)),E!==f.scaleX||D!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=p(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),v(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=b("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,p=Math.floor(c/d)*d;Math.abs(c-p)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),C(h)&&(n=n===s?a:s)),e.originX=n,b("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=w(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),C(a)&&(n=n===o?h:o)),e.originY=n,b("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",_(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=b,n.getLocalPoint=w,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),p=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(p),l=f*e.util.sin(p)}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 m=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,p=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,p=-i.top),new x.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:p})}})}(),v=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:v(this.offsetX,r),offsetY:v(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:e,target:t}),s.push(t))})),r.forEach((function(r){-1===t.indexOf(r)&&(i=!0,r.fire("selected",{e:e,target:r}),n.push(r))})),t.length>0&&r.length>0?i&&this.fire("selection:updated",{e:e,selected:n,deselected:s}):r.length>0?this.fire("selection:created",{e:e,selected:n}):t.length>0&&this.fire("selection:cleared",{e: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: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: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(_(r,s),_(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(),p=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=p,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,p=f||g,m=0,v=0,_=!1;if(f){var y=this._cacheCanvas.width,b=this._cacheCanvas.height,w=l>y||c>b;_=w||(l<.9*y||c<.9*b)&&y>h&&b>h,w&&!a.capped&&(l>h||c>h)&&(m=.1*l,v=.1*c)}return this instanceof e.Text&&this.path&&(p=!0,_=!0,m+=this.getHeightOfLine(0)*this.zoomX,v+=this.getHeightOfLine(0)*this.zoomY),!!p&&(_?(o.width=Math.ceil(l+m),o.height=Math.ceil(c+v)):(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,p={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),p.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),p.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+p.x,u=f.height+p.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var m=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(m.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(m.width/2,m.height/2),"center","center");var v=this.canvas;m.add(this);var _=m.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",v),n&&(this.group=n),this.set(r).setCoords(),m._objects=[],m.dispose(),m=null,_},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),b=x.util.degreesToRadians,w={left:-.5,center:0,right:.5},C={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=w[e]:e-=.5,"string"==typeof r?r=w[r]:r-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof n?n=C[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,b(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,b(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,-b(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=b(this.angle),n=this.getScaledWidth(),s=x.util.cos(r)*n,o=x.util.sin(r)*n;e="string"==typeof this.originX?w[this.originX]:this.originX-.5,i="string"==typeof t?w[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=[],p=t.indexOf("COMMON_PARTS"),m=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()," ",m?'transform="'+m+'" ':""].join(""),t[p]=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),p=o(s*r,u-f),m=-n/2,v=-s/2,_=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=E);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),O.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=O}},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:O,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=b||o<0||o>=y||(h=4*(a*y+o),l=m[f*v+d],e+=p[h]*l,i+=p[h+1]*l,r+=p[h+2]*l,S||(n+=p[h+3]*l));C[s]=e,C[s+1]=i,C[s+2]=r,C[s+3]=S?p[s+3]:n}t.imageData=w},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,p=e.filterBackend.resources,m=0,v=0,_=i,y=0;for(p.sliceByTwo||(p.sliceByTwo=document.createElement("canvas")),((a=p.sliceByTwo).width<1.5*i||a.height=e)){P=r(1e3*s(x-w.x)),b[P]||(b[P]={});for(var L=C.y-y;L<=C.y+y;L++)L<0||L>=o||(k=r(1e3*s(L-w.y)),b[P][k]||(b[P][k]=f(n(i(P*m,2)+i(k*v,2))/1e3)),(T=b[P][k])>0&&(E+=T,D+=T*c[O=4*(L*e+x)],M+=T*c[O+1],I+=T*c[O+2],F+=T*c[O+3]))}d[O=4*(S*a+h)]=D/E,d[O+1]=M/E,d[O+2]=I/E,d[O+3]=F/E}return++h1&&k<-1||(y=2*k*k*k-3*k*k+1)>0&&(T+=y*f[3+(P=4*(F+E*e))],w+=y,f[P+3]<255&&(y=y*f[P+3]/250),C+=y*f[P],S+=y*f[P+1],x+=y*f[P+2],b+=y)}p[_]=C/b,p[_+1]=S/b,p[_+2]=x/b,p[_+3]=T/w}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,p=this._textLines.length;g=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 E=_+s+u;"rtl"===this.direction&&(E=this.width-E-d),l&&v&&(t.fillStyle=v,t.fillRect(E,c+C*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,v=m,r=n,o=a}else d+=f.kernedWidth;E=_+s+u,"rtl"===this.direction&&(E=this.width-E-d),t.fillStyle=m,g&&m&&t.fillRect(E,c+C*r+o,d-w,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),p=0,m=0;if(u===a&&(p=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var _=t.left+f+p,y=m-p,b=g,w=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",b=1,w=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(_=this.width-_-y),e.fillRect(_,t.top+t.topOffset+w,y,b),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")}}(),S=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,p=c.clientWidth/u,m=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=p,h.y*=m,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=S(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:S(r[i-1])}:n?this.styles[t+i]={0:S(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?S(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]=S(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(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),p=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,p=f.length-1;g<=p;g++)h=g===p||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&&!m?(a.push(h),h=[],s=f,m=!0):s+=v,m||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,m=!1,f>p&&(p=f);return _&&a.push(h),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+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 r(t){var n=i[t];if(void 0!==n)return n.exports;var s=i[t]={exports:{}};return e[t](s,s.exports,r),s.exports}r.d=(t,e)=>{for(var i in e)r.o(e,i)&&!r.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},r.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var n={};(()=>{let t;r.d(n,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?r(653).fabric:{version:"5.2.1"}})();var s=n.R;const o="undefined"==typeof self;let a,h,l,c,u;if("undefined"!=typeof navigator&&(a=navigator,h=a.userAgent,l=a.platform,c=a.mediaDevices),!o){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:a.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:l,search:"Win"},Mac:{str:l},Linux:{str:l}};let i="unknownBrowser",r=0,n="unknownOS";for(let e in t){const n=t[e]||{};let s=n.str||h,o=n.search||e,a=n.verStr||h,l=n.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(o)){i=e;for(let t of l){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||h,s=i.search||t;if(-1!=r.indexOf(s)){n=t;break}}"Linux"==n&&-1!=h.indexOf("Windows NT")&&(n="HarmonyOS"),u={browser:i,version:r,OS:n}}o&&(u={browser:"ssr",version:0,OS:"ssr"});const d="undefined"!=typeof WebAssembly&&h&&!(/Safari/.test(h)&&!/Chrome/.test(h)&&/\(.+\s11_2_([2-6]).*\)/.test(h)),f=!("undefined"==typeof Worker),g=!(!c||!c.getUserMedia),p=async()=>{let t=!1;if(g)try{(await c.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===u.browser&&u.version>66||"Safari"===u.browser&&u.version>13||"OPR"===u.browser&&u.version>43||"Edge"===u.browser&&u.version;const m=(()=>{if(!o&&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 v{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,b),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 s.Control({positionHandler:_,actionHandler:w(r>0?r-1:i,b),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 o=s.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:o.x,y:o.y})}return t}}}const S=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;i_?(p=f,m=f/v,{x:n.x*i.width,y:(n.y-(g-m)/2)*i.width}):(p=g*v,m=g,{x:(n.x-(f-p)/2)*i.height,y:n.y*i.height}):"cover"===c?v>_?{x:(u-i.height*f)/2+n.x*i.height,y:n.y*i.height}:{x:n.x*i.width,y:(d-i.width*g)/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}},s.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();s.util.addListener(s.document,"touchend",this._onTouchEnd,{passive:!1}),s.util.addListener(s.document,"touchmove",this._onMouseMove,{passive:!1}),s.util.removeListener(i,r+"down",this._onMouseDown)},s.Textbox.prototype._wrapLine=function(t,e,i,r){const n=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),o=!(!n||!n.length);var a=0,h=this.splitByGrapheme||o,l=[],c=[],u=h?s.util.string.graphemeSplit(t):t.split(this._wordJoiners),d="",f=0,g=h?"":" ",p=0,m=0,v=0,_=!0,y=this._getWidthOfCharSpacing();r=r||0;0===u.length&&u.push([]),i-=r;for(var b=0;bi&&!_?(l.push(c),c=[],a=p,_=!0):a+=y,_||h||c.push(g),c=c.concat(d),m=h?0:this._measureWord([g],e,f),f++,_=!1,p>v&&(v=p);return b&&l.push(c),v+r>this.dynamicMinWidth&&(this.dynamicMinWidth=v-y+r),l});class T{constructor(t,e,i,r){let n,o;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 s.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),o=i.get(5);break;case 2:n=i.get(2),o=i.get(6);break;case 3:n=i.get(3),o=i.get(7);break;default:n=i.get(4),o=i.get(8)}for(let t of v.arrMediaTypes)this.mapMediaType_Style.set(t,{default:n,selected:o})}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);const e=t._mapStyle.get(t.styleSelector);return e||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 v.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 v.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 T(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 E{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 D{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 D.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 D.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return D.multiply(t,[e,0,0,0,i,0,0,0,1])}}var M;!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"}(M||(M={}));const I=(t,e,i,r)=>{let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class F{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();if(F._onLog&&F._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===M.GREY)h.stride=h.width;else h.stride=4*h.width;return 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",M.GREY],["grey32",M.GREY32],["rgba",M.RGBA],["rbga",M.RBGA],["grba",M.GRBA],["gbra",M.GBRA],["brga",M.BRGA],["bgra",M.BGRA]]),this.shaderPixelFormat=M.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,p=o/a;let m=1;if("contain"===s)if(p>g){m=d/o,r=(e-l)/m;n=(i-c-(f-d/p)/2)/m}else{m=f/a,n=(i-c)/m;r=(e-l-(d-f*p)/2)/m}else{if("cover"!==s)throw new Error("Unsupported object-fit.");if(p>g){m=f/a,n=(i-c)/m;r=(e-l+(f*p-d)/2)/m}else{m=d/o,r=(e-l)/m;n=(i-c+(d/p-f)/2)/m}}const v={x:r+"px",y:n+"px"},_=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=_;await this._setLocalFocus(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;t.width=this.width,t.height=this.height;if("grey"===(this.pixelFormat||this.colorMode)){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let t,e;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];t=i.getAttribute("data-width"),e=i.getAttribute("data-height")}await this.setResolution(t,e),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this._isSingleFrameModeEnabled())if("visible"===document.visibilityState){if(F._onLog&&F._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];this._video.srcObject.active&&t&&!t.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(F._onLog&&F._onLog("DCE: document hidden."),["iPhone","iPad","Mac"].includes(u.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let t of this._arrScanRegionOverlays)t&&(t.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&(t.style.display="",this._updateScanRegionOverlay(t));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this._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:d,worker:f,getUserMedia:g,camera:await p(),browser:u.browser,version:u.version,OS:u.OS}))()}static set engineResourcePath(t){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");F._engineResourcePath=(t=>{if(null==t&&(t="./"),!o){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){F._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=F._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",F.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?(_=c/i,g=0,p=(u-r*_)/2):(_=u/r,g=(c-i*_)/2,p=0),g+=s.regionLeft*_,p+=s.regionTop*_,m=(s.regionRight-s.regionLeft)*_,v=(s.regionBottom-s.regionTop)*_):"cover"===n?(f>d?(_=u/r,g=s.regionLeft*_-(i*_-c)/2,p=s.regionTop*_):(_=c/i,g=s.regionLeft*_,p=s.regionTop*_-(r*_-u)/2),m=(s.regionRight-s.regionLeft)*_,v=(s.regionBottom-s.regionTop)*_):(g=0,p=0,m=0,v=0),t.style.position="absolute",t.style.left=g+"px",t.style.top=p+"px",t.style.width=m+"px",t.style.height=v+"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 F;("string"==typeof t||t instanceof String)&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return this._hasEngineResourceLoaded=!0,F.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{F.onWarning&&F.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((()=>{F.onWarning&&F.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 O,e}static async playVideo(t,e,i){return new Promise(((r,n)=>{t||n(new Error("Invalid video element.")),e||n(new Error("Invalid source.")),t.onloadedmetadata=async()=>{t.onloadedmetadata=null,await t.play(),r(t)},"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,void 0!==i&&setTimeout((()=>n(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(u.OS))return F.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(u.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){F._onLog&&(n=Date.now(),F._onLog("DCE: start loading static video: "+n));const t=await F.playVideo(this._video,this.videoSrc,4e3);if(F._onLog&&F._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(),F._onLog&&F._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&&F.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=F.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}),F._onLog&&F._onLog("DCE: ======try getUserMedia========");let l=[0,500],c=null;const d=async t=>{for(let e of l){e&&await new Promise((t=>setTimeout(t,e))),s();try{F._onLog&&F._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,F._onLog&&F._onLog("DCE: "+t.message||t)}}s()};let f;if(await d(o),!h){if(F._onLog&&F._onLog("DCE: ======try getUserMedia again========"),f=JSON.parse(JSON.stringify(o)),"object"==typeof f.video){["iPhone","iPad"].includes(u.OS)?(e>=1280||i>=1280?f.video.width=1280:e>=640||i>=640?f.video.width=640:(e<640||i<640)&&(f.video.width=320),delete f.video.height):a&&!o.video.deviceId?(delete f.video.facingMode,this._allCameras.length&&(f.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):f.video=!0}F._onLog&&F._onLog("DCE: "+f),await d(f)}if(h||(l=[1e3,2e3],await d(o)),h||await d(f),!h)throw c;const g=()=>{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){g();const t=F.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 d(o))}F._onLog&&F._onLog("DCE: ======play video========"),s(),await F.playVideo(this._video,h,4e3),s(),F._onLog&&F._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const p=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=p,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),F._onLog&&F._onLog("DCE: got "+p),g(),this._renderSelCameraInfo();const m={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(m.deviceId&&(this._lastDeviceId=m.deviceId,this.ifSaveLastUsedCamera&&F.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(m));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return this.promisePlay=null,m}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}})(),F._onLog&&(n=Date.now(),F._onLog("DCE: start opening camera: "+n));const o=await this.promisePlay;return F._onLog&&F._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','','',''].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 t of this.extraBindings)try{t(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(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((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(F.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&&(F._onLog&&F._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&&(F._onLog&&F._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=I(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.");if(!this._videoTrack)return null;return this._getHardwareScale()*this._softwareScale}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;return{factor:this._getHardwareScale()*this._softwareScale}}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=I(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=I(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=I(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:M.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=I(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=I(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=I(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;F._onLog&&(a=Date.now(),F._onLog("DCE: _drawImage(), START: "+a));let h=0,l=0,c=i,u=r,d=0,f=0,g=i,p=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&&(p=Math.round(n.dHeight)));let m=M.RGBA;o&&o.pixelFormat&&(m=o.pixelFormat);const v=t;if(!o||!o.bUseWebGL){F._onLog&&F._onLog("DCE: _drawImage() in context2d."),v.ctx2d||(v.ctx2d=v.getContext("2d",{willReadFrequently:!0}));const t=v.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(v.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();t.bindBuffer(t.ARRAY_BUFFER,i);return 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(m)&&(o=m.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=n(t,t.VERTEX_SHADER,s),l=r(t,[h,n(t,t.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:l,attribLocations:{vertexPosition:t.getAttribLocation(l,"a_position"),texPosition:t.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(l,"u_image"),uColorFactor:t.getUniformLocation(l,"uColorFactor"),uMatrix:t.getUniformLocation(l,"u_matrix"),uTextureMatrix:t.getUniformLocation(l,"u_textureMatrix")}},this._webGLBuffers=e(t),this._webGLTexture=i(t),this.shaderPixelFormat=m}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)},_=(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,[M.GREY,M.GREY32].includes(m)?1:0);let a,v,_=D.translate(D.identity(),-1,-1);_=D.scale(_,2,2),_=D.scale(_,1/t.canvas.width,1/t.canvas.height),a=D.translate(_,d,f),a=D.scale(a,g,p),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,a),v=D.translate(D.identity(),h/i,l/r),v=D.scale(v,c/i,u/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};let y;if(o(t,this._webGLTexture,e),_(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;F._onLog&&(o=Date.now(),F._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=M.RGBA;s&&s.pixelFormat&&(f=s.pixelFormat);let g,p,m,v=this._bWebGLSupported;s&&0==s.bUseWebGL&&(v=!1),v?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),g=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),g=this._reusedCvs);try{if(v)if(F._onLog&&F._onLog("DCE: _getImageData() in WebGL."),n)if(f===M.GREY){if(m=new Uint8Array(u*d*4),p=this._drawImage(g,t,e,i,{sx:a,sy:h,sWidth:l,sHeight:c,dWidth:u,dHeight:d},m,{pixelFormat:f,bUseWebGL:v}),m=this._transformPixelFormat(m,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=()=>{F._onLog&&F._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(F._onLog&&F._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),F._onLog&&F._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()?(F._onLog&&F._onLog("DCE: second timeout executes: "+Date.now()),e(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};t&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(e(),i()):0===this.refreshInterval?e():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this._isSingleFrameModeEnabled())throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,F._onLog&&F._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(F._onLog&&F._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 x(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 E(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,v=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 s.Control({positionHandler:_,actionHandler:w(i>0?i-1:r,b),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 o=s.util.transformPoint({x:r,y:n},i.calcTransformMatrix());e.push({x:o.x,y:o.y})}return"startPoint"===t?e[0]:e[1]}}},DT_Group:class extends v{constructor(t){super(new s.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()))}}};t.CameraEnhancer=F,t.DrawingItem=P,Object.defineProperty(t,"__esModule",{value:!0})})); diff --git a/dist/dce.mjs b/dist/dce.mjs index 9a56f6c..2bfe679 100644 --- a/dist/dce.mjs +++ b/dist/dce.mjs @@ -4,8 +4,8 @@ * @website https://www.dynamsoft.com * @copyright Copyright 2023, Dynamsoft Corporation * @author Dynamsoft - * @version 3.3.7 (js 20231010) + * @version 3.3.8 (js 20231011) * @fileoverview Dynamsoft JavaScript Library for Camera Enhancer * More info on DCE JS: https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest */ -const t="undefined"==typeof self;let e,i,r,n,s;if("undefined"!=typeof navigator&&(e=navigator,i=e.userAgent,r=e.platform,n=e.mediaDevices),!t){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:e.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},n={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:r,search:"Win"},Mac:{str:r},Linux:{str:r}};let o="unknownBrowser",a=0,h="unknownOS";for(let e in t){const r=t[e]||{};let n=r.str||i,s=r.search||e,h=r.verStr||i,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=n.indexOf(s)){o=e;for(let t of l){let e=h.indexOf(t);if(-1!=e){a=parseFloat(h.substring(e+t.length+1));break}}break}}for(let t in n){const e=n[t]||{};let r=e.str||i,s=e.search||t;if(-1!=r.indexOf(s)){h=t;break}}"Linux"==h&&-1!=i.indexOf("Windows NT")&&(h="HarmonyOS"),s={browser:o,version:a,OS:h}}t&&(s={browser:"ssr",version:0,OS:"ssr"});const o="undefined"!=typeof WebAssembly&&i&&!(/Safari/.test(i)&&!/Chrome/.test(i)&&/\(.+\s11_2_([2-6]).*\)/.test(i)),a=!("undefined"==typeof Worker),h=!(!n||!n.getUserMedia),l=async()=>{let t=!1;if(h)try{(await n.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"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 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"./"})();var u={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,p,m,v,_,y,b,w,C,S,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 O(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 E(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),p=g.vector,m=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(m/2),f=new x.Point(p.x*d*s.x,p.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(p.x*d*s.x,p.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,p=-d*t*.5-u*e*.5,m=-d*e*.5+u*t*.5,v=(i=Math.abs(i))*i,_=(s=Math.abs(s))*s,y=m*m,b=p*p,w=v*_-v*y-_*b,C=0;if(w<0){var S=Math.sqrt(1-w/(v*_));i*=S,s*=S}else C=(o===a?-1:1)*Math.sqrt(w/(v*y+_*b));var T=C*i*m/s,O=-C*s*p/i,E=d*T-u*O+.5*t,D=u*T+d*O+.5*e,M=n(1,0,(p-T)/i,(m-O)/s),I=n((p-T)/i,(m-O)/s,(-p-T)/i,(-m-O)/s);0===a&&I>0?I-=2*l:1===a&&I<0&&(I+=2*l);for(var F=Math.ceil(Math.abs(I/l*2)),P=[],k=I/F,L=8/3*Math.sin(k/4)*Math.sin(k/4)/Math.sin(k/2),A=M+k,R=0;RC)for(var T=1,O=p.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,b=Math.max,w=Math.abs,C=[],S=[[],[]];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),w(c)<1e-12){if(w(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(m=u*u-4*d*c)<0||(0<(g=(-u+(v=_(m)))/(2*c))&&g<1&&C.push(g),0<(p=(-u-v)/(2*c))&&p<1&&C.push(p));for(var O,E,D,M=C.length,I=M;M--;)O=(D=1-(f=C[M]))*D*D*e+3*D*D*f*r+3*D*f*f*s+f*f*f*a,S[0][M]=O,E=D*D*D*i+3*D*D*f*n+3*D*f*f*o+f*f*f*h,S[1][M]=E;S[0][I]=e,S[1][I]=i,S[0][I+1]=a,S[1][I+1]=h;var F=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:b.apply(null,S[0]),y:b.apply(null,S[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=F),F},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*([^\)]+)\)/,p=function(t){return t},d?p=function(t,e){return t.style.opacity=e,t}:f&&(p=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?p(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?p(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,p=i.easing||n,m="startValue"in i&&i.startValue.length>0,v="startValue"in i?i.startValue:0,_="endValue"in i?i.endValue:100,y=i.byValue||(m?v.map((function(t,e){return _[e]-v[e]})):_-v);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,b=m?v.map((function(t,e){return p(r,v[e],y[e],c)})):p(r,v,y,c),w=m?Math.abs((b[0]-v[0])/y[0]):Math.abs((b-v)/y);if(s.currentValue=m?b.slice():b,s.completionRate=w,s.durationRate=n,!o){if(!f(b,w,n))return e>u?(s.currentValue=m?_.slice():_,s.completionRate=1,s.durationRate=1,d(m?_.slice():_,1,1),g(_,1,1),void h()):(d(b,w,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 _=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,p=t.getAttribute("y")||0,m=t.getAttribute("preserveAspectRatio")||"",v=!l||!(l=l.match(_)),y=!d||!f||"100%"===d||"100%"===f,b=v&&y,w={},C="",S=0,x=0;if(w.width=0,w.height=0,w.toBeParsed=b,v&&(g||p)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(p)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),b)return w;if(v)return w.width=s(d),w.height=s(f),w;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),w.minX=i,w.minY=r,w.viewBoxWidth=n,w.viewBoxHeight=o,y?(w.width=n,w.height=o):(w.width=s(d),w.height=s(f),c=w.width/n,u=w.height/o),"none"!==(m=e.util.parsePreserveAspectRatioAttribute(m)).alignX&&("meet"===m.meetOrSlice&&(u=c=c>u?u:c),"slice"===m.meetOrSlice&&(u=c=c>u?c:u),S=w.width-n*c,x=w.height-o*c,"Mid"===m.alignX&&(S/=2),"Mid"===m.alignY&&(x/=2),"Min"===m.alignX&&(S=0),"Min"===m.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===p)return w;if((g||p)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(p)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(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),w}function b(t,e){var i="xlink:href",r=v(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&b(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 p(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function m(t){return t.originX===l&&t.originY===l}function v(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function _(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 b(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,_(i,r,n,s)),o}}function w(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 C(t){return t.flipX!==t.flipY}function S(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=w(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),C(l)&&(n=-n));var p=g!==n;if(p){var m=l._getTransformedDimensions().y;l.set("skewX",n),S(l,"skewY","scaleY","y",m)}return p}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=w(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),C(l)&&(n=-n));var p=g!==n;if(p){var m=l._getTransformedDimensions().x;l.set("skewY",n),S(l,"skewX","scaleX","x",m)}return p}function O(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,_=f.lockScalingY,y=n.by,b=p(t,f),C=v(f,y,b),S=e.gestureScale;if(C)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=w(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(),b&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=e.original,O=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*O,a=T.scaleY*O}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);m(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var E=f.scaleX,D=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!_&&f.set("scaleY",a)),E!==f.scaleX||D!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=p(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),v(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=b("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,p=Math.floor(c/d)*d;Math.abs(c-p)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),C(h)&&(n=n===s?a:s)),e.originX=n,b("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=w(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),C(a)&&(n=n===o?h:o)),e.originY=n,b("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",_(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=b,n.getLocalPoint=w,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),p=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(p),l=f*e.util.sin(p)}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 m=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,p=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,p=-i.top),new x.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:p})}})}(),v=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:v(this.offsetX,r),offsetY:v(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(_(r,s),_(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(),p=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=p,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,p=f||g,m=0,v=0,_=!1;if(f){var y=this._cacheCanvas.width,b=this._cacheCanvas.height,w=l>y||c>b;_=w||(l<.9*y||c<.9*b)&&y>h&&b>h,w&&!a.capped&&(l>h||c>h)&&(m=.1*l,v=.1*c)}return this instanceof e.Text&&this.path&&(p=!0,_=!0,m+=this.getHeightOfLine(0)*this.zoomX,v+=this.getHeightOfLine(0)*this.zoomY),!!p&&(_?(o.width=Math.ceil(l+m),o.height=Math.ceil(c+v)):(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,p={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),p.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),p.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+p.x,u=f.height+p.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var m=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(m.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(m.width/2,m.height/2),"center","center");var v=this.canvas;m.add(this);var _=m.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",v),n&&(this.group=n),this.set(r).setCoords(),m._objects=[],m.dispose(),m=null,_},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),b=x.util.degreesToRadians,w={left:-.5,center:0,right:.5},C={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=w[e]:e-=.5,"string"==typeof r?r=w[r]:r-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof n?n=C[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,b(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,b(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,-b(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=b(this.angle),n=this.getScaledWidth(),s=x.util.cos(r)*n,o=x.util.sin(r)*n;e="string"==typeof this.originX?w[this.originX]:this.originX-.5,i="string"==typeof t?w[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=[],p=t.indexOf("COMMON_PARTS"),m=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()," ",m?'transform="'+m+'" ':""].join(""),t[p]=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),p=o(s*r,u-f),m=-n/2,v=-s/2,_=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=E);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),O.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=O}},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:O,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=b||o<0||o>=y||(h=4*(a*y+o),l=m[f*v+d],e+=p[h]*l,i+=p[h+1]*l,r+=p[h+2]*l,S||(n+=p[h+3]*l));C[s]=e,C[s+1]=i,C[s+2]=r,C[s+3]=S?p[s+3]:n}t.imageData=w},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,p=e.filterBackend.resources,m=0,v=0,_=i,y=0;for(p.sliceByTwo||(p.sliceByTwo=document.createElement("canvas")),((a=p.sliceByTwo).width<1.5*i||a.height=e)){P=r(1e3*s(x-w.x)),b[P]||(b[P]={});for(var L=C.y-y;L<=C.y+y;L++)L<0||L>=o||(k=r(1e3*s(L-w.y)),b[P][k]||(b[P][k]=f(n(i(P*m,2)+i(k*v,2))/1e3)),(T=b[P][k])>0&&(E+=T,D+=T*c[O=4*(L*e+x)],M+=T*c[O+1],I+=T*c[O+2],F+=T*c[O+3]))}d[O=4*(S*a+h)]=D/E,d[O+1]=M/E,d[O+2]=I/E,d[O+3]=F/E}return++h1&&k<-1||(y=2*k*k*k-3*k*k+1)>0&&(T+=y*f[3+(P=4*(F+E*e))],w+=y,f[P+3]<255&&(y=y*f[P+3]/250),C+=y*f[P],S+=y*f[P+1],x+=y*f[P+2],b+=y)}p[_]=C/b,p[_+1]=S/b,p[_+2]=x/b,p[_+3]=T/w}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,p=this._textLines.length;g=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 E=_+s+u;"rtl"===this.direction&&(E=this.width-E-d),l&&v&&(t.fillStyle=v,t.fillRect(E,c+C*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,v=m,r=n,o=a}else d+=f.kernedWidth;E=_+s+u,"rtl"===this.direction&&(E=this.width-E-d),t.fillStyle=m,g&&m&&t.fillRect(E,c+C*r+o,d-w,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),p=0,m=0;if(u===a&&(p=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var _=t.left+f+p,y=m-p,b=g,w=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",b=1,w=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(_=this.width-_-y),e.fillRect(_,t.top+t.topOffset+w,y,b),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")}}(),S=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,p=c.clientWidth/u,m=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=p,h.y*=m,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=S(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:S(r[i-1])}:n?this.styles[t+i]={0:S(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?S(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]=S(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(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),p=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,p=f.length-1;g<=p;g++)h=g===p||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&&!m?(a.push(h),h=[],s=f,m=!0):s+=v,m||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,m=!1,f>p&&(p=f);return _&&a.push(h),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+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:()=>{}},d={};function f(t){var e=d[t];if(void 0!==e)return e.exports;var i=d[t]={exports:{}};return u[t](i,i.exports,f),i.exports}f.d=(t,e)=>{for(var i in e)f.o(e,i)&&!f.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},f.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var g={};(()=>{let t;f.d(g,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?f(653).fabric:{version:"5.2.1"}})();var p=g.R;class m{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 p.Control({positionHandler:v,actionHandler:b(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=p.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}}const C=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;i_?(g=d,m=d/v,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*v,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?v>_?{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}},p.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();p.util.addListener(p.document,"touchend",this._onTouchEnd,{passive:!1}),p.util.addListener(p.document,"touchmove",this._onMouseMove,{passive:!1}),p.util.removeListener(i,r+"down",this._onMouseDown)},p.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?p.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,v=0,_=!0,y=this._getWidthOfCharSpacing();r=r||0;0===c.length&&c.push([]),i-=r;for(var b=0;bi&&!_?(h.push(l),l=[],o=g,_=!0):o+=y,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>v&&(v=g);return b&&h.push(l),v+r>this.dynamicMinWidth&&(this.dynamicMinWidth=v-y+r),h});class x{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 p.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 m.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);const e=t._mapStyle.get(t.styleSelector);return e||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 m.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 m.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 x(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 O{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 E{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 E.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 E.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return E.multiply(t,[e,0,0,0,i,0,0,0,1])}}var D;!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"}(D||(D={}));const M=(t,e,i,r)=>{let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class I{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();if(I._onLog&&I._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===D.GREY)h.stride=h.width;else h.stride=4*h.width;return 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",D.GREY],["grey32",D.GREY32],["rgba",D.RGBA],["rbga",D.RBGA],["grba",D.GRBA],["gbra",D.GBRA],["brga",D.BRGA],["bgra",D.BGRA]]),this.shaderPixelFormat=D.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,p=o/a;let m=1;if("contain"===s)if(p>g){m=d/o,r=(e-l)/m;n=(i-c-(f-d/p)/2)/m}else{m=f/a,n=(i-c)/m;r=(e-l-(d-f*p)/2)/m}else{if("cover"!==s)throw new Error("Unsupported object-fit.");if(p>g){m=f/a,n=(i-c)/m;r=(e-l+(f*p-d)/2)/m}else{m=d/o,r=(e-l)/m;n=(i-c+(d/p-f)/2)/m}}const v={x:r+"px",y:n+"px"},_=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=_;await this._setLocalFocus(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;t.width=this.width,t.height=this.height;if("grey"===(this.pixelFormat||this.colorMode)){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let t,e;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];t=i.getAttribute("data-width"),e=i.getAttribute("data-height")}await this.setResolution(t,e),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this._isSingleFrameModeEnabled())if("visible"===document.visibilityState){if(I._onLog&&I._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];this._video.srcObject.active&&t&&!t.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(I._onLog&&I._onLog("DCE: document hidden."),["iPhone","iPad","Mac"].includes(s.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let t of this._arrScanRegionOverlays)t&&(t.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&(t.style.display="",this._updateScanRegionOverlay(t));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this._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:o,worker:a,getUserMedia:h,camera:await l(),browser:s.browser,version:s.version,OS:s.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");I._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 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){I._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=I._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",I.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?(_=c/i,g=0,p=(u-r*_)/2):(_=u/r,g=(c-i*_)/2,p=0),g+=s.regionLeft*_,p+=s.regionTop*_,m=(s.regionRight-s.regionLeft)*_,v=(s.regionBottom-s.regionTop)*_):"cover"===n?(f>d?(_=u/r,g=s.regionLeft*_-(i*_-c)/2,p=s.regionTop*_):(_=c/i,g=s.regionLeft*_,p=s.regionTop*_-(r*_-u)/2),m=(s.regionRight-s.regionLeft)*_,v=(s.regionBottom-s.regionTop)*_):(g=0,p=0,m=0,v=0),t.style.position="absolute",t.style.left=g+"px",t.style.top=p+"px",t.style.width=m+"px",t.style.height=v+"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 I;("string"==typeof t||t instanceof String)&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return this._hasEngineResourceLoaded=!0,I.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{I.onWarning&&I.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((()=>{I.onWarning&&I.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 T,e}static async playVideo(t,e,i){return new Promise(((r,n)=>{t||n(new Error("Invalid video element.")),e||n(new Error("Invalid source.")),t.onloadedmetadata=async()=>{t.onloadedmetadata=null,await t.play(),r(t)},"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,void 0!==i&&setTimeout((()=>n(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(s.OS))return I.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(s.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){I._onLog&&(n=Date.now(),I._onLog("DCE: start loading static video: "+n));const t=await I.playVideo(this._video,this.videoSrc,4e3);if(I._onLog&&I._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 o=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,o{var n;try{this._video&&this._video.srcObject&&this.stop(),I._onLog&&I._onLog("DCE: ======before video========");const o=()=>{if(!this._video)throw l&&l.getTracks().forEach((t=>{t.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},a=this.getVideoSettings();let h,l;if("boolean"==typeof a.video&&(a.video={}),t)delete a.video.facingMode,a.video.deviceId={exact:t};else if(a.video.deviceId);else if(this._lastDeviceId)delete a.video.facingMode,a.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&I.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete a.video.facingMode,a.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&&(a.video.width=t,a.video.height=e)}else if(this.ifSkipCameraInspection);else if(a.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let t=a.video.facingMode;if(t instanceof Array&&t.length&&(t=t[0]),t=t.exact||t.ideal||t,"environment"===t){h=!0;const t=I.findBestRearCamera(this._allCameras);t&&(delete a.video.facingMode,a.video.deviceId={exact:t})}}e&&(a.video.width={ideal:e}),i&&(a.video.height={ideal:i}),I._onLog&&I._onLog("DCE: ======try getUserMedia========");let c=[0,500],u=null;const d=async t=>{for(let e of c){e&&await new Promise((t=>setTimeout(t,e))),o();try{I._onLog&&I._onLog("DCE: ask "+JSON.stringify(t)),l=await navigator.mediaDevices.getUserMedia(t);break}catch(t){if(o(),"NotFoundError"===t.name||"NotAllowedError"===t.name)throw t;u=t,I._onLog&&I._onLog("DCE: "+t.message||t)}}o()};let f;if(await d(a),!l){if(I._onLog&&I._onLog("DCE: ======try getUserMedia again========"),f=JSON.parse(JSON.stringify(a)),"object"==typeof f.video){["iPhone","iPad"].includes(s.OS)?(e>=1280||i>=1280?f.video.width=1280:e>=640||i>=640?f.video.width=640:(e<640||i<640)&&(f.video.width=320),delete f.video.height):h&&!a.video.deviceId?(delete f.video.facingMode,this._allCameras.length&&(f.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):f.video=!0}I._onLog&&I._onLog("DCE: "+f),await d(f)}if(l||(c=[1e3,2e3],await d(a)),l||await d(f),!l)throw u;const g=()=>{const t=l.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),o(),h&&!this.ifSkipCameraInspection){g();const t=I.findBestRearCamera(this._allCameras),e=null===(n=this._currentCamera)||void 0===n?void 0:n.deviceId;t&&t!=e&&(l.getTracks().forEach((t=>{t.stop()})),c=[0,500,1e3,2e3],a.video.deviceId={exact:t},await d(a))}I._onLog&&I._onLog("DCE: ======play video========"),o(),await I.playVideo(this._video,l,4e3),o(),I._onLog&&I._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const p=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=p,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),I._onLog&&I._onLog("DCE: got "+p),g(),this._renderSelCameraInfo();const m={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(m.deviceId&&(this._lastDeviceId=m.deviceId,this.ifSaveLastUsedCamera&&I.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),a.video.width&&a.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(a.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(a.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(m));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return this.promisePlay=null,m}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}})(),I._onLog&&(n=Date.now(),I._onLog("DCE: start opening camera: "+n));const a=await this.promisePlay;return I._onLog&&I._onLog("DCE: finish opening camera. Costs: "+(Date.now()-n)),this.playCallbackInfo=JSON.parse(JSON.stringify(a)),this._recordedStates.videoPlaying=!0,a}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','','',''].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 t of this.extraBindings)try{t(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(s.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(I.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&&(I._onLog&&I._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&&(I._onLog&&I._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=M(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.");if(!this._videoTrack)return null;return this._getHardwareScale()*this._softwareScale}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;return{factor:this._getHardwareScale()*this._softwareScale}}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=M(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=M(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=M(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:D.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=M(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=M(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=M(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;I._onLog&&(a=Date.now(),I._onLog("DCE: _drawImage(), START: "+a));let h=0,l=0,c=i,u=r,d=0,f=0,g=i,p=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&&(p=Math.round(n.dHeight)));let m=D.RGBA;o&&o.pixelFormat&&(m=o.pixelFormat);const v=t;if(o&&o.bUseWebGL){I._onLog&&I._onLog("DCE: _drawImage() in WebGL."),(v.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();t.bindBuffer(t.ARRAY_BUFFER,i);return 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(m)&&(o=m.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=m}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)},_=(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,[D.GREY,D.GREY32].includes(m)?1:0);let a,v,_=E.translate(E.identity(),-1,-1);_=E.scale(_,2,2),_=E.scale(_,1/t.canvas.width,1/t.canvas.height),a=E.translate(_,d,f),a=E.scale(a,g,p),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,a),v=E.translate(E.identity(),h/i,l/r),v=E.scale(v,c/i,u/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};let y;if(o(t,this._webGLTexture,e),_(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;I._onLog&&(o=Date.now(),I._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=D.RGBA;s&&s.pixelFormat&&(f=s.pixelFormat);let g,p,m,v=this._bWebGLSupported;s&&0==s.bUseWebGL&&(v=!1),v?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),g=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),g=this._reusedCvs);try{if(v)if(I._onLog&&I._onLog("DCE: _getImageData() in WebGL."),n)if(f===D.GREY){if(m=new Uint8Array(u*d*4),p=this._drawImage(g,t,e,i,{sx:a,sy:h,sWidth:l,sHeight:c,dWidth:u,dHeight:d},m,{pixelFormat:f,bUseWebGL:v}),m=this._transformPixelFormat(m,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=()=>{I._onLog&&I._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(I._onLog&&I._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),I._onLog&&I._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()?(I._onLog&&I._onLog("DCE: second timeout executes: "+Date.now()),e(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};t&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(e(),i()):0===this.refreshInterval?e():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this._isSingleFrameModeEnabled())throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,I._onLog&&I._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(I._onLog&&I._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 S(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 O(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,v=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 p.Control({positionHandler:v,actionHandler:b(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=p.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 m{constructor(t){super(new p.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()))}}};export{I as CameraEnhancer,F as DrawingItem}; +const t="undefined"==typeof self;let e,i,r,n,s;if("undefined"!=typeof navigator&&(e=navigator,i=e.userAgent,r=e.platform,n=e.mediaDevices),!t){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:e.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},n={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:r,search:"Win"},Mac:{str:r},Linux:{str:r}};let o="unknownBrowser",a=0,h="unknownOS";for(let e in t){const r=t[e]||{};let n=r.str||i,s=r.search||e,h=r.verStr||i,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=n.indexOf(s)){o=e;for(let t of l){let e=h.indexOf(t);if(-1!=e){a=parseFloat(h.substring(e+t.length+1));break}}break}}for(let t in n){const e=n[t]||{};let r=e.str||i,s=e.search||t;if(-1!=r.indexOf(s)){h=t;break}}"Linux"==h&&-1!=i.indexOf("Windows NT")&&(h="HarmonyOS"),s={browser:o,version:a,OS:h}}t&&(s={browser:"ssr",version:0,OS:"ssr"});const o="undefined"!=typeof WebAssembly&&i&&!(/Safari/.test(i)&&!/Chrome/.test(i)&&/\(.+\s11_2_([2-6]).*\)/.test(i)),a=!("undefined"==typeof Worker),h=!(!n||!n.getUserMedia),l=async()=>{let t=!1;if(h)try{(await n.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"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 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"./"})();var u={653:(t,e,i)=>{var r,n,s,o,a,h,l,c,u,d,f,g,p,m,v,_,y,b,w,C,S,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 O(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 E(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),p=g.vector,m=g.angle;if("miter"===e.strokeLineJoin&&(d=-n/Math.sin(m/2),f=new x.Point(p.x*d*s.x,p.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(p.x*d*s.x,p.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,p=-d*t*.5-u*e*.5,m=-d*e*.5+u*t*.5,v=(i=Math.abs(i))*i,_=(s=Math.abs(s))*s,y=m*m,b=p*p,w=v*_-v*y-_*b,C=0;if(w<0){var S=Math.sqrt(1-w/(v*_));i*=S,s*=S}else C=(o===a?-1:1)*Math.sqrt(w/(v*y+_*b));var T=C*i*m/s,O=-C*s*p/i,E=d*T-u*O+.5*t,D=u*T+d*O+.5*e,M=n(1,0,(p-T)/i,(m-O)/s),I=n((p-T)/i,(m-O)/s,(-p-T)/i,(-m-O)/s);0===a&&I>0?I-=2*l:1===a&&I<0&&(I+=2*l);for(var F=Math.ceil(Math.abs(I/l*2)),P=[],k=I/F,L=8/3*Math.sin(k/4)*Math.sin(k/4)/Math.sin(k/2),A=M+k,R=0;RC)for(var T=1,O=p.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,b=Math.max,w=Math.abs,C=[],S=[[],[]];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),w(c)<1e-12){if(w(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(m=u*u-4*d*c)<0||(0<(g=(-u+(v=_(m)))/(2*c))&&g<1&&C.push(g),0<(p=(-u-v)/(2*c))&&p<1&&C.push(p));for(var O,E,D,M=C.length,I=M;M--;)O=(D=1-(f=C[M]))*D*D*e+3*D*D*f*r+3*D*f*f*s+f*f*f*a,S[0][M]=O,E=D*D*D*i+3*D*D*f*n+3*D*f*f*o+f*f*f*h,S[1][M]=E;S[0][I]=e,S[1][I]=i,S[0][I+1]=a,S[1][I+1]=h;var F=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:b.apply(null,S[0]),y:b.apply(null,S[1])}];return x.cachesBoundsOfCurve&&(x.boundsOfCurveCache[l]=F),F},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*([^\)]+)\)/,p=function(t){return t},d?p=function(t,e){return t.style.opacity=e,t}:f&&(p=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?p(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var r in e)"opacity"===r?p(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,p=i.easing||n,m="startValue"in i&&i.startValue.length>0,v="startValue"in i?i.startValue:0,_="endValue"in i?i.endValue:100,y=i.byValue||(m?v.map((function(t,e){return _[e]-v[e]})):_-v);i.onStart&&i.onStart(),function t(i){var r=(e=i||+new Date)>u?c:e-l,n=r/c,b=m?v.map((function(t,e){return p(r,v[e],y[e],c)})):p(r,v,y,c),w=m?Math.abs((b[0]-v[0])/y[0]):Math.abs((b-v)/y);if(s.currentValue=m?b.slice():b,s.completionRate=w,s.durationRate=n,!o){if(!f(b,w,n))return e>u?(s.currentValue=m?_.slice():_,s.completionRate=1,s.durationRate=1,d(m?_.slice():_,1,1),g(_,1,1),void h()):(d(b,w,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 _=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,p=t.getAttribute("y")||0,m=t.getAttribute("preserveAspectRatio")||"",v=!l||!(l=l.match(_)),y=!d||!f||"100%"===d||"100%"===f,b=v&&y,w={},C="",S=0,x=0;if(w.width=0,w.height=0,w.toBeParsed=b,v&&(g||p)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(p)+") ",a=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",a),t.removeAttribute("x"),t.removeAttribute("y")),b)return w;if(v)return w.width=s(d),w.height=s(f),w;if(i=-parseFloat(l[1]),r=-parseFloat(l[2]),n=parseFloat(l[3]),o=parseFloat(l[4]),w.minX=i,w.minY=r,w.viewBoxWidth=n,w.viewBoxHeight=o,y?(w.width=n,w.height=o):(w.width=s(d),w.height=s(f),c=w.width/n,u=w.height/o),"none"!==(m=e.util.parsePreserveAspectRatioAttribute(m)).alignX&&("meet"===m.meetOrSlice&&(u=c=c>u?u:c),"slice"===m.meetOrSlice&&(u=c=c>u?c:u),S=w.width-n*c,x=w.height-o*c,"Mid"===m.alignX&&(S/=2),"Mid"===m.alignY&&(x/=2),"Min"===m.alignX&&(S=0),"Min"===m.alignY&&(x=0)),1===c&&1===u&&0===i&&0===r&&0===g&&0===p)return w;if((g||p)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(p)+") "),a=C+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(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),w}function b(t,e){var i="xlink:href",r=v(t,e.getAttribute(i).slice(1));if(r&&r.getAttribute(i)&&b(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 p(t,e){var i=e.canvas,r=t[i.uniScaleKey];return i.uniformScaling&&!r||!i.uniformScaling&&r}function m(t){return t.originX===l&&t.originY===l}function v(t,e,i){var r=t.lockScalingX,n=t.lockScalingY;return!((!r||!n)&&(e||!r&&!n||!i)&&(!r||"x"!==e)&&(!n||"y"!==e))}function _(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 b(t,e){return function(i,r,n,s){var o=e(i,r,n,s);return o&&g(t,_(i,r,n,s)),o}}function w(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 C(t){return t.flipX!==t.flipY}function S(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=w(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),C(l)&&(n=-n));var p=g!==n;if(p){var m=l._getTransformedDimensions().y;l.set("skewX",n),S(l,"skewY","scaleY","y",m)}return p}function T(t,e,i,r){var n,l=e.target,c=l._getTransformedDimensions(l.skewX,0),d=w(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),C(l)&&(n=-n));var p=g!==n;if(p){var m=l._getTransformedDimensions().x;l.set("skewY",n),S(l,"skewX","scaleX","x",m)}return p}function O(t,e,i,r,n){n=n||{};var s,o,a,h,l,u,f=e.target,g=f.lockScalingX,_=f.lockScalingY,y=n.by,b=p(t,f),C=v(f,y,b),S=e.gestureScale;if(C)return!1;if(S)o=e.scaleX*S,a=e.scaleY*S;else{if(s=w(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(),b&&!y){var x=Math.abs(s.x)+Math.abs(s.y),T=e.original,O=x/(Math.abs(h.x*T.scaleX/f.scaleX)+Math.abs(h.y*T.scaleY/f.scaleY));o=T.scaleX*O,a=T.scaleY*O}else o=Math.abs(s.x*f.scaleX/h.x),a=Math.abs(s.y*f.scaleY/h.y);m(e)&&(o*=2,a*=2),e.signX!==l&&"y"!==y&&(e.originX=c[e.originX],o*=-1,e.signX=l),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],a*=-1,e.signY=u)}var E=f.scaleX,D=f.scaleY;return y?("x"===y&&f.set("scaleX",o),"y"===y&&f.set("scaleY",a)):(!g&&f.set("scaleX",o),!_&&f.set("scaleY",a)),E!==f.scaleX||D!==f.scaleY}n.scaleCursorStyleHandler=function(t,e,r){var n=p(t,r),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),v(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=b("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,p=Math.floor(c/d)*d;Math.abs(c-p)0?s:a:(c>0&&(n=u===o?s:a),c<0&&(n=u===o?a:s),C(h)&&(n=n===s?a:s)),e.originX=n,b("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=w(e,l,l,i,r).y>0?o:h:(c>0&&(n=u===s?o:h),c<0&&(n=u===s?h:o),C(a)&&(n=n===o?h:o)),e.originY=n,b("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",_(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=b,n.getLocalPoint=w,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),p=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(p),l=f*e.util.sin(p)}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 m=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,p=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,p=-i.top),new x.Gradient({id:e.getAttribute("id"),type:o,coords:a,colorStops:f,gradientUnits:u,gradientTransform:l,offsetX:g,offsetY:p})}})}(),v=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:v(this.offsetX,r),offsetY:v(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(_(r,s),_(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(),p=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=p,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,p=f||g,m=0,v=0,_=!1;if(f){var y=this._cacheCanvas.width,b=this._cacheCanvas.height,w=l>y||c>b;_=w||(l<.9*y||c<.9*b)&&y>h&&b>h,w&&!a.capped&&(l>h||c>h)&&(m=.1*l,v=.1*c)}return this instanceof e.Text&&this.path&&(p=!0,_=!0,m+=this.getHeightOfLine(0)*this.zoomX,v+=this.getHeightOfLine(0)*this.zoomY),!!p&&(_?(o.width=Math.ceil(l+m),o.height=Math.ceil(c+v)):(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,p={x:0,y:0};g&&(l=g.blur,h=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),p.x=2*Math.round(o(g.offsetX)+l)*o(h.scaleX),p.y=2*Math.round(o(g.offsetY)+l)*o(h.scaleY)),c=f.width+p.x,u=f.height+p.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var m=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(m.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(m.width/2,m.height/2),"center","center");var v=this.canvas;m.add(this);var _=m.toCanvasElement(a||1,t);return this.shadow=s,this.set("canvas",v),n&&(this.group=n),this.set(r).setCoords(),m._objects=[],m.dispose(),m=null,_},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),b=x.util.degreesToRadians,w={left:-.5,center:0,right:.5},C={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=w[e]:e-=.5,"string"==typeof r?r=w[r]:r-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof n?n=C[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,b(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,b(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,-b(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=b(this.angle),n=this.getScaledWidth(),s=x.util.cos(r)*n,o=x.util.sin(r)*n;e="string"==typeof this.originX?w[this.originX]:this.originX-.5,i="string"==typeof t?w[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=[],p=t.indexOf("COMMON_PARTS"),m=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()," ",m?'transform="'+m+'" ':""].join(""),t[p]=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),p=o(s*r,u-f),m=-n/2,v=-s/2,_=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=E);var h,l,c={imageBuffer:a,destinationWidth:t,destinationHeight:e,targetCanvas:o};o.width=t,o.height=e,h=window.performance.now(),O.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=O}},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:O,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=b||o<0||o>=y||(h=4*(a*y+o),l=m[f*v+d],e+=p[h]*l,i+=p[h+1]*l,r+=p[h+2]*l,S||(n+=p[h+3]*l));C[s]=e,C[s+1]=i,C[s+2]=r,C[s+3]=S?p[s+3]:n}t.imageData=w},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,p=e.filterBackend.resources,m=0,v=0,_=i,y=0;for(p.sliceByTwo||(p.sliceByTwo=document.createElement("canvas")),((a=p.sliceByTwo).width<1.5*i||a.height=e)){P=r(1e3*s(x-w.x)),b[P]||(b[P]={});for(var L=C.y-y;L<=C.y+y;L++)L<0||L>=o||(k=r(1e3*s(L-w.y)),b[P][k]||(b[P][k]=f(n(i(P*m,2)+i(k*v,2))/1e3)),(T=b[P][k])>0&&(E+=T,D+=T*c[O=4*(L*e+x)],M+=T*c[O+1],I+=T*c[O+2],F+=T*c[O+3]))}d[O=4*(S*a+h)]=D/E,d[O+1]=M/E,d[O+2]=I/E,d[O+3]=F/E}return++h1&&k<-1||(y=2*k*k*k-3*k*k+1)>0&&(T+=y*f[3+(P=4*(F+E*e))],w+=y,f[P+3]<255&&(y=y*f[P+3]/250),C+=y*f[P],S+=y*f[P+1],x+=y*f[P+2],b+=y)}p[_]=C/b,p[_+1]=S/b,p[_+2]=x/b,p[_+3]=T/w}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,p=this._textLines.length;g=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 E=_+s+u;"rtl"===this.direction&&(E=this.width-E-d),l&&v&&(t.fillStyle=v,t.fillRect(E,c+C*r+o,d,this.fontSize/15)),u=f.left,d=f.width,l=g,v=m,r=n,o=a}else d+=f.kernedWidth;E=_+s+u,"rtl"===this.direction&&(E=this.width-E-d),t.fillStyle=m,g&&m&&t.fillRect(E,c+C*r+o,d-w,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),p=0,m=0;if(u===a&&(p=this.__charBounds[a][l].left),u>=a&&u1)&&(g/=this.lineHeight);var _=t.left+f+p,y=m-p,b=g,w=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",b=1,w=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(_=this.width-_-y),e.fillRect(_,t.top+t.topOffset+w,y,b),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")}}(),S=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,p=c.clientWidth/u,m=c.clientHeight/d;return h=x.util.transformPoint(h,a),(h=x.util.transformPoint(h,this.canvas.viewportTransform)).x*=p,h.y*=m,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=S(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:S(r[i-1])}:n?this.styles[t+i]={0:S(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?S(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]=S(r[i]));else if(n)for(var h=n[e?e-1:1];h&&i--;)this.styles[t][e+i]=S(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),p=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,p=f.length-1;g<=p;g++)h=g===p||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&&!m?(a.push(h),h=[],s=f,m=!0):s+=v,m||o||h.push(d),h=h.concat(c),g=o?0:this._measureWord([d],i,u),u++,m=!1,f>p&&(p=f);return _&&a.push(h),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+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:()=>{}},d={};function f(t){var e=d[t];if(void 0!==e)return e.exports;var i=d[t]={exports:{}};return u[t](i,i.exports,f),i.exports}f.d=(t,e)=>{for(var i in e)f.o(e,i)&&!f.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},f.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var g={};(()=>{let t;f.d(g,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?f(653).fabric:{version:"5.2.1"}})();var p=g.R;class m{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 p.Control({positionHandler:v,actionHandler:b(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=p.util.transformPoint({x:r,y:n},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}}const C=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;i_?(g=d,m=d/v,{x:n.x*i.width,y:(n.y-(f-m)/2)*i.width}):(g=f*v,m=f,{x:(n.x-(d-g)/2)*i.height,y:n.y*i.height}):"cover"===l?v>_?{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}},p.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();p.util.addListener(p.document,"touchend",this._onTouchEnd,{passive:!1}),p.util.addListener(p.document,"touchmove",this._onMouseMove,{passive:!1}),p.util.removeListener(i,r+"down",this._onMouseDown)},p.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?p.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=a?"":" ",g=0,m=0,v=0,_=!0,y=this._getWidthOfCharSpacing();r=r||0;0===c.length&&c.push([]),i-=r;for(var b=0;bi&&!_?(h.push(l),l=[],o=g,_=!0):o+=y,_||a||l.push(f),l=l.concat(u),m=a?0:this._measureWord([f],e,d),d++,_=!1,g>v&&(v=g);return b&&h.push(l),v+r>this.dynamicMinWidth&&(this.dynamicMinWidth=v-y+r),h});class x{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 p.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 m.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);const e=t._mapStyle.get(t.styleSelector);return e||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 m.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 m.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 x(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 O{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 E{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 E.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 E.multiply(t,[i,-r,0,r,i,0,0,0,1])}static scale(t,e,i){return E.multiply(t,[e,0,0,0,i,0,0,0,1])}}var D;!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"}(D||(D={}));const M=(t,e,i,r)=>{let n=e+Math.round((t-e)/i)*i;return r&&(n=Math.min(n,r)),n};class I{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();if(I._onLog&&I._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===D.GREY)h.stride=h.width;else h.stride=4*h.width;return 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",D.GREY],["grey32",D.GREY32],["rgba",D.RGBA],["rbga",D.RBGA],["grba",D.GRBA],["gbra",D.GBRA],["brga",D.BRGA],["bgra",D.BGRA]]),this.shaderPixelFormat=D.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,p=o/a;let m=1;if("contain"===s)if(p>g){m=d/o,r=(e-l)/m;n=(i-c-(f-d/p)/2)/m}else{m=f/a,n=(i-c)/m;r=(e-l-(d-f*p)/2)/m}else{if("cover"!==s)throw new Error("Unsupported object-fit.");if(p>g){m=f/a,n=(i-c)/m;r=(e-l+(f*p-d)/2)/m}else{m=d/o,r=(e-l)/m;n=(i-c+(d/p-f)/2)/m}}const v={x:r+"px",y:n+"px"},_=2*Math.round(Math.min(o,a)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px",y=_;await this._setLocalFocus(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;t.width=this.width,t.height=this.height;if("grey"===(this.pixelFormat||this.colorMode)){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{await this.selectCamera(this._selCam.value),this._bOpen||this.stop()},this._onResolutionSelChange=async()=>{let t,e;if(this._selRsl&&-1!=this._selRsl.selectedIndex){let i=this._selRsl.options[this._selRsl.selectedIndex];t=i.getAttribute("data-width"),e=i.getAttribute("data-height")}await this.setResolution(t,e),this._bOpen||this.stop()},this._onCloseBtnClick=()=>{this.close(!0)},this._bOpen=!1,this.isCameraEnhancer=!0,this.isDisposed=!1,this.disposed=!1,this.videoSrc=null,this.videoSettings={video:{width:{ideal:1280},height:{ideal:720},facingMode:{ideal:"environment"}}},this.iPlayRound=0,this.promisePlay=null,this._ifSaveLastUsedCamera=!1,this.ifSkipCameraInspection=!1,this._allCameras=[],this._currentCamera=null,this._videoTrack=null,this._lastDeviceId=void 0,this._vc_bPlayingVideoBeforeHide=!1,this._ev_documentHideEvent=()=>{if(!this._isSingleFrameModeEnabled())if("visible"===document.visibilityState){if(I._onLog&&I._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];this._video.srcObject.active&&t&&!t.muted?this._video.play():this.play()}}else"hidden"===document.visibilityState&&(I._onLog&&I._onLog("DCE: document hidden."),["iPhone","iPad","Mac"].includes(s.OS)?(this._vc_bPlayingVideoBeforeHide=!0,this._video&&this._video.pause()):this._video&&!this._video.paused?(this._vc_bPlayingVideoBeforeHide=!0,this._video.pause()):this._vc_bPlayingVideoBeforeHide=!1)},this.containerClassName="dce-video-container",this._elContainer=null,this._videoContainer=null,this._video=null,this.videoFit="contain",this._cvsScanRegion=null,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=2,this._bShowScanRegionMask=!0,this._bShowScanRegionLaser=void 0,this._defaultBShowScanRegionLaser=!1,this._scanRegion=null,this._arrScanRegionOverlays=[],this._layerBaseCvs=null,this._drawingLayerOfTip=null,this._tipArgs={x:void 0,y:void 0,width:void 0,duration:void 0,autoShowSuggestedTip:void 0},this._hideTipTimeoutId=null,this.onTipSuggested=null,this._cvsViewDecorator=null,this._decoratorType=[],this._decoratorArea=null,this._viewDecoratorInfo={rectangle:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},focus:{lineWidth:4,strokeStyle:"rgb(254,142,20)",fillStyle:"transparent",maskFillStyle:"transparent"},crossline:{lineWidth:2,strokeStyle:"rgb(254,142,20)"},crosshair:{lineWidth:4,strokeStyle:"rgb(254,142,20)"}},this._croppingRegions=void 0,this._defaultCroppingRegions=[null],this.bIncreaseRegionIndexAuto=!0,this._croppingRegionIndex=0,this._loopInterval=void 0,this._defaultLoopInterval=0,this._maxNumberOfFramesInBuffer=void 0,this._defaultMaxNumberOfFramesInBuffer=1,this._frameQueue=[],this._bFetchingLoopStarted=!1,this._refreshInterval=void 0,this._defaultRefreshInterval=-1,this._updateLayersTimeout=500,this._updateLayers=()=>{this._cvsScanRegion&&(this._cvsScanRegion.style.display="none"),this._divScanLight&&(this._divScanLight.style.display="none"),this._cvsViewDecorator&&(this._cvsViewDecorator.style.display="none");for(let t of this._arrScanRegionOverlays)t&&(t.style.display="none");this._resizeTimeoutId&&clearTimeout(this._resizeTimeoutId),this._resizeTimeoutId=setTimeout((()=>{if(!this.isDisposed||!this.disposed){this.ifShowScanRegionMask&&this.showScanRegionMask(),this.ifShowScanRegionLaser&&this.showScanRegionLaser(),this._cvsViewDecorator&&this.showViewDecorator(),this._updateScanRegionCanvas(),this._updateScanAreaDiv(),this._updateViewDecorator();for(let t of this._arrScanRegionOverlays)t&&(t.style.display="",this._updateScanRegionOverlay(t));this._updateDrawingLayersSize(),this._updateVideoContainerStyle()}}),this._updateLayersTimeout)},this._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:o,worker:a,getUserMedia:h,camera:await l(),browser:s.browser,version:s.version,OS:s.OS}))()}static set engineResourcePath(e){if(this._hasEngineResourceLoaded)throw new Error("`engineResourcePath` is not allowed to change after `createInstance` is called.");I._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 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){I._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=I._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",I.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?(_=c/i,g=0,p=(u-r*_)/2):(_=u/r,g=(c-i*_)/2,p=0),g+=s.regionLeft*_,p+=s.regionTop*_,m=(s.regionRight-s.regionLeft)*_,v=(s.regionBottom-s.regionTop)*_):"cover"===n?(f>d?(_=u/r,g=s.regionLeft*_-(i*_-c)/2,p=s.regionTop*_):(_=c/i,g=s.regionLeft*_,p=s.regionTop*_-(r*_-u)/2),m=(s.regionRight-s.regionLeft)*_,v=(s.regionBottom-s.regionTop)*_):(g=0,p=0,m=0,v=0),t.style.position="absolute",t.style.left=g+"px",t.style.top=p+"px",t.style.width=m+"px",t.style.height=v+"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 I;("string"==typeof t||t instanceof String)&&(t=JSON.parse(t));for(let i in t)e[i]=t[i];return this._hasEngineResourceLoaded=!0,I.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{I.onWarning&&I.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((()=>{I.onWarning&&I.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 T,e}static async playVideo(t,e,i){return new Promise(((r,n)=>{t||n(new Error("Invalid video element.")),e||n(new Error("Invalid source.")),t.onloadedmetadata=async()=>{t.onloadedmetadata=null,await t.play(),r(t)},"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,void 0!==i&&setTimeout((()=>n(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(s.OS))return I.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(s.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){I._onLog&&(n=Date.now(),I._onLog("DCE: start loading static video: "+n));const t=await I.playVideo(this._video,this.videoSrc,4e3);if(I._onLog&&I._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 o=++this.iPlayRound;if(this.promisePlay&&(await this.promisePlay,o{var n;try{this._video&&this._video.srcObject&&this.stop(),I._onLog&&I._onLog("DCE: ======before video========");const o=()=>{if(!this._video)throw l&&l.getTracks().forEach((t=>{t.stop()})),this._videoTrack=null,this._currentCamera=null,new Error("'video' is null or undefined.")},a=this.getVideoSettings();let h,l;if("boolean"==typeof a.video&&(a.video={}),t)delete a.video.facingMode,a.video.deviceId={exact:t};else if(a.video.deviceId);else if(this._lastDeviceId)delete a.video.facingMode,a.video.deviceId={exact:this._lastDeviceId};else if(this.ifSaveLastUsedCamera&&I.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete a.video.facingMode,a.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&&(a.video.width=t,a.video.height=e)}else if(this.ifSkipCameraInspection);else if(a.video.facingMode){if(await this.getAllCameras(!1),!this._video)throw new Error("'video' is null or undefined.");let t=a.video.facingMode;if(t instanceof Array&&t.length&&(t=t[0]),t=t.exact||t.ideal||t,"environment"===t){h=!0;const t=I.findBestRearCamera(this._allCameras);t&&(delete a.video.facingMode,a.video.deviceId={exact:t})}}e&&(a.video.width={ideal:e}),i&&(a.video.height={ideal:i}),I._onLog&&I._onLog("DCE: ======try getUserMedia========");let c=[0,500],u=null;const d=async t=>{for(let e of c){e&&await new Promise((t=>setTimeout(t,e))),o();try{I._onLog&&I._onLog("DCE: ask "+JSON.stringify(t)),l=await navigator.mediaDevices.getUserMedia(t);break}catch(t){if(o(),"NotFoundError"===t.name||"NotAllowedError"===t.name)throw t;u=t,I._onLog&&I._onLog("DCE: "+t.message||t)}}o()};let f;if(await d(a),!l){if(I._onLog&&I._onLog("DCE: ======try getUserMedia again========"),f=JSON.parse(JSON.stringify(a)),"object"==typeof f.video){["iPhone","iPad"].includes(s.OS)?(e>=1280||i>=1280?f.video.width=1280:e>=640||i>=640?f.video.width=640:(e<640||i<640)&&(f.video.width=320),delete f.video.height):h&&!a.video.deviceId?(delete f.video.facingMode,this._allCameras.length&&(f.video.deviceId={ideal:this._allCameras[this._allCameras.length-1].deviceId})):f.video=!0}I._onLog&&I._onLog("DCE: "+f),await d(f)}if(l||(c=[1e3,2e3],await d(a)),l||await d(f),!l)throw u;const g=()=>{const t=l.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),o(),h&&!this.ifSkipCameraInspection){g();const t=I.findBestRearCamera(this._allCameras),e=null===(n=this._currentCamera)||void 0===n?void 0:n.deviceId;t&&t!=e&&(l.getTracks().forEach((t=>{t.stop()})),c=[0,500,1e3,2e3],a.video.deviceId={exact:t},await d(a))}I._onLog&&I._onLog("DCE: ======play video========"),o(),await I.playVideo(this._video,l,4e3),o(),I._onLog&&I._onLog("DCE: ======played video========"),this._bgLoading&&(this._bgLoading.style.animationPlayState="paused");const p=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=p,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got")),I._onLog&&I._onLog("DCE: got "+p),g(),this._renderSelCameraInfo();const m={width:this._video.videoWidth,height:this._video.videoHeight,deviceId:this._currentCamera&&this._currentCamera.deviceId};if(m.deviceId&&(this._lastDeviceId=m.deviceId,this.ifSaveLastUsedCamera&&I.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",this._lastDeviceId),a.video.width&&a.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(a.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(a.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(m));setTimeout((()=>{this.isDisposed&&this.disposed||e.apply(this,[t])}),0)}}return this.promisePlay=null,m}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}})(),I._onLog&&(n=Date.now(),I._onLog("DCE: start opening camera: "+n));const a=await this.promisePlay;return I._onLog&&I._onLog("DCE: finish opening camera. Costs: "+(Date.now()-n)),this.playCallbackInfo=JSON.parse(JSON.stringify(a)),this._recordedStates.videoPlaying=!0,a}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','','',''].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 t of this.extraBindings)try{t(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(s.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(I.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&&(I._onLog&&I._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&&(I._onLog&&I._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=M(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.");if(!this._videoTrack)return null;return this._getHardwareScale()*this._softwareScale}getZoomSettings(){if(this._assertOpen(),this._isSingleFrameModeEnabled())throw new Error("'getZoom()' is unavailable in singleFrameMode.");if(!this._videoTrack)return null;return{factor:this._getHardwareScale()*this._softwareScale}}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=M(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=M(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=M(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:D.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=M(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),n=M(Math.sqrt((e||this._focusParameters.fds.step)*r),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=M(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;I._onLog&&(a=Date.now(),I._onLog("DCE: _drawImage(), START: "+a));let h=0,l=0,c=i,u=r,d=0,f=0,g=i,p=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&&(p=Math.round(n.dHeight)));let m=D.RGBA;o&&o.pixelFormat&&(m=o.pixelFormat);const v=t;if(!o||!o.bUseWebGL){I._onLog&&I._onLog("DCE: _drawImage() in context2d."),v.ctx2d||(v.ctx2d=v.getContext("2d",{willReadFrequently:!0}));const t=v.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(v.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();t.bindBuffer(t.ARRAY_BUFFER,i);return 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(m)&&(o=m.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=n(t,t.VERTEX_SHADER,s),l=r(t,[h,n(t,t.FRAGMENT_SHADER,a)]);this._webGLProgramInfo={program:l,attribLocations:{vertexPosition:t.getAttribLocation(l,"a_position"),texPosition:t.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(l,"u_image"),uColorFactor:t.getUniformLocation(l,"uColorFactor"),uMatrix:t.getUniformLocation(l,"u_matrix"),uTextureMatrix:t.getUniformLocation(l,"u_textureMatrix")}},this._webGLBuffers=e(t),this._webGLTexture=i(t),this.shaderPixelFormat=m}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)},_=(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,[D.GREY,D.GREY32].includes(m)?1:0);let a,v,_=E.translate(E.identity(),-1,-1);_=E.scale(_,2,2),_=E.scale(_,1/t.canvas.width,1/t.canvas.height),a=E.translate(_,d,f),a=E.scale(a,g,p),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,a),v=E.translate(E.identity(),h/i,l/r),v=E.scale(v,c/i,u/r),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,v),t.drawArrays(t.TRIANGLES,0,6)};let y;if(o(t,this._webGLTexture,e),_(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;I._onLog&&(o=Date.now(),I._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=D.RGBA;s&&s.pixelFormat&&(f=s.pixelFormat);let g,p,m,v=this._bWebGLSupported;s&&0==s.bUseWebGL&&(v=!1),v?(this._reusedWebGLCvs||(this._reusedWebGLCvs=document.createElement("canvas")),g=this._reusedWebGLCvs):(this._reusedCvs||(this._reusedCvs=document.createElement("canvas")),g=this._reusedCvs);try{if(v)if(I._onLog&&I._onLog("DCE: _getImageData() in WebGL."),n)if(f===D.GREY){if(m=new Uint8Array(u*d*4),p=this._drawImage(g,t,e,i,{sx:a,sy:h,sWidth:l,sHeight:c,dWidth:u,dHeight:d},m,{pixelFormat:f,bUseWebGL:v}),m=this._transformPixelFormat(m,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=()=>{I._onLog&&I._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(I._onLog&&I._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),I._onLog&&I._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()?(I._onLog&&I._onLog("DCE: second timeout executes: "+Date.now()),e(),i()):this.stopFetchingLoop())}),this.refreshInterval)))};t&&(this._frameQueue.length0&&i()):this.refreshInterval>0?(e(),i()):0===this.refreshInterval?e():this.refreshInterval),this._frameLoopTimeoutId&&clearTimeout(this._frameLoopTimeoutId),this._frameLoopTimeoutId=setTimeout((()=>{this.isDisposed&&this.disposed||this._fetchingLoop(!0)}),this.loopInterval)}startFetchingLoop(){if(this.isDisposed&&this.disposed)throw Error("The 'CameraEnhancer' instance has been disposed.");if(this._assertOpen(),this._isSingleFrameModeEnabled())throw Error("'startFetchingLoop()' is unavailable in singleFrameMode.");this.isFetchingLoopStarted()||(this._bFetchingLoopStarted=!0,this._recordedStates.fetchingLoopStart=!0,I._onLog&&I._onLog("DCE: start fetching loop: "+Date.now()),this._fetchingLoop(!0))}isFetchingLoopStarted(){return this._bFetchingLoopStarted}stopFetchingLoop(){this._bFetchingLoopStarted&&(I._onLog&&I._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 S(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 O(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,v=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 p.Control({positionHandler:v,actionHandler:b(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=p.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 m{constructor(t){super(new p.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()))}}};export{I as CameraEnhancer,F as DrawingItem}; diff --git a/package.json b/package.json index deef71e..9314b93 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dynamsoft-camera-enhancer", - "version": "3.3.7", + "version": "3.3.8", "description": "Allow your website to easily control cameras on desktop and mobile devices.", "private": false, "homepage": "https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/?ver=latest", diff --git a/samples.url b/samples.url index 05d6aec..166523c 100644 --- a/samples.url +++ b/samples.url @@ -1,2 +1,2 @@ [InternetShortcut] -URL=https://github.com/Dynamsoft/camera-enhancer-javascript-samples/tree/v3.3.7 \ No newline at end of file +URL=https://github.com/Dynamsoft/camera-enhancer-javascript-samples/tree/v3.3.8 \ No newline at end of file