@mlightcad/cad-simple-viewer 1.6.1 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/dist/cad-simple-viewer.js +5714 -4936
  2. package/dist/cad-simple-viewer.umd.cjs +180 -29
  3. package/lib/app/AcApSettingManager.d.ts.map +1 -1
  4. package/lib/app/AcApSettingManager.js +1 -0
  5. package/lib/app/AcApSettingManager.js.map +1 -1
  6. package/lib/command/draw/AcApArcCmd.d.ts.map +1 -1
  7. package/lib/command/draw/AcApArcCmd.js +28 -312
  8. package/lib/command/draw/AcApArcCmd.js.map +1 -1
  9. package/lib/command/draw/AcApCircleCmd.d.ts.map +1 -1
  10. package/lib/command/draw/AcApCircleCmd.js +10 -42
  11. package/lib/command/draw/AcApCircleCmd.js.map +1 -1
  12. package/lib/command/markup/AcApMarkupTextCmd.d.ts.map +1 -1
  13. package/lib/command/markup/AcApMarkupTextCmd.js +8 -2
  14. package/lib/command/markup/AcApMarkupTextCmd.js.map +1 -1
  15. package/lib/command/markup/AcApMarkupTextEdit.d.ts.map +1 -1
  16. package/lib/command/markup/AcApMarkupTextEdit.js +3 -1
  17. package/lib/command/markup/AcApMarkupTextEdit.js.map +1 -1
  18. package/lib/command/markup/AcApMarkupUtil.d.ts.map +1 -1
  19. package/lib/command/markup/AcApMarkupUtil.js +3 -2
  20. package/lib/command/markup/AcApMarkupUtil.js.map +1 -1
  21. package/lib/command/measure/AcApMeasureArcCmd.d.ts +22 -25
  22. package/lib/command/measure/AcApMeasureArcCmd.d.ts.map +1 -1
  23. package/lib/command/measure/AcApMeasureArcCmd.js +480 -256
  24. package/lib/command/measure/AcApMeasureArcCmd.js.map +1 -1
  25. package/lib/command/measure/AcApMeasureArcLock.d.ts +40 -0
  26. package/lib/command/measure/AcApMeasureArcLock.d.ts.map +1 -0
  27. package/lib/command/measure/AcApMeasureArcLock.js +226 -0
  28. package/lib/command/measure/AcApMeasureArcLock.js.map +1 -0
  29. package/lib/command/measure/AcApMeasurementGeometry.d.ts.map +1 -1
  30. package/lib/command/measure/AcApMeasurementGeometry.js +9 -9
  31. package/lib/command/measure/AcApMeasurementGeometry.js.map +1 -1
  32. package/lib/command/measure/AcApMeasurementSidecar.d.ts.map +1 -1
  33. package/lib/command/measure/AcApMeasurementSidecar.js +12 -7
  34. package/lib/command/measure/AcApMeasurementSidecar.js.map +1 -1
  35. package/lib/command/measure/AcApMeasurementStore.d.ts +2 -0
  36. package/lib/command/measure/AcApMeasurementStore.d.ts.map +1 -1
  37. package/lib/command/measure/AcApMeasurementStore.js +4 -0
  38. package/lib/command/measure/AcApMeasurementStore.js.map +1 -1
  39. package/lib/command/measure/AcApMeasurementTypes.d.ts +6 -0
  40. package/lib/command/measure/AcApMeasurementTypes.d.ts.map +1 -1
  41. package/lib/command/measure/entity/AcApMeasureArcEntity.d.ts +24 -22
  42. package/lib/command/measure/entity/AcApMeasureArcEntity.d.ts.map +1 -1
  43. package/lib/command/measure/entity/AcApMeasureArcEntity.js +104 -41
  44. package/lib/command/measure/entity/AcApMeasureArcEntity.js.map +1 -1
  45. package/lib/command/measure/entity/AcApMeasureDrawUtil.d.ts +35 -38
  46. package/lib/command/measure/entity/AcApMeasureDrawUtil.d.ts.map +1 -1
  47. package/lib/command/measure/entity/AcApMeasureDrawUtil.js +42 -53
  48. package/lib/command/measure/entity/AcApMeasureDrawUtil.js.map +1 -1
  49. package/lib/command/measure/entity/AcApMeasureEntityFactory.d.ts.map +1 -1
  50. package/lib/command/measure/entity/AcApMeasureEntityFactory.js +1 -1
  51. package/lib/command/measure/entity/AcApMeasureEntityFactory.js.map +1 -1
  52. package/lib/command/modify/AcApEraseCmd.d.ts +1 -0
  53. package/lib/command/modify/AcApEraseCmd.d.ts.map +1 -1
  54. package/lib/command/modify/AcApEraseCmd.js +4 -2
  55. package/lib/command/modify/AcApEraseCmd.js.map +1 -1
  56. package/lib/editor/grip/AcEdGripEditSession.d.ts.map +1 -1
  57. package/lib/editor/grip/AcEdGripEditSession.js +2 -0
  58. package/lib/editor/grip/AcEdGripEditSession.js.map +1 -1
  59. package/lib/editor/input/AcEdOsnapCenterMarks.d.ts +23 -0
  60. package/lib/editor/input/AcEdOsnapCenterMarks.d.ts.map +1 -0
  61. package/lib/editor/input/AcEdOsnapCenterMarks.js +240 -0
  62. package/lib/editor/input/AcEdOsnapCenterMarks.js.map +1 -0
  63. package/lib/editor/input/AcEdOsnapResolver.d.ts +18 -0
  64. package/lib/editor/input/AcEdOsnapResolver.d.ts.map +1 -1
  65. package/lib/editor/input/AcEdOsnapResolver.js +159 -10
  66. package/lib/editor/input/AcEdOsnapResolver.js.map +1 -1
  67. package/lib/editor/input/marker/AcEdMarker.d.ts +1 -1
  68. package/lib/editor/input/marker/AcEdMarker.d.ts.map +1 -1
  69. package/lib/editor/input/marker/AcEdMarker.js +11 -1
  70. package/lib/editor/input/marker/AcEdMarker.js.map +1 -1
  71. package/lib/editor/input/marker/AcEdOSnapMarkerManager.d.ts +17 -1
  72. package/lib/editor/input/marker/AcEdOSnapMarkerManager.d.ts.map +1 -1
  73. package/lib/editor/input/marker/AcEdOSnapMarkerManager.js +71 -10
  74. package/lib/editor/input/marker/AcEdOSnapMarkerManager.js.map +1 -1
  75. package/lib/editor/input/ui/AcEdFloatingInput.d.ts.map +1 -1
  76. package/lib/editor/input/ui/AcEdFloatingInput.js +4 -0
  77. package/lib/editor/input/ui/AcEdFloatingInput.js.map +1 -1
  78. package/lib/i18n/cs/jig.d.ts +3 -0
  79. package/lib/i18n/cs/jig.d.ts.map +1 -1
  80. package/lib/i18n/cs/jig.js +6 -3
  81. package/lib/i18n/cs/jig.js.map +1 -1
  82. package/lib/i18n/en/jig.d.ts +3 -0
  83. package/lib/i18n/en/jig.d.ts.map +1 -1
  84. package/lib/i18n/en/jig.js +6 -3
  85. package/lib/i18n/en/jig.js.map +1 -1
  86. package/lib/i18n/tr/jig.d.ts +3 -0
  87. package/lib/i18n/tr/jig.d.ts.map +1 -1
  88. package/lib/i18n/tr/jig.js +6 -3
  89. package/lib/i18n/tr/jig.js.map +1 -1
  90. package/lib/i18n/zh/jig.d.ts +3 -0
  91. package/lib/i18n/zh/jig.d.ts.map +1 -1
  92. package/lib/i18n/zh/jig.js +6 -3
  93. package/lib/i18n/zh/jig.js.map +1 -1
  94. package/lib/service/AcApEntityService.d.ts +4 -2
  95. package/lib/service/AcApEntityService.d.ts.map +1 -1
  96. package/lib/service/AcApEntityService.js +14 -10
  97. package/lib/service/AcApEntityService.js.map +1 -1
  98. package/lib/ui/AcApDrawStyle.d.ts +19 -1
  99. package/lib/ui/AcApDrawStyle.d.ts.map +1 -1
  100. package/lib/ui/AcApDrawStyle.js +22 -1
  101. package/lib/ui/AcApDrawStyle.js.map +1 -1
  102. package/lib/ui/AcApDrawStyleToolbar.d.ts +12 -7
  103. package/lib/ui/AcApDrawStyleToolbar.d.ts.map +1 -1
  104. package/lib/ui/AcApDrawStyleToolbar.js +173 -52
  105. package/lib/ui/AcApDrawStyleToolbar.js.map +1 -1
  106. package/lib/util/AcApCssColor.d.ts +8 -0
  107. package/lib/util/AcApCssColor.d.ts.map +1 -0
  108. package/lib/util/AcApCssColor.js +20 -0
  109. package/lib/util/AcApCssColor.js.map +1 -0
  110. package/lib/util/AcApMeasurementUtil.d.ts.map +1 -1
  111. package/lib/util/AcApMeasurementUtil.js +3 -2
  112. package/lib/util/AcApMeasurementUtil.js.map +1 -1
  113. package/lib/util/AcApScreenHitTest.d.ts +5 -1
  114. package/lib/util/AcApScreenHitTest.d.ts.map +1 -1
  115. package/lib/util/AcApScreenHitTest.js +9 -3
  116. package/lib/util/AcApScreenHitTest.js.map +1 -1
  117. package/lib/util/index.d.ts +1 -0
  118. package/lib/util/index.d.ts.map +1 -1
  119. package/lib/util/index.js +1 -0
  120. package/lib/util/index.js.map +1 -1
  121. package/lib/view/AcTrView2d.d.ts +6 -1
  122. package/lib/view/AcTrView2d.d.ts.map +1 -1
  123. package/lib/view/AcTrView2d.js +62 -34
  124. package/lib/view/AcTrView2d.js.map +1 -1
  125. package/package.json +5 -5
@@ -1,8 +1,8 @@
1
- (function(y,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("@mlightcad/data-model"),require("@mlightcad/three-renderer"),require("three"),require("three/examples/jsm/libs/stats.module"),require("three/examples/jsm/renderers/CSS2DRenderer.js"),require("@mlightcad/mtext-renderer"),require("three/examples/jsm/lines/Line2.js"),require("three/examples/jsm/lines/LineGeometry.js"),require("three/examples/jsm/lines/LineMaterial.js"),require("lodash-es")):typeof define=="function"&&define.amd?define(["exports","@mlightcad/data-model","@mlightcad/three-renderer","three","three/examples/jsm/libs/stats.module","three/examples/jsm/renderers/CSS2DRenderer.js","@mlightcad/mtext-renderer","three/examples/jsm/lines/Line2.js","three/examples/jsm/lines/LineGeometry.js","three/examples/jsm/lines/LineMaterial.js","lodash-es"],u):(y=typeof globalThis<"u"?globalThis:y||self,u(y["cad-simple-viewer"]={},y.dataModel,y.threeRenderer,y.THREE,y.Stats,y.CSS2DRenderer_js,y.mtextRenderer,y.Line2_js,y.LineGeometry_js,y.LineMaterial_js,y.lodashEs))})(this,(function(y,u,M,Fh,zh,Nh,D,Rh,Vh,Gh,Bo){"use strict";var yb=Object.defineProperty;var gb=(y,u,M)=>u in y?yb(y,u,{enumerable:!0,configurable:!0,writable:!0,value:M}):y[u]=M;var E=(y,u,M)=>gb(y,typeof u!="symbol"?u+"":u,M);function Kh(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const T=Kh(Fh),Fo='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" aria-hidden="true"><path fill="currentColor" d="M737.216 357.952 704 349.824l-11.776-32a192.064 192.064 0 0 0-367.424 23.04l-8.96 39.04-39.04 8.96A192.064 192.064 0 0 0 320 768h368a207.81 207.81 0 0 0 207.808-208 208.32 208.32 0 0 0-158.592-202.048m15.168-62.208A272.32 272.32 0 0 1 959.744 560a271.81 271.81 0 0 1-271.552 272H320a256 256 0 0 1-57.536-505.536 256.128 256.128 0 0 1 489.92-30.72"/><text x="512" y="580" text-anchor="middle" dominant-baseline="middle" font-size="300" font-family="Arial,sans-serif" fill="currentColor" font-weight="bold">ML</text></svg>',tn="mlightcad",zo="https://mlightcad.github.io/cad-viewer/",No="https://mlightcad.github.io/cad-viewer/docs/",Ro="https://github.com/mlightcad/cad-viewer";function Ds(s){const e=document.createElement("span");e.className=(s==null?void 0:s.className)??"ml-brand-mark-icon",e.setAttribute("role","img"),e.setAttribute("aria-label",tn),e.innerHTML=Fo;const t=(s==null?void 0:s.size)??"40px";return e.style.width=t,e.style.height=t,e}function Vo(s){const e=document.createElement("div");e.className=(s==null?void 0:s.className)??"ml-brand-mark",e.setAttribute("role","img"),e.setAttribute("aria-label",tn);const t=Ds({className:"ml-brand-mark-icon",size:(s==null?void 0:s.iconSize)??"40px"});t.removeAttribute("role"),t.removeAttribute("aria-label");const i=document.createElement("span");return i.className="ml-brand-mark-label",i.textContent=tn,e.appendChild(t),e.appendChild(i),e}function bt(s,e,t,i,n,r){const o=n-t,a=r-i,l=o*o+a*a;if(l<1e-10)return Math.hypot(s-t,e-i);let c=((s-t)*o+(e-i)*a)/l;return c=Math.max(0,Math.min(1,c)),Math.hypot(s-(t+c*o),e-(i+c*a))}function Os(s,e,t,i=!1){if(t.length===0)return 1/0;if(t.length===1)return Math.hypot(s-t[0].x,e-t[0].y);let n=1/0;const r=i?t.length:t.length-1;for(let o=0;o<r;o++){const a=t[o],l=t[(o+1)%t.length];n=Math.min(n,bt(s,e,a.x,a.y,l.x,l.y))}return n}function nn(s,e,t,i){const n=Math.min(t.x,i.x),r=Math.max(t.x,i.x),o=Math.min(t.y,i.y),a=Math.max(t.y,i.y);return Os(s,e,[{x:n,y:o},{x:r,y:o},{x:r,y:a},{x:n,y:a}],!0)}function Go(s,e,t,i){const n=Math.min(t.x,i.x),r=Math.max(t.x,i.x),o=Math.min(t.y,i.y),a=Math.max(t.y,i.y);return s>=n&&s<=r&&e>=o&&e<=a}function js(s,e,t,i,n){return Math.abs(Math.hypot(s-t,e-i)-n)}function Ko(s,e,t){let i=!1;for(let n=0,r=t.length-1;n<t.length;r=n++){const o=t[n].x,a=t[n].y,l=t[r].x,c=t[r].y;a>e!=c>e&&s<(l-o)*(e-a)/(c-a+1e-15)+o&&(i=!i)}return i}function Bs(s,e,t,i,n,r,o,a){let c=1/0;const h=a?r-o:o-r,p=Math.abs(h);for(let m=0;m<=24;m++){const g=m/24,f=a?r-g*p:r+g*p,w=t+n*Math.cos(f),v=i+n*Math.sin(f);c=Math.min(c,Math.hypot(s-w,e-v))}return c}const Uh=8;function oe(s,e,t){return{x:s.x+e,y:s.y+t}}function sn(s,e,t){return{tip:oe(s.tip,e,t),anchor:oe(s.anchor,e,t),text:s.text}}function rn(s){switch(s.type){case"cloud":case"rect":case"highlight":return{x:(s.corner1.x+s.corner2.x)/2,y:(s.corner1.y+s.corner2.y)/2};case"circle":return{...s.center};case"callout":return{x:(s.tip.x+s.anchor.x)/2,y:(s.tip.y+s.anchor.y)/2};case"arrow":case"line":return{x:(s.start.x+s.end.x)/2,y:(s.start.y+s.end.y)/2};case"text":case"stamp":case"symbol":return{...s.position};default:return}}function Fs(s,e,t){switch(s.type){case"cloud":return{...s,corner1:oe(s.corner1,e,t),corner2:oe(s.corner2,e,t),callout:s.callout?sn(s.callout,e,t):void 0};case"rect":return{...s,corner1:oe(s.corner1,e,t),corner2:oe(s.corner2,e,t),callout:s.callout?sn(s.callout,e,t):void 0};case"highlight":return{...s,corner1:oe(s.corner1,e,t),corner2:oe(s.corner2,e,t)};case"circle":return{...s,center:oe(s.center,e,t),callout:s.callout?sn(s.callout,e,t):void 0};case"callout":return{...s,tip:oe(s.tip,e,t),anchor:oe(s.anchor,e,t)};case"arrow":case"line":return{...s,start:oe(s.start,e,t),end:oe(s.end,e,t)};case"text":case"stamp":case"symbol":return{...s,position:oe(s.position,e,t)}}}function on(s,e,t,i){const n=t(s.tip),r=t(s.anchor);return bt(e.x,e.y,n.x,n.y,r.x,r.y)<=i}function Uo(s,e){e&&(s.expandByPoint(e.tip),s.expandByPoint(e.anchor))}function Ho(s){const e=new u.AcGeBox2d;switch(s.type){case"line":case"arrow":e.expandByPoint(s.start).expandByPoint(s.end);break;case"rect":case"cloud":e.expandByPoint(s.corner1).expandByPoint(s.corner2),Uo(e,s.callout);break;case"highlight":e.expandByPoint(s.corner1).expandByPoint(s.corner2);break;case"circle":e.expandByPoint({x:s.center.x-s.radius,y:s.center.y-s.radius}).expandByPoint({x:s.center.x+s.radius,y:s.center.y+s.radius}),Uo(e,s.callout);break;case"callout":e.expandByPoint(s.tip).expandByPoint(s.anchor);break;case"text":case"stamp":case"symbol":e.expandByPoint(s.position);break;default:return}return e.isEmpty()?void 0:e}function zs(s,e,t,i){switch(s.type){case"line":case"arrow":{const n=t(s.start),r=t(s.end);return bt(e.x,e.y,n.x,n.y,r.x,r.y)<=i}case"rect":return nn(e.x,e.y,t(s.corner1),t(s.corner2))<=i?!0:s.callout?on(s.callout,e,t,i):!1;case"cloud":return nn(e.x,e.y,t(s.corner1),t(s.corner2))<=i+Uh?!0:s.callout?on(s.callout,e,t,i):!1;case"circle":{const n=t(s.center),r=t({x:s.center.x+s.radius,y:s.center.y}),o=Math.hypot(r.x-n.x,r.y-n.y);return js(e.x,e.y,n.x,n.y,o)<=i?!0:s.callout?on(s.callout,e,t,i):!1}case"highlight":return Go(e.x,e.y,t(s.corner1),t(s.corner2))||nn(e.x,e.y,t(s.corner1),t(s.corner2))<=i;case"callout":return on(s,e,t,i);case"text":case"stamp":case"symbol":return!1}}const an="markup",ae="markup-live";class Wo{constructor(){this.records=new Map,this.listeners=new Set,this._dirty=!1}get drawingName(){return this._drawingName}set drawingName(e){this._drawingName=e}get dirty(){return this._dirty}get selectedId(){return this._selectedId}list(){return[...this.records.values()]}get(e){return this.records.get(e)}has(e){return this.records.has(e)}get size(){return this.records.size}upsert(e,t){this.records.set(e.id,e),(t==null?void 0:t.markDirty)!==!1&&(this._dirty=!0),this.emit()}updateMeta(e,t){const i=this.records.get(e);if(!i)return;const n={...i,...t,geometry:t.text!==void 0?Hh(i.geometry,t.text):i.geometry,updatedAt:new Date().toISOString()};return this.records.set(e,n),this._dirty=!0,this.emit(),n}updateStyle(e,t){const i=this.records.get(e);if(!i)return;const n={...i,style:{...i.style,...t},updatedAt:new Date().toISOString()};return this.records.set(e,n),this._dirty=!0,this.emit(),n}updateGeometry(e,t){const i=this.records.get(e);if(!i)return;const n={...i,geometry:t,updatedAt:new Date().toISOString()};return this.records.set(e,n),this._dirty=!0,this.emit(),n}removeRecord(e,t){return this.records.delete(e)?(this._selectedId===e&&(this._selectedId=void 0),(t==null?void 0:t.markDirty)!==!1&&(this._dirty=!0),this.emit(),!0):!1}replaceAll(e,t){this.records.clear();for(const i of e)this.records.set(i.id,i);t!==void 0&&(this._drawingName=t),this._selectedId=void 0,this._dirty=!1,this.emit()}restore(e,t){this.records.clear();for(const i of e)this.records.set(i.id,i);this._selectedId=void 0,(t==null?void 0:t.dirty)!==void 0&&(this._dirty=t.dirty),this.emit()}clear(e){this.records.size===0&&this._selectedId==null||(this.records.clear(),this._selectedId=void 0,(e==null?void 0:e.markDirty)!==!1&&(this._dirty=!0),this.emit())}reset(){this.records.clear(),this._selectedId=void 0,this._dirty=!1,this._drawingName=void 0,this.emit()}setSelectedId(e){this._selectedId!==e&&(this._selectedId=e,this.emit())}toSidecar(){return{version:1,drawingName:this._drawingName,markups:this.list()}}markClean(){this._dirty=!1,this.emit()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(){for(const e of[...this.listeners])try{e()}catch{}}}let Ns;function U(){return Ns||(Ns=new Wo),Ns}function Hh(s,e){return(s.type==="cloud"||s.type==="rect"||s.type==="circle")&&s.callout?{...s,callout:{...s.callout,text:e}}:s}const $o=["open","question","answered","closed"],Rs=Math.PI*2;function Yo(s){return(s%Rs+Rs)%Rs}function Zo(s){const e=new u.AcGeBox2d;switch(s.type){case"distance":e.expandByPoint(s.start).expandByPoint(s.end);break;case"angle":e.expandByPoint(s.vertex).expandByPoint(s.arm1).expandByPoint(s.arm2);break;case"area":for(const t of s.points)e.expandByPoint(t);break;case"arc":e.expandByPoint({x:s.center.x-s.radius,y:s.center.y-s.radius}).expandByPoint({x:s.center.x+s.radius,y:s.center.y+s.radius});break;case"point":e.expandByPoint(s.position);break;default:return}return e.isEmpty()?void 0:e}function Vs(s,e,t,i){switch(s.type){case"distance":{const n=t(s.start),r=t(s.end);return bt(e.x,e.y,n.x,n.y,r.x,r.y)<=i}case"angle":{const n=t(s.vertex),r=t(s.arm1),o=t(s.arm2);if(bt(e.x,e.y,n.x,n.y,r.x,r.y)<=i||bt(e.x,e.y,n.x,n.y,o.x,o.y)<=i)return!0;const a=Math.hypot(r.x-n.x,r.y-n.y),l=Math.hypot(o.x-n.x,o.y-n.y),c=Math.max(Math.min(a,l)*.3,15),h=Math.atan2(r.y-n.y,r.x-n.x),p=Math.atan2(o.y-n.y,o.x-n.x),m=Yo(p-h)>Math.PI;return Bs(e.x,e.y,n.x,n.y,c,h,p,m)<=i}case"area":{const n=s.points.map(t);return n.length<2?!1:Ko(e.x,e.y,n)?!0:Os(e.x,e.y,n,!0)<=i}case"arc":{const n=t(s.center),r=t(s.start),o=t(s.end),a=Math.hypot(r.x-n.x,r.y-n.y);if(!(a>0))return js(e.x,e.y,n.x,n.y,0)<=i;const l=Math.atan2(r.y-n.y,r.x-n.x),c=Math.atan2(o.y-n.y,o.x-n.x),p=Yo(c-l)>Math.PI;return Bs(e.x,e.y,n.x,n.y,a,l,c,p)<=i}case"point":return!1}}const Xo={showUnits:!0,showApproximate:!0},qo={showUnits:!0,showApproximate:!0,applyAngbaseAngdir:!1};let Re={};function fb(s){return s}function Gs(s){return{lunits:Re.lunits??s.lunits,luprec:Re.luprec??s.luprec,aunits:Re.aunits??s.aunits,auprec:Re.auprec??s.auprec}}function Wh(){return{...Re}}function $h(s){s.lunits!=null&&(Re.lunits=s.lunits),s.luprec!=null&&(Re.luprec=s.luprec),s.aunits!=null&&(Re.aunits=s.aunits),s.auprec!=null&&(Re.auprec=s.auprec)}function Jo(){Re={}}function Yh(s){const e=Gs(s);return e.lunits!==s.lunits||e.luprec!==s.luprec||e.aunits!==s.aunits||e.auprec!==s.auprec}function Qo(s,e){if(!Yh(s))return e();const t=Gs(s),i=s,n={lunits:i._lunits,luprec:i._luprec,aunits:i._aunits,auprec:i._auprec};i._lunits=t.lunits,i._luprec=t.luprec,i._aunits=t.aunits,i._auprec=t.auprec;try{return e()}finally{i._lunits=n.lunits,i._luprec=n.luprec,i._aunits=n.aunits,i._auprec=n.auprec}}function Te(s,e,t=Xo){return Qo(s,()=>s.formatter.formatLength(e,t))}function ln(s,e,t=qo){return Qo(s,()=>s.formatter.formatAngle(e,t))}function Ks(s,e){switch(e.kind){case"length":return Te(s,e.value);case"area":return`${Te(s,e.value)}²`;case"angle":return ln(s,e.radians);case"coordinate":{const t=Te(s,e.x),i=Te(s,e.y);return`X ${t} Y ${i}`}}}const Dt=u.AcGiLineWeight.LineWeight070,Ot=13;let cn,Us=Dt,Hs=Ot;function Je(s){return cn?cn.clone():u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.MEASUREMENTCOLOR,s)}function jt(){return Us}function wt(){return Hs}function ea(s){cn=s.clone()}function ta(s){s>0&&(Us=s)}function ia(s){!Number.isFinite(s)||s<=0||(Hs=s)}function Zh(){cn=void 0,Us=Dt,Hs=Ot}function at(s){return{color:Je(s),lineWeight:jt(),fontSize:wt()}}function li(s){return{color:s.color.clone(),lineWeight:s.lineWeight,fontSize:s.fontSize}}function Ve(s){const e=Number(s);return!Number.isFinite(e)||e<=0?2:Math.max(1,e/28)}function Ws(s,e){return`rgba(${s.red}, ${s.green}, ${s.blue}, ${e})`}function ge(s){return s.cssColor??`rgb(${s.red}, ${s.green}, ${s.blue})`}function $s(s){const e=u.AcCmColor.fromString(s);if(e)return e;try{return new u.AcCmColor().setRGBFromCss(s)}catch{const t=new u.AcCmColor;return t.setRGB(123,135,148),t}}function Xh(s){return{all:s=s||new Map,on:function(e,t){var i=s.get(e);i?i.push(t):s.set(e,[t])},off:function(e,t){var i=s.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):s.set(e,[]))},emit:function(e,t){var i=s.get(e);i&&i.slice().map(function(n){n(t)}),(i=s.get("*"))&&i.slice().map(function(n){n(e,t)})}}}const Q=Xh();function lt(){Q.emit("undo-stack-changed",{})}function ct(s,e,t){var n;const i=((n=s.isUndoRecording)==null?void 0:n.call(s))??!1;s.runDatabaseEdit(e,t),i||(Q.emit("session-db-edit-committed",{}),lt())}let Z;function na(s){Z=s}class sa{constructor(){this.undoStack=[],this.redoStack=[],this.depth=0}get isBusy(){return this.depth>0}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clearRedo(){this.redoStack.length=0}clear(){this.undoStack.length=0,this.redoStack.length=0}run(e,t,i){if(this.depth>0){i();return}const n=U(),r=oa(n.list()),o=n.dirty;this.depth++;try{i()}finally{this.depth--}const a=oa(n.list()),l=n.dirty;qh(r,a)&&o===l||(this.undoStack.push({label:t,before:r,after:a,beforeDirty:o,afterDirty:l}),this.redoStack.length=0,vt().recordMarkup(),lt())}undo(){const e=this.undoStack.pop();return e?(this.apply(e.before,e.beforeDirty),this.redoStack.push(e),!0):!1}redo(){const e=this.redoStack.pop();return e?(this.apply(e.after,e.afterDirty),this.undoStack.push(e),!0):!1}apply(e,t){this.depth++;try{U().restore(e,{dirty:t})}finally{this.depth--}}}class ra{constructor(){this.undoKinds=[],this.redoKinds=[]}recordDb(){this.undoKinds.push("db"),this.redoKinds.length=0,fe().clearRedo(),Z==null||Z.clearRedo()}recordMarkup(){this.undoKinds.push("markup"),this.redoKinds.length=0,Z==null||Z.clearRedo()}recordOverlay(){this.undoKinds.push("overlay"),this.redoKinds.length=0,fe().clearRedo()}canUndo(e){var t;return this.undoKinds.length>0||fe().canUndo()||((Z==null?void 0:Z.canUndo())??!1)||(((t=e.transactionManager)==null?void 0:t.canUndo())??!1)}canRedo(e){var t;return this.redoKinds.length>0||fe().canRedo()||((Z==null?void 0:Z.canRedo())??!1)||(((t=e.transactionManager)==null?void 0:t.canRedo())??!1)}undo(e){var t;for(;;){const i=this.undoKinds.pop();if(i==="markup"){if(fe().undo())return this.redoKinds.push("markup"),"markup";continue}if(i==="overlay"){if(Z!=null&&Z.undo())return this.redoKinds.push("overlay"),"overlay";continue}if(i==="db"){if(e.transactionManager.undo())return this.redoKinds.push("db"),"db";continue}return fe().undo()?(this.redoKinds.push("markup"),"markup"):Z!=null&&Z.undo()?(this.redoKinds.push("overlay"),"overlay"):(t=e.transactionManager)!=null&&t.undo()?(this.redoKinds.push("db"),"db"):!1}}redo(e){var t;for(;;){const i=this.redoKinds.pop();if(i==="markup"){if(fe().redo())return this.undoKinds.push("markup"),"markup";continue}if(i==="overlay"){if(Z!=null&&Z.redo())return this.undoKinds.push("overlay"),"overlay";continue}if(i==="db"){if(e.transactionManager.redo())return this.undoKinds.push("db"),"db";continue}return fe().redo()?(this.undoKinds.push("markup"),"markup"):Z!=null&&Z.redo()?(this.undoKinds.push("overlay"),"overlay"):(t=e.transactionManager)!=null&&t.redo()?(this.undoKinds.push("db"),"db"):!1}}clear(){this.undoKinds.length=0,this.redoKinds.length=0,Z==null||Z.clear()}}let Ys,Zs;function fe(){return Ys||(Ys=new sa),Ys}function vt(){return Zs||(Zs=new ra),Zs}function ve(s,e,t){fe().run(s,e,t)}Q.on("session-db-edit-committed",()=>{vt().recordDb()});function oa(s){return structuredClone(s)}function qh(s,e){return s.length!==e.length?!1:JSON.stringify(s)===JSON.stringify(e)}class aa{constructor(){this.undoStack=[],this.redoStack=[],this.depth=0}get isBusy(){return this.depth>0}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clearRedo(){for(const e of this.redoStack)ca(e);this.redoStack.length=0}clear(){for(const e of[...this.undoStack,...this.redoStack])ca(e);this.undoStack.length=0,this.redoStack.length=0}run(e,t,i){if(this.depth>0){i();return}const n=e,r=Xs(n),o=la(r);this.depth++;try{i()}finally{this.depth--}const a=Xs(n),l=a.filter(p=>r.indexOf(p)<0),c=r.filter(p=>a.indexOf(p)<0),h=la(a);l.length===0&&c.length===0&&!Jh(o,h)||(this.undoStack.push({label:t,view:n,added:l,removed:c,stylesBefore:o,stylesAfter:h}),this.clearRedo(),vt().recordOverlay(),lt())}undo(){const e=this.undoStack.pop();return e?(this.apply(e,"undo"),this.redoStack.push(e),!0):!1}redo(){const e=this.redoStack.pop();return e?(this.apply(e,"redo"),this.undoStack.push(e),!0):!1}apply(e,t){this.depth++;try{const i=e.view.htmlTransientManager,n=t==="undo"?e.added:e.removed,r=t==="undo"?e.removed:e.added;for(const a of n)i.detach(a.id);for(const a of r)i.reattach(a);const o=t==="undo"?e.stylesBefore:e.stylesAfter;for(const a of Xs(e.view)){const l=o[a.id];l&&er(e.view,a,l)}e.view.isHtmlDirty=!0}finally{this.depth--}}}function Xs(s){return s.htmlTransientManager.groupsOnLayer(Y)}function la(s){const e={};for(const t of s){const i=kt(t.id);i&&(e[t.id]=li(i))}return e}function Jh(s,e){const t=Object.keys(s),i=Object.keys(e);if(t.length!==i.length)return!0;for(const n of t){const r=s[n],o=e[n];if(!o||r.lineWeight!==o.lineWeight||r.fontSize!==o.fontSize||r.color.red!==o.color.red||r.color.green!==o.color.green||r.color.blue!==o.color.blue)return!0}return!1}function ca(s){const e=s.view.htmlTransientManager;for(const t of[...s.added,...s.removed])if(!e.has(t.id)){for(const i of t.children)i.dispose();t.dispose()}}let qs;function Qe(){return qs||(qs=new aa),qs}function Bt(s,e,t){Qe().run(s,e,t)}function da(){Qe().clear(),ka(),Jo(),ga()}function ua(){na({canUndo:()=>Qe().canUndo(),canRedo:()=>Qe().canRedo(),undo:()=>Qe().undo(),redo:()=>Qe().redo(),clearRedo:()=>Qe().clearRedo(),clear:()=>Qe().clear()})}ua();const Qh=["distance","angle","area","arc","point"];function ci(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function Ge(s){return ci(s)&&typeof s.x=="number"&&typeof s.y=="number"&&Number.isFinite(s.x)&&Number.isFinite(s.y)}function ep(s){return typeof s=="string"&&Qh.includes(s)}function tp(s){if(!ci(s)||typeof s.color!="string")return;const e=typeof s.lineWeight=="number"&&s.lineWeight>0?s.lineWeight:Dt,t=typeof s.fontSize=="number"&&s.fontSize>0?s.fontSize:Ot;return{color:s.color,lineWeight:e,fontSize:t}}function ip(s,e){if(!(!ci(e)||e.type!==s))switch(s){case"distance":return!Ge(e.start)||!Ge(e.end)?void 0:{type:s,start:e.start,end:e.end};case"angle":return!Ge(e.vertex)||!Ge(e.arm1)||!Ge(e.arm2)?void 0:{type:s,vertex:e.vertex,arm1:e.arm1,arm2:e.arm2};case"area":return!Array.isArray(e.points)||e.points.length<3||!e.points.every(Ge)?void 0:{type:s,points:e.points};case"arc":return!Ge(e.center)||typeof e.radius!="number"||!(e.radius>0)||!Ge(e.start)||!Ge(e.end)?void 0:{type:s,center:e.center,radius:e.radius,start:e.start,end:e.end};case"point":return Ge(e.position)?{type:s,position:e.position}:void 0}}function np(s){if(!ci(s)||typeof s.id!="string"||!ep(s.type))return;const e=tp(s.style),t=ip(s.type,s.geometry);if(!(!e||!t))return{id:s.id,type:s.type,layoutId:typeof s.layoutId=="string"?s.layoutId:void 0,style:e,geometry:t}}function dt(s){return{color:ge(s.color),lineWeight:s.lineWeight,fontSize:s.fontSize}}function ha(s){return{color:$s(s.color),lineWeight:s.lineWeight>0?s.lineWeight:Dt,fontSize:s.fontSize>0?s.fontSize:Ot}}function pa(s){let e;try{e=JSON.parse(s)}catch{throw new Error("Invalid measurement sidecar: not JSON")}if(!ci(e)||e.version!==1)throw new Error("Invalid measurement sidecar: expected version 1");if(!Array.isArray(e.measurements))throw new Error("Invalid measurement sidecar: measurements must be an array");const t=[];for(const i of e.measurements){const n=np(i);n&&t.push(n)}return{version:1,drawingName:typeof e.drawingName=="string"?e.drawingName:void 0,measurements:t}}function ma(s){return`${JSON.stringify(s,null,2)}
2
- `}function ya(s){return s?`${s.replace(/\.(dwg|dxf)$/i,"")}.measurement.json`:"drawing.measurement.json"}const Y="measurement",ue="measurement-live";let di=!0;function Js(){return di}function ga(){di=!0}function fa(s,e){di=e;const t=s.activeLayoutBtrId,i=s.htmlTransientManager;for(const n of i.groupsOnLayer(Y))(n.layoutId==null||n.layoutId===t)&&n.setVisible(e);i.setVisible(e,ue),s.isHtmlDirty=!0}const ut=new Map,Ft=new Map,Qs=new Set;let ht;function kt(s){const e=Ft.get(s);return e?li(e):void 0}function ba(){return ht?kt(ht):void 0}function sp(s){return Qs.add(s),()=>{Qs.delete(s)}}function dn(){for(const s of Qs)s()}function wa(s,e){Ft.set(s,li(e))}function er(s,e,t){var a;const i=Ft.get(e.id),n=((a=t.color)==null?void 0:a.clone())??(i==null?void 0:i.color.clone());if(!n)return;const r={color:n,lineWeight:t.lineWeight??(i==null?void 0:i.lineWeight)??Dt,fontSize:t.fontSize??(i==null?void 0:i.fontSize)??Ot};wa(e.id,r);const o=ut.get(e.id);o&&(o.style=li(r),o.snapshot&&(o.snapshot={...o.snapshot,style:dt(r)})),rp(s,e,r)}function un(s,e){const t=s.htmlTransientManager.getSelectedGroups().filter(i=>i.layer===Y);t.length!==0&&Bt(s,"Measurement Style",()=>{for(const i of t)er(s,i,e)})}function rp(s,e,t){var n,r,o;for(const a of e.children){const l=a;(n=l.setColor)==null||n.call(l,t.color),(r=l.setFontSize)==null||r.call(l,t.fontSize)}const i=ut.get(e.id);(o=i==null?void 0:i.redraw)==null||o.call(i,t),s.isHtmlDirty=!0}function op(s,e){var t;for(const i of s.htmlTransientManager.groupsOnLayer(Y)){const n=ut.get(i.id);if(!(n!=null&&n.value))continue;const r=Ks(e,n.value);for(const o of i.children){const a=o;(t=a.setText)==null||t.call(a,r)}}s.isHtmlDirty=!0}function va(s){const e=[];for(const t of s.htmlTransientManager.groupsOnLayer(Y)){const i=ut.get(t.id);if(!(i!=null&&i.snapshot))continue;const n=i.style??Ft.get(t.id);e.push({...i.snapshot,id:t.id,layoutId:t.layoutId,style:n?dt(n):i.snapshot.style})}return e}function ka(){ut.clear(),Ft.clear(),ht=void 0,dn()}function xa(s,e,t){const i=(t==null?void 0:t.entityIds)??[];ut.set(e.id,t??{}),t!=null&&t.style&&wa(e.id,t.style);const n=e.onSelectedChanged;e.onSelectedChanged=(a,l)=>{n==null||n(a,l),a?(ht=l.id,dn(),i.length>0&&s.highlight(i)):(ht===l.id&&(ht=void 0,dn()),i.length>0&&s.unhighlight(i))};const r=e.onVisibleChanged;e.onVisibleChanged=(a,l)=>{r==null||r(a,l);for(const c of i)s.setTransientEntityVisible(c,a)};const o=e.onDispose;e.onDispose=()=>{var a;o==null||o(),ut.delete(e.id),Ft.delete(e.id),ht===e.id&&(ht=void 0,dn()),i.length>0&&s.unhighlight(i);try{(a=t==null?void 0:t.dispose)==null||a.call(t)}catch{}},Bt(s,"Create Measurement",()=>{s.htmlTransientManager.add(e)}),!di&&(e.layoutId==null||e.layoutId===s.activeLayoutBtrId)&&e.setVisible(!1),s.isHtmlDirty=!0}function tr(s){var e,t;return(t=(e=ut.get(s))==null?void 0:e.snapshot)==null?void 0:t.geometry}function Sa(s,e,t,i){if(!di)return;const n={x:e,y:t},r=a=>s.worldToScreen(a),o=s.htmlTransientManager.groupsOnLayer(Y);for(let a=o.length-1;a>=0;a--){const l=o[a];if(!l.visible)continue;const c=tr(l.id);if(c&&Vs(c,n,r,i))return l.id}}function zt(s,e){return s.minX>=e.minX&&s.maxX<=e.maxX&&s.minY>=e.minY&&s.maxY<=e.maxY}function ap(s){var e;return 80+(((e=s.id)==null?void 0:e.length)??0)*2}function Pa(s,e=32){const t=s.length;if(t===0)return 0;const i=Math.min(t,e);let n=0;for(let r=0;r<i;r++)n+=ap(s[r]);return Math.round(n/i*t)}const Aa=10;function Ca(s){return{minX:s.min.x,minY:s.min.y,maxX:s.max.x,maxY:s.max.y}}function lp(s,e){return!(s.maxX<e.minX||s.minX>e.maxX||s.maxY<e.minY||s.minY>e.maxY)}function _a(s,e,t){const i=Ca(s);return t==="window"?zt(i,e):lp(i,e)}function cp(s,e,t,i){const n={x:e,y:t},r=l=>s.worldToScreen(l),o=s.activeLayoutBtrId,a=U().list();for(let l=a.length-1;l>=0;l--){const c=a[l];if(c.layoutId!=null&&c.layoutId!==o)continue;const h=s.htmlTransientManager.getGroup(c.id);if(h!=null&&h.visible&&zs(c.geometry,n,r,i))return c.id}}function Ea(s,e,t){const i=Ca(e),n=s.activeLayoutBtrId,r=[];for(const o of U().list()){if(o.layoutId!=null&&o.layoutId!==n)continue;const a=s.htmlTransientManager.getGroup(o.id);if(!(a!=null&&a.visible))continue;const l=Ho(o.geometry);l&&_a(l,i,t)&&r.push(o.id)}if(!Js())return r;for(const o of s.htmlTransientManager.groupsOnLayer(Y)){if(!o.visible||o.layoutId!=null&&o.layoutId!==n)continue;const a=tr(o.id);if(!a)continue;const l=Zo(a);l&&_a(l,i,t)&&r.push(o.id)}return r}function dp(s,e,t){const i=s.htmlTransientManager;return t==="remove"?i.deselectGroup(e):t==="add"?i.selectGroup(e,!1):(i.selectGroup(e,!0),!0)}function up(s,e,t){const i=s.htmlTransientManager;let n=!1;if(t==="replace"){const r=i.hasSelection();i.deselectAll();for(const o of e)i.selectGroup(o,!1)&&(n=!0);return r||n}if(e.length===0)return!1;if(t==="add"){for(const r of e)i.selectGroup(r,!1)&&(n=!0);return n}for(const r of e)i.deselectGroup(r)&&(n=!0);return n}function La(s,e,t,i){const n=Math.max(s.selectionBoxSize*2,Aa),r=cp(s,e,t,n),o=Sa(s,e,t,n),a=r??o;if(!a)return!1;const l=dp(s,a,i);return l&&(s.isHtmlDirty=!0),l}function Ta(s,e,t,i){const n=Ea(s,e,t),r=up(s,n,i);return r&&(s.isHtmlDirty=!0),r}const hn="simkai";function hp(){return{fontFamily:hn,fontSize:24,bold:!1,italic:!1,underline:!1,overline:!1,strike:!1,script:"normal",aci:null,rgb:16777215,obliqueAngle:0,widthFactor:1,tracking:1,paragraphAlignment:D.MTextParagraphAlignment.DEFAULT}}function Ia(s,e){return s.fontFamily===e.fontFamily&&s.fontSize===e.fontSize&&s.bold===e.bold&&s.italic===e.italic&&s.underline===e.underline&&s.overline===e.overline&&s.strike===e.strike&&s.script===e.script&&s.aci===e.aci&&s.rgb===e.rgb&&s.obliqueAngle===e.obliqueAngle&&s.widthFactor===e.widthFactor&&s.tracking===e.tracking&&s.paragraphAlignment===e.paragraphAlignment}function ke(s,e,t){return Math.min(t,Math.max(e,s))}function pp(s,e){const t=Math.max(s.y-s.height/2,e.y-e.height/2),i=Math.min(s.y+s.height/2,e.y+e.height/2);return Math.max(0,i-t)}class mp{constructor(e){E(this,"containerBox");E(this,"charBoxes");E(this,"explicitLineBreakIndices",[]);E(this,"explicitLineLayouts",[]);E(this,"cursorLineHint",null);E(this,"verticalAlign");E(this,"lineTolerance");E(this,"debug");E(this,"lines",[]);E(this,"cursorIndex",0);E(this,"selection",null);E(this,"dragAnchor",null);E(this,"preferredX",null);E(this,"handlers",{cursorMove:new Set,selectionChange:new Set,linesUpdate:new Set});this.containerBox={...e.containerBox};const t=this.normalizeCharLayout(e.charBoxes,e.lineBreakIndices);this.charBoxes=t.charBoxes,this.explicitLineBreakIndices=t.lineBreakIndices,this.explicitLineLayouts=this.normalizeLineLayouts(e.lineLayouts),this.verticalAlign=e.verticalAlign??"center",this.lineTolerance=e.lineTolerance??5,this.debug=e.debug??!1,this.cursorIndex=ke(e.initialIndex??0,0,this.charBoxes.length),this.recomputeLines(),e.initialSelection&&this.setSelection(e.initialSelection.start,e.initialSelection.end)}moveLeft(){if(this.selection&&!this.selection.isCollapsed){this.cursorIndex=this.selection.start,this.cursorLineHint=null,this.clearSelection(),this.emitCursor();return}const e=this.getCurrentLineIndex();if(e>=0){const t=this.lines[e];if(t){if(this.cursorIndex>t.startIndex&&this.cursorIndex<=t.endIndex+1){this.moveTo(this.cursorIndex-1,e);return}if(this.cursorIndex===t.startIndex&&e>0){this.moveTo(this.cursorIndex,e-1);return}}}this.moveTo(this.cursorIndex-1)}moveRight(){if(this.selection&&!this.selection.isCollapsed){this.cursorIndex=this.selection.end,this.cursorLineHint=null,this.clearSelection(),this.emitCursor();return}const e=this.getCurrentLineIndex();if(e>=0){const t=this.lines[e],i=e+1;if(t&&this.cursorIndex===t.endIndex&&i<this.lines.length&&this.isHardBreakChar(t.endIndex)){this.moveTo(t.endIndex+1,i);return}if(t&&this.cursorIndex===t.endIndex+1&&i<this.lines.length){this.moveTo(this.cursorIndex,i);return}}this.cursorIndex>=this.charBoxes.length||this.moveTo(this.cursorIndex+1)}moveUp(){this.moveVertical(-1)}moveDown(){this.moveVertical(1)}moveTo(e,t=null){const i=ke(e,0,this.charBoxes.length);i===this.cursorIndex&&this.cursorLineHint===t||(this.cursorIndex=i,this.cursorLineHint=t,this.preferredX=null,this.emitCursor())}moveToStart(){this.moveTo(0)}moveToEnd(){this.moveTo(this.charBoxes.length)}moveToLineStart(){const e=this.getCurrentLineIndex();if(e<0){this.moveToStart();return}const t=this.lines[e];t&&this.moveTo(t.startIndex,e)}moveToLineEnd(){const e=this.getCurrentLineIndex();if(e<0){this.moveToEnd();return}const t=this.lines[e];t&&this.moveTo(t.endIndex+1,e)}setSelection(e,t){const i=ke(e,0,this.charBoxes.length),n=ke(t,0,this.charBoxes.length);this.setSelectionWithDirection(i,n)}clearSelection(){this.selection&&(this.selection=null,this.dragAnchor=null,this.emit("selectionChange",null))}selectAll(){this.setSelectionWithDirection(0,this.charBoxes.length),this.cursorIndex=this.charBoxes.length,this.cursorLineHint=null,this.emitCursor()}setSelectionWithDirection(e,t){const i=ke(e,0,this.charBoxes.length),n=ke(t,0,this.charBoxes.length),r=Math.min(i,n),o=Math.max(i,n);this.selection={start:r,end:o,isCollapsed:r===o,anchor:i,active:n,isBackwards:n<i,selectedLines:this.resolveSelectedLines(r,o)},this.cursorIndex=n,this.cursorLineHint=null,this.emit("selectionChange",this.selection),this.emitCursor()}extendSelection(e){var n;const t=ke(e,0,this.charBoxes.length),i=((n=this.selection)==null?void 0:n.anchor)??this.cursorIndex;this.setSelectionWithDirection(i,t)}getSelection(){return this.selection?{...this.selection,selectedLines:[...this.selection.selectedLines]}:null}getSelectedCharBoxes(){return!this.selection||this.selection.isCollapsed?[]:this.charBoxes.slice(this.selection.start,this.selection.end).map(e=>({...e}))}getSelectedLines(){if(!this.selection||this.selection.isCollapsed)return[];const e=[],{start:t,end:i}=this.selection;for(let n=0;n<this.lines.length;n++){const r=this.lines[n];if(!r)continue;const o=r.startIndex,a=r.endIndex+1,l=Math.max(t,o),c=Math.min(i,a);l<c&&e.push({lineIndex:n,startOffset:l-o,endOffset:c-o})}return e}hasSelection(){return!!this.selection&&!this.selection.isCollapsed}moveToClick(e,t){const i=this.hitTest(e,t);if(i<0)return!1;const n=this.hitTestLine(t);return this.clearSelection(),this.moveTo(i,n>=0?n:null),!0}extendSelectionToClick(e,t){const i=this.hitTestClamped(e,t);i<0||(this.dragAnchor===null&&(this.dragAnchor=this.cursorIndex),this.setSelectionWithDirection(this.dragAnchor,i))}updateSelectionDrag(e,t){const i=this.hitTestClamped(e,t);i<0||(this.dragAnchor===null&&(this.dragAnchor=this.cursorIndex),this.setSelectionWithDirection(this.dragAnchor,i))}hitTest(e,t){if(!this.isInContainer(e,t))return-1;if(this.charBoxes.length===0)return 0;const i=this.hitTestLine(t);return i<0?-1:this.closestIndexInLine(i,e)}hitTestLine(e){if(this.lines.length===0)return-1;let t=-1,i=Number.POSITIVE_INFINITY;for(let n=0;n<this.lines.length;n++){const r=this.lines[n];if(!r)continue;const o=r.y-r.height/2,a=r.y+r.height/2;if(e>=o&&e<=a)return n;const l=e<o?o-e:e-a;l<i&&(i=l,t=n)}return t}getLines(){return this.lines.map(e=>({...e}))}getLineCount(){return this.lines.length}getLineIndex(e){if(this.lines.length===0)return-1;const t=ke(e,0,this.charBoxes.length);for(let i=0;i<this.lines.length;i++){const n=this.lines[i];if(n&&t>=n.startIndex&&t<=n.endIndex+1)return i}return this.lines.length-1}getLineInfo(e){const t=this.lines[e];if(!t)throw new Error(`Line index out of range: ${e}`);return{...t}}getCurrentLineInfo(){const e=this.getCurrentLineIndex();if(e<0)return{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0};const t=this.lines[e];return t?{...t}:{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0}}getCursorState(){var n,r;const e=this.getCurrentLineIndex(),t=this.getCursorPosition(),i=e>=0&&this.lines[e]?this.lines[e]:{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0};return{index:this.cursorIndex,position:t,lineIndex:e,lineInfo:{...i},isAtStart:this.cursorIndex===0,isAtEnd:this.cursorIndex===this.charBoxes.length,isAtLineStart:e<0?!0:this.cursorIndex===(((n=this.lines[e])==null?void 0:n.startIndex)??this.cursorIndex),isAtLineEnd:e<0?!0:this.cursorIndex===(((r=this.lines[e])==null?void 0:r.endIndex)??this.cursorIndex-1)+1}}getCurrentIndex(){return this.cursorIndex}getCursorPosition(){if(this.lines.length===0)return{x:this.containerBox.x,y:this.alignY(this.containerBox.y,this.containerBox.height)};const e=this.getCurrentLineIndex(),t=this.lines[Math.max(0,e)];if(!t)return{x:this.containerBox.x,y:this.alignY(this.containerBox.y,this.containerBox.height)};const i=this.alignY(t.y,t.height);return{x:this.indexToX(this.cursorIndex,e),y:i}}getCharBoxes(){return this.charBoxes.map(e=>({...e}))}getContainerBox(){return{...this.containerBox}}updateData(e,t,i,n){this.containerBox={...e};const r=this.normalizeCharLayout(t,i);if(this.charBoxes=r.charBoxes,this.explicitLineBreakIndices=r.lineBreakIndices,this.explicitLineLayouts=this.normalizeLineLayouts(n),this.recomputeLines(),this.cursorIndex=ke(this.cursorIndex,0,this.charBoxes.length),this.cursorLineHint=null,this.selection){const o=ke(this.selection.anchor,0,this.charBoxes.length),a=ke(this.selection.active,0,this.charBoxes.length);o===a?this.selection=null:this.setSelectionWithDirection(o,a)}this.emit("linesUpdate",this.getLines()),this.emitCursor()}setLineTolerance(e){this.lineTolerance=Math.max(0,e),this.recomputeLines(),this.emit("linesUpdate",this.getLines()),this.emitCursor(),this.selection&&(this.selection.selectedLines=this.resolveSelectedLines(this.selection.start,this.selection.end),this.emit("selectionChange",this.selection))}on(e,t){this.handlers[e].add(t)}off(e,t){(e==="cursorMove"||e==="selectionChange"||e==="linesUpdate")&&this.handlers[e].delete(t)}enableDebug(){this.debug=!0}disableDebug(){this.debug=!1}getDebugInfo(){return{debug:this.debug,container:this.getContainerBox(),cursor:this.getCursorState(),selection:this.getSelection(),lines:this.getLines(),gaps:this.lines.map((e,t)=>this.getGapPositions(t))}}destroy(){this.handlers.cursorMove.clear(),this.handlers.selectionChange.clear(),this.handlers.linesUpdate.clear(),this.selection=null,this.dragAnchor=null,this.preferredX=null}emitCursor(){this.emit("cursorMove",this.getCursorState())}emit(e,t){for(const i of this.handlers[e])i(t)}moveVertical(e){const t=this.getCurrentLineIndex();if(t<0)return;const i=this.lines[t],n=t+e;if(n<0||n>=this.lines.length)return;(this.preferredX===null||(i==null?void 0:i.charCount)===0)&&(this.preferredX=this.getCursorPosition().x);const r=this.closestIndexInLine(n,this.preferredX);this.cursorIndex=r,this.cursorLineHint=n,this.emitCursor()}getCurrentLineIndex(){const e=this.getLineIndex(this.cursorIndex);if(e<0||this.cursorLineHint===null)return e;const t=this.lines[this.cursorLineHint];return t&&this.cursorIndex>=t.startIndex&&this.cursorIndex<=t.endIndex+1?this.cursorLineHint:e}isHardBreakChar(e){const t=this.charBoxes[e];return t?t.width===0:!1}resolveSelectedLines(e,t){if(e===t)return[];const i=[];for(let n=0;n<this.lines.length;n++){const r=this.lines[n];r&&t>r.startIndex&&e<r.endIndex+1&&i.push(n)}return i}isInContainer(e,t){return e>=this.containerBox.x&&e<=this.containerBox.x+this.containerBox.width&&t>=this.containerBox.y&&t<=this.containerBox.y+this.containerBox.height}hitTestClamped(e,t){if(this.charBoxes.length===0)return 0;const i=this.lines.length===0?-1:this.hitTestLine(t);return i<0?e<=this.containerBox.x?0:e>=this.containerBox.x+this.containerBox.width?this.charBoxes.length:ke(this.cursorIndex,0,this.charBoxes.length):this.closestIndexInLine(i,e)}recomputeLines(){if(this.explicitLineBreakIndices.length>0){this.lines=this.linesFromBreakIndices(this.charBoxes,this.explicitLineBreakIndices,this.explicitLineLayouts);return}this.lines=this.detectLines(this.charBoxes,this.lineTolerance)}normalizeCharLayout(e,t){const i=[],n=[];for(const a of e){if(!a){n.push(i.length);continue}i.push({...a})}const r=[...n,...t??[]],o=this.normalizeBreakIndices(r,i.length);return{charBoxes:i,lineBreakIndices:o}}normalizeBreakIndices(e,t){if(e.length===0)return[];const i=[];for(const n of e){if(!Number.isFinite(n))continue;const r=ke(Math.round(n),0,t);i.push(r)}return i.sort((n,r)=>n-r)}normalizeLineLayouts(e){if(!e||e.length===0)return[];const t=[];for(const i of e)i&&(!Number.isFinite(i.y)||!Number.isFinite(i.height)||t.push({y:i.y,height:Math.max(1,i.height)}));return t}linesFromBreakIndices(e,t,i){if(e.length===0&&t.length===0)return[];if(t.length===0)return this.detectLines(e,this.lineTolerance);const n=[];let r=0;for(const o of t)if(!(o<r||o>e.length)){if(o===r){n.push(this.createEmptyLine(r,n[n.length-1],i[n.length]));continue}n.push(this.withLineLayout(this.aggregateLine(e,r,o-1),i[n.length])),r=o}return r<e.length?n.push(this.withLineLayout(this.aggregateLine(e,r,e.length-1),i[n.length])):n.push(this.createEmptyLine(r,n[n.length-1],i[n.length])),n}detectLines(e,t){if(e.length===0)return[];const i=[],n=.65;let r=0;for(let o=1;o<e.length;o++){const a=e[o-1],l=e[o];if(!a||!l)continue;const c=Math.abs(l.y-a.y),h=l.x+t<a.x,p=pp(a,l),m=Math.min(a.height,l.height),f=(m>0?p/m:0)<n;(h||c>t&&f)&&(i.push(this.aggregateLine(e,r,o-1)),r=o)}return i.push(this.aggregateLine(e,r,e.length-1)),i}aggregateLine(e,t,i){let n=0,r=0,o=0;for(let a=t;a<=i;a++){const l=e[a];l&&(n+=l.y,r+=1,o=Math.max(o,l.height))}return r===0?{startIndex:t,endIndex:i,y:this.containerBox.y,height:this.containerBox.height,charCount:Math.max(0,i-t+1)}:{startIndex:t,endIndex:i,y:n/r,height:o,charCount:i-t+1}}withLineLayout(e,t){return t?{...e,y:t.y,height:Math.max(1,t.height)}:e}createEmptyLine(e,t,i){if(i)return{startIndex:e,endIndex:e-1,y:i.y,height:Math.max(1,i.height),charCount:0};const n=Math.max(1,(t==null?void 0:t.height)??this.containerBox.height),r=t!==void 0?t.y+n:this.alignY(this.containerBox.y,this.containerBox.height);return{startIndex:e,endIndex:e-1,y:r,height:n,charCount:0}}alignY(e,t){return this.verticalAlign==="top"?e-t/2:this.verticalAlign==="bottom"?e+t/2:e}indexToX(e,t){if(this.charBoxes.length===0)return this.containerBox.x;if(e<=0)return this.containerBox.x;const i=t??this.getLineIndex(e);if(i<0)return this.containerBox.x;const n=this.lines[i];if(!n)return this.containerBox.x;if(e<=n.startIndex)return this.containerBox.x;if(e>n.endIndex+1){const o=this.charBoxes[this.charBoxes.length-1];return o?o.x+o.width:this.containerBox.x}const r=this.charBoxes[e-1];return r?r.x+r.width:this.containerBox.x}getGapPositions(e){const t=this.lines[e];if(!t)return[];const i=[{index:t.startIndex,x:this.containerBox.x}];for(let n=t.startIndex;n<=t.endIndex;n++){const r=this.charBoxes[n];r&&i.push({index:n+1,x:r.x+r.width})}return i}closestIndexInLine(e,t){const i=this.getGapPositions(e);if(i.length===0)return 0;let n=i[0],r=Math.abs(t-n.x);for(let o=1;o<i.length;o++){const a=i[o];if(!a)continue;const l=Math.abs(t-a.x);l<r&&(n=a,r=l)}return n.index}}const yp={width:4,height:24,heightMode:"lineHeight",color:"#00f5ff",glowColor:"#00f5ff",glowIntensity:.9,blinkSpeed:1.05,blinkEnabled:!0,billboard:!0,depthTest:!1,renderOrder:100,mode:"plane"},gp={fillColor:"rgba(0,120,255,0.30)",blendMode:"normal",animate:!1,strategy:"perChar"},fp={charBoxColor:"rgba(64,160,255,0.55)",charBoxFill:"rgba(64,160,255,0.10)",charIndexColor:"rgba(255,255,255,0.85)",rowHoverColor:"rgba(200,200,200,0.10)",rowBoundaryColor:"rgba(255,255,255,0.22)",gapColor:"rgba(255,153,0,0.7)",baselineColor:"rgba(255,51,51,0.55)",containerColor:"rgba(255,255,255,0.30)"},bp={showCharBoxes:!0,showLineIndices:!0,showCharIndices:!0,showChars:!0};class wp{constructor(e){E(this,"renderer");E(this,"cursorStyle");E(this,"selectionStyle");E(this,"debugStyle");E(this,"debugVisibility");E(this,"enableSelection");E(this,"enableDebug");E(this,"debugYAxisUp");E(this,"visible",!0);E(this,"cursorState",null);E(this,"selectionBoxes",[]);E(this,"debugData",null);E(this,"viewTransform",{x:0,y:0,scaleX:1,scaleY:1,rotation:0});this.renderer=e.renderer,this.cursorStyle={...yp,...e.cursorStyle},this.selectionStyle={...gp,...e.selectionStyle},this.debugStyle={...fp,...e.debugStyle},this.debugVisibility={...bp,...e.debugVisibility},this.enableSelection=e.enableSelection??!0,this.enableDebug=e.enableDebug??!1,this.debugYAxisUp=e.debugYAxisUp??!1}updateCursor(e,t){this.cursorState={position:e,lineHeight:t}}updateSelection(e){this.selectionBoxes=e.map(t=>({...t}))}updateDebugInfo(e){const t={containerBox:{...e.containerBox},charBoxes:e.charBoxes.map(i=>({...i})),lines:e.lines.map(i=>({...i}))};e.chars&&(t.chars=[...e.chars]),e.gapPositions&&(t.gapPositions=[...e.gapPositions]),e.hoverLineIndex!==void 0&&(t.hoverLineIndex=e.hoverLineIndex),this.debugData=t}setCursorStyle(e){this.cursorStyle={...this.cursorStyle,...e}}setSelectionStyle(e){this.selectionStyle={...this.selectionStyle,...e}}setDebugMode(e){this.enableDebug=e}setDebugVisibility(e){this.debugVisibility={...this.debugVisibility,...e}}setViewTransform(e){this.viewTransform={...this.viewTransform,...e}}show(){this.visible=!0}hide(){this.visible=!1}toggle(){this.visible=!this.visible}render(){if(this.renderer.beginFrame(),!this.visible){this.renderer.endFrame();return}this.renderer.setTransform({x:this.viewTransform.x??0,y:this.viewTransform.y??0,scaleX:this.viewTransform.scaleX??1,scaleY:this.viewTransform.scaleY??1,rotation:this.viewTransform.rotation??0}),this.enableDebug&&this.debugData&&this.drawDebug(this.debugData),this.enableSelection&&this.selectionBoxes.length>0&&this.drawSelection(this.selectionBoxes),this.cursorState&&this.drawCursor(this.cursorState.position,this.cursorState.lineHeight),this.renderer.resetTransform(),this.renderer.endFrame()}dispose(){this.renderer.destroy(),this.selectionBoxes=[],this.cursorState=null,this.debugData=null}drawCursor(e,t){const i=Math.max(.2,this.cursorStyle.blinkSpeed)*1e3;if(!(!this.cursorStyle.blinkEnabled||Date.now()%i<i/2))return;const r=this.cursorStyle.heightMode==="fixed"?this.cursorStyle.height:Math.max(this.cursorStyle.height,t*.8);this.cursorStyle.glowColor&&(this.cursorStyle.glowIntensity??0)>0&&this.renderer.drawLine({x1:e.x,y1:e.y-r/2,x2:e.x,y2:e.y+r/2,color:this.cursorStyle.glowColor,width:this.cursorStyle.width+2,opacity:Math.min(1,this.cursorStyle.glowIntensity??0)}),this.renderer.drawLine({x1:e.x,y1:e.y-r/2,x2:e.x,y2:e.y+r/2,color:this.cursorStyle.color,width:this.cursorStyle.width,opacity:1})}drawSelection(e){if(this.selectionStyle.strategy==="merged"){this.mergeBoxes(e).forEach(t=>this.drawSelectionQuad(t));return}e.forEach(t=>this.drawSelectionQuad(t))}drawSelectionQuad(e){const t={x:e.x,y:e.y,width:e.width,height:e.height,fillColor:this.selectionStyle.fillColor,blendMode:this.selectionStyle.blendMode==="additive"?"lighter":this.selectionStyle.blendMode==="multiply"?"multiply":"source-over"};this.renderer.drawQuad({...t,...this.selectionStyle.borderColor?{borderColor:this.selectionStyle.borderColor}:{},...this.selectionStyle.borderWidth!==void 0?{borderWidth:this.selectionStyle.borderWidth}:{},...this.selectionStyle.cornerRadius!==void 0?{cornerRadius:this.selectionStyle.cornerRadius}:{}})}drawDebug(e){var i;this.renderer.drawBox({box:{x:e.containerBox.x,y:e.containerBox.y+e.containerBox.height/2,width:e.containerBox.width,height:e.containerBox.height},color:this.debugStyle.containerColor,opacity:1,lineWidth:1});const t=e.containerBox.x+e.containerBox.width+60;e.lines.forEach((n,r)=>{const o=this.debugYAxisUp?n.y+n.height/2:n.y-n.height/2,a=this.debugYAxisUp?n.y-n.height/2:n.y+n.height/2;e.hoverLineIndex===r&&this.renderer.drawQuad({x:0,y:n.y,width:t,height:n.height,fillColor:this.debugStyle.rowHoverColor}),this.renderer.drawLine({x1:0,y1:o,x2:t,y2:o,color:this.debugStyle.rowBoundaryColor,dashed:[5,5]}),this.renderer.drawLine({x1:0,y1:a,x2:t,y2:a,color:this.debugStyle.rowBoundaryColor,dashed:[5,5]}),this.debugVisibility.showLineIndices&&this.renderer.drawText({text:`L${r}`,x:8,y:o+(this.debugYAxisUp?-2:2),color:"rgba(255,255,255,0.65)",font:"12px monospace"})}),e.charBoxes.forEach((n,r)=>{var c;const o=this.debugYAxisUp?n.y+n.height/2:n.y-n.height/2,a=this.debugYAxisUp?-2:2,l=this.debugYAxisUp?-Math.max(8,n.height*.2):Math.max(8,n.height*.2);if(this.debugVisibility.showCharBoxes&&this.renderer.drawQuad({x:n.x,y:n.y,width:n.width,height:n.height,fillColor:this.debugStyle.charBoxFill,borderColor:this.debugStyle.charBoxColor,borderWidth:1}),this.debugVisibility.showCharIndices&&this.renderer.drawText({text:String(r),x:n.x+2,y:o+a,color:this.debugStyle.charIndexColor,font:"10px monospace"}),this.debugVisibility.showChars){const h=(c=e.chars)==null?void 0:c[r];if(!h)return;this.renderer.drawText({text:h,x:n.x+2,y:o+l,color:"rgba(255,255,255,0.95)",font:`${Math.max(12,Math.round(n.height*.6))}px monospace`})}}),(i=e.gapPositions)==null||i.forEach(n=>{this.renderer.drawLine({x1:n.x,y1:n.y-n.height/2,x2:n.x,y2:n.y+n.height/2,color:this.debugStyle.gapColor,opacity:n.strong?.9:.55,width:1})})}mergeBoxes(e){if(e.length===0)return[];const t=[...e].sort((n,r)=>n.y===r.y?n.x-r.x:n.y-r.y),i=[];for(const n of t){const r=i[i.length-1];if(!r){i.push({...n});continue}const o=Math.abs(r.y-n.y)<=1,a=n.x<=r.x+r.width+1,l=Math.abs(r.height-n.height)<=1;o&&a&&l?r.width=Math.max(r.x+r.width,n.x+n.width)-r.x:i.push({...n})}return i}}function pn(s){const e=s.match(/rgba?\(([^)]+)\)/i);if(e){const n=(e[1]??"").split(",").map(c=>Number(c.trim())),[r=255,o=255,a=255,l=1]=n;return{color:new T.Color(r/255,o/255,a/255),alpha:Number.isFinite(l)?l:1}}const t=new T.Color;return t.setStyle(s),{color:t,alpha:1}}class vp{constructor(e){E(this,"scene");E(this,"camera");E(this,"frameGroup",new T.Group);E(this,"currentTransform",{x:0,y:0,scaleX:1,scaleY:1,rotation:0});E(this,"canvas",null);this.scene=e.scene,this.camera=e.camera,this.scene.add(this.frameGroup)}initialize(e){this.canvas=e}destroy(){this.clearFrame(),this.scene.remove(this.frameGroup)}beginFrame(){this.clearFrame()}endFrame(){this.camera}drawQuad(e){const t=this.currentTransform.scaleX??1,i=this.currentTransform.scaleY??1,n=this.transformPoint(e.x+e.width/2,e.y),r=this.createQuadMesh(n.x-e.width*t/2,n.y,Math.abs(e.width*t),Math.abs(e.height*i),e.fillColor,e.opacity);if(r&&this.frameGroup.add(r),e.borderColor){const o=this.createRectBorder(n.x-e.width*t/2,n.y,Math.abs(e.width*t),Math.abs(e.height*i),e.borderColor,e.borderWidth??1,e.opacity??1);this.frameGroup.add(o)}}drawLine(e){const t=this.transformPoint(e.x1,e.y1),i=this.transformPoint(e.x2,e.y2),n=pn(e.color),r=(e.opacity??1)*n.alpha;if(e.dashed&&e.dashed.length>0){const h=[new T.Vector3(t.x,t.y,0),new T.Vector3(i.x,i.y,0)],p=new T.BufferGeometry().setFromPoints(h),m=new T.LineDashedMaterial({color:n.color,linewidth:e.width??1,transparent:r<1,opacity:r,dashSize:e.dashed[0]??4,gapSize:e.dashed[1]??2,depthTest:!1}),g=new T.Line(p,m);g.computeLineDistances(),g.renderOrder=e.renderOrder??1,this.frameGroup.add(g);return}const o=new Vh.LineGeometry;o.setPositions([t.x,t.y,0,i.x,i.y,0]);const a=new Gh.LineMaterial({color:n.color,linewidth:e.width??1,worldUnits:!1,transparent:r<1,opacity:r,depthTest:!1}),l=this.getResolution();a.resolution.set(l.x,l.y);const c=new Rh.Line2(o,a);c.computeLineDistances(),c.renderOrder=e.renderOrder??1,this.frameGroup.add(c)}drawText(e){var R;const t=e.font??"20px monospace",i=Number(((R=t.match(/(\d+(?:\.\d+)?)px/))==null?void 0:R[1])??20),n=4,r=document.createElement("canvas");let o=r.getContext("2d");if(!o)return;o.font=t;const l=Math.max(1,Math.ceil(o.measureText(e.text).width))+n*2,c=Math.max(1,Math.ceil(i*1.4));if(r.width=l,r.height=c,o=r.getContext("2d"),!o)return;o.clearRect(0,0,r.width,r.height),o.font=t;const h=e.align??"left",p=e.baseline??"top";o.textAlign=h,o.textBaseline=p;const m=pn(e.color);o.fillStyle=`rgba(${Math.round(m.color.r*255)}, ${Math.round(m.color.g*255)}, ${Math.round(m.color.b*255)}, ${e.opacity??m.alpha})`;const g=h==="center"?r.width/2:h==="right"?r.width-n:n,f=p==="middle"?r.height/2:p==="bottom"?r.height-n:n;o.fillText(e.text,g,f);const w=this.isYAxisUp(),v=new T.CanvasTexture(r);v.flipY=w,v.needsUpdate=!0;const x=Math.abs(this.currentTransform.scaleX??1),S=Math.abs(this.currentTransform.scaleY??1),P=Math.max(1,r.width*x),A=Math.max(1,r.height*S),_=new T.PlaneGeometry(P,A),C=new T.MeshBasicMaterial({map:v,transparent:!0,depthTest:!1,depthWrite:!1,side:T.DoubleSide}),O=new T.Mesh(_,C),j=this.transformPoint(e.x,e.y),L=h==="center"?0:h==="right"?-P/2:P/2,N=p==="middle"?0:p==="bottom"?w?A/2:-A/2:w?-A/2:A/2;O.position.set(j.x+L,j.y+N,.2),O.renderOrder=10,this.frameGroup.add(O)}drawBox(e){const t=this.currentTransform.scaleX??1,i=this.currentTransform.scaleY??1,n=this.transformPoint(e.box.x+e.box.width/2,e.box.y),r=this.createRectBorder(n.x-e.box.width*t/2,n.y,Math.abs(e.box.width*t),Math.abs(e.box.height*i),e.color,e.lineWidth??1,e.opacity??1);r.renderOrder=e.renderOrder??2,this.frameGroup.add(r)}setTransform(e){this.currentTransform={x:e.x??0,y:e.y??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,rotation:e.rotation??0}}resetTransform(){this.currentTransform={x:0,y:0,scaleX:1,scaleY:1,rotation:0}}transformPoint(e,t){const i=this.currentTransform.scaleX??1,n=this.currentTransform.scaleY??1,r=(this.currentTransform.x??0)+e*i,o=(this.currentTransform.y??0)+t*n,a=this.currentTransform.rotation??0;if(a===0)return{x:r,y:o};const l=Math.cos(a),c=Math.sin(a);return{x:r*l-o*c,y:r*c+o*l}}isYAxisUp(){return this.camera instanceof T.OrthographicCamera?this.camera.top>=this.camera.bottom:!0}createLineQuad(e,t,i,n,r){const o=t.x-e.x,a=t.y-e.y,l=Math.max(.001,Math.hypot(o,a)),c=Math.atan2(a,o),h=new T.PlaneGeometry(l,i),p=new T.MeshBasicMaterial({color:n,transparent:r<1,opacity:r,side:T.DoubleSide,depthTest:!1}),m=new T.Mesh(h,p);return m.position.set((e.x+t.x)/2,(e.y+t.y)/2,0),m.rotation.z=c,m}createQuadMesh(e,t,i,n,r,o=1){if(!r)return null;const a=new T.PlaneGeometry(i,n),l=pn(r),c=new T.MeshBasicMaterial({color:l.color,transparent:o*l.alpha<1,opacity:o*l.alpha,side:T.DoubleSide,depthTest:!1}),h=new T.Mesh(a,c);return h.position.set(e+i/2,t,0),h.renderOrder=1,h}createRectBorder(e,t,i,n,r,o,a){const l=pn(r),c=i/2,h=n/2,p=e+c,m=t,g=[new T.Vector3(p-c,m-h,0),new T.Vector3(p+c,m-h,0),new T.Vector3(p+c,m+h,0),new T.Vector3(p-c,m+h,0)],f=new T.BufferGeometry().setFromPoints(g),w=new T.LineBasicMaterial({color:l.color,transparent:a*l.alpha<1,opacity:a*l.alpha,linewidth:o,depthTest:!1});return new T.LineLoop(f,w)}clearFrame(){for(;this.frameGroup.children.length>0;){const e=this.frameGroup.children.pop();e&&this.disposeObject(e)}}disposeObject(e){if("geometry"in e&&e.geometry instanceof T.BufferGeometry&&e.geometry.dispose(),"material"in e){const t=e.material;Array.isArray(t)?t.forEach(i=>this.disposeMaterial(i)):t&&this.disposeMaterial(t)}"children"in e&&e.children.length>0&&[...e.children].forEach(t=>this.disposeObject(t)),e.removeFromParent()}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),e.dispose()}getResolution(){return this.canvas?{x:this.canvas.width||1,y:this.canvas.height||1}:typeof window<"u"?{x:window.innerWidth||1,y:window.innerHeight||1}:{x:1,y:1}}}function kp(s){return s===D.MTextLineAlignment.TOP?"superscript":s===D.MTextLineAlignment.BOTTOM?"subscript":"normal"}function xp(s){return s==="superscript"?D.MTextLineAlignment.TOP:s==="subscript"?D.MTextLineAlignment.BOTTOM:D.MTextLineAlignment.MIDDLE}function Ma(s){return{...s,align:xp(s.script)}}function ui(s){return{underline:s.underline,overline:s.overline,strikeThrough:s.strikeThrough,script:kp(s.align),aci:s.aci,rgb:s.rgb?[...s.rgb]:null,align:s.align,fontFace:{...s.fontFace},capHeight:{...s.capHeight},widthFactor:{...s.widthFactor},charTrackingFactor:{...s.charTrackingFactor},oblique:s.oblique,paragraph:{indent:s.paragraph.indent,left:s.paragraph.left,right:s.paragraph.right,align:s.paragraph.align,tabs:[...s.paragraph.tabs]}}}function he(s){return{underline:s.underline,overline:s.overline,strikeThrough:s.strikeThrough,script:s.script,aci:s.aci,rgb:s.rgb?[...s.rgb]:null,align:s.align,fontFace:{...s.fontFace},capHeight:{...s.capHeight},widthFactor:{...s.widthFactor},charTrackingFactor:{...s.charTrackingFactor},oblique:s.oblique,paragraph:{indent:s.paragraph.indent,left:s.paragraph.left,right:s.paragraph.right,align:s.paragraph.align,tabs:[...s.paragraph.tabs]}}}function hi(s){return s.type==="char"||s.type==="stack"||s.type==="paragraphBreak"||s.type==="columnBreak"||s.type==="wrapAtDimLine"}function Sp(s,e){return s.underline===e.underline&&s.overline===e.overline&&s.strikeThrough===e.strikeThrough&&s.script===e.script&&s.aci===e.aci&&JSON.stringify(s.rgb)===JSON.stringify(e.rgb)&&s.align===e.align&&s.fontFace.family===e.fontFace.family&&s.fontFace.style===e.fontFace.style&&s.fontFace.weight===e.fontFace.weight&&s.capHeight.value===e.capHeight.value&&s.capHeight.isRelative===e.capHeight.isRelative&&s.widthFactor.value===e.widthFactor.value&&s.widthFactor.isRelative===e.widthFactor.isRelative&&s.charTrackingFactor.value===e.charTrackingFactor.value&&s.charTrackingFactor.isRelative===e.charTrackingFactor.isRelative&&s.oblique===e.oblique&&s.paragraph.indent===e.paragraph.indent&&s.paragraph.left===e.paragraph.left&&s.paragraph.right===e.paragraph.right&&s.paragraph.align===e.paragraph.align&&JSON.stringify(s.paragraph.tabs)===JSON.stringify(e.paragraph.tabs)}function Da(s,e){const t=s??ui(new D.MTextContext),i=Ma(t),n=Ma(e);if(Sp(i,n))return"";let r="";if(i.underline!==n.underline&&(r+=n.underline?"\\L":"\\l"),i.overline!==n.overline&&(r+=n.overline?"\\O":"\\o"),i.strikeThrough!==n.strikeThrough&&(r+=n.strikeThrough?"\\K":"\\k"),i.align!==n.align&&(r+=`\\A${n.align};`),(i.aci!==n.aci||JSON.stringify(i.rgb)!==JSON.stringify(n.rgb))&&(n.rgb?r+=`\\c${D.rgb2int(n.rgb)};`:r+=`\\C${n.aci??256};`),i.fontFace.family!==n.fontFace.family||i.fontFace.style!==n.fontFace.style||i.fontFace.weight!==n.fontFace.weight){const o=n.fontFace.weight>=700?1:0,a=n.fontFace.style==="Italic"?1:0;r+=`\\f${n.fontFace.family}|b${o}|i${a};`}return(i.capHeight.value!==n.capHeight.value||i.capHeight.isRelative!==n.capHeight.isRelative)&&(r+=`\\H${ir(n.capHeight)};`),(i.widthFactor.value!==n.widthFactor.value||i.widthFactor.isRelative!==n.widthFactor.isRelative)&&(r+=`\\W${ir(n.widthFactor)};`),(i.charTrackingFactor.value!==n.charTrackingFactor.value||i.charTrackingFactor.isRelative!==n.charTrackingFactor.isRelative)&&(r+=`\\T${ir(n.charTrackingFactor)};`),i.oblique!==n.oblique&&(r+=`\\Q${pi(n.oblique)};`),JSON.stringify(i.paragraph)!==JSON.stringify(n.paragraph)&&(r+=`\\p${Pp(n.paragraph)};`),r}function ir(s){return`${pi(s.value)}${s.isRelative?"x":""}`}function pi(s){return Number.isInteger(s),s.toString()}function Pp(s){const e=[`i${pi(s.indent)}`,`l${pi(s.left)}`,`r${pi(s.right)}`];return s.align!==D.MTextParagraphAlignment.DEFAULT&&e.push(`q${Ap(s.align)}`),s.tabs.length>0&&e.push(`t${s.tabs.map(t=>String(t)).join(",")}`),e.join(",")}function Ap(s){switch(s){case D.MTextParagraphAlignment.LEFT:return"l";case D.MTextParagraphAlignment.RIGHT:return"r";case D.MTextParagraphAlignment.CENTER:return"c";case D.MTextParagraphAlignment.JUSTIFIED:return"j";case D.MTextParagraphAlignment.DISTRIBUTED:return"d";default:return"x"}}function Oa(s,e,t={}){const i=new D.MTextParser(s,e,{...t,yieldPropertyCommands:!1}),n=[];for(const r of i.parse()){const o=ui(r.ctx);switch(r.type){case D.TokenType.WORD:{const a=r.data;for(const l of a)n.push({type:"char",value:l,style:he(o)});break}case D.TokenType.SPACE:n.push({type:"char",value:" ",style:he(o)});break;case D.TokenType.NBSP:n.push({type:"char",value:" ",style:he(o)});break;case D.TokenType.TABULATOR:n.push({type:"char",value:" ",style:he(o)});break;case D.TokenType.STACK:{const[a,l,c]=r.data,h=he(o);c==="^"&&(a.length===0&&l.length>0?h.script="subscript":a.length>0&&l.length===0?h.script="superscript":h.script="normal"),n.push({type:"stack",numerator:a,denominator:l,divider:c,style:h});break}case D.TokenType.NEW_PARAGRAPH:n.push({type:"paragraphBreak",style:he(o)});break;case D.TokenType.NEW_COLUMN:n.push({type:"columnBreak",style:he(o)});break;case D.TokenType.WRAP_AT_DIMLINE:n.push({type:"wrapAtDimLine",style:he(o)});break}}return{nodes:n}}function Cp(s){const e=ui(new D.MTextContext);let t="",i=0;for(;i<s.nodes.length;){const n=s.nodes[i];if(!n)break;if(!hi(n)){t+=za(n),i+=1;continue}const r=n.style;let o="",a=i;for(;a<s.nodes.length;){const l=s.nodes[a];if(!l||!hi(l)||!Fa(r,l.style))break;o+=za(l),a+=1}Fa(r,e)?t+=o:t+=`{${Da(null,r)}${o}}`,i=a}return t}function mn(s,e,t){if(t<=0)return s;const i=yn(e,0,s.nodes.length),n=yn(t,0,s.nodes.length-i);return s.nodes.splice(i,n),s}function _p(s,e,t,i,n){const r=yn(e,0,s.nodes.length),o=yn(t,0,s.nodes.length-r),a=n??ja(s,r)??ui(new D.MTextContext),l=Tp(i,a);return s.nodes.splice(r,o,...l),s}function ja(s,e){for(let t=e-1;t>=0;t--){const i=s.nodes[t];if(i&&hi(i))return he(i.style)}for(let t=e;t<s.nodes.length;t++){const i=s.nodes[t];if(i&&hi(i))return he(i.style)}}function Ep(s){return s===" "?"\\~":s===" "?"^I":s==="\\"?"\\\\":s==="{"?"\\{":s==="}"?"\\}":s==="^"?"\\U+005E":s==="%"?"\\U+0025":s===`
3
- `?"\\P":s==="\r"?"":s}function Ba(s){return s.replace(/[\\;/#^]/g,"\\$&")}function Fa(s,e){return Da(s,e)===""}function za(s){switch(s.type){case"char":return Ep(s.value);case"stack":return Lp(s.numerator,s.denominator,s.divider);case"paragraphBreak":return"\\P";case"columnBreak":return"\\N";case"wrapAtDimLine":return"\\X"}}function Lp(s,e,t){const i=Ba(s),n=Ba(e);if(t==="^"){if(i.length===0&&n.length>0)return`\\S^ ${n};`;if(i.length>0&&n.length===0)return`\\S${i}^ ;`;if(i.length===0&&n.length===0)return"\\S^ ;"}return`\\S${i}${t}${n};`}function Tp(s,e){const t=[];for(const i of s){if(i===`
4
- `){t.push({type:"paragraphBreak",style:he(e)});continue}t.push({type:"char",value:i,style:he(e)})}return t}function yn(s,e,t){return Math.max(e,Math.min(t,s))}class pe{constructor(e={nodes:[]}){E(this,"_ast");E(this,"_cursor");E(this,"_selection",null);this._ast=typeof e=="string"?Oa(e):pe.cloneAst(e),this._cursor=this._ast.nodes.length}static fromMText(e,t){return new pe(Oa(e,t))}get ast(){return this._ast}get length(){return this._ast.nodes.length}get cursor(){return this._cursor}set cursor(e){this._cursor=pe.clamp(e,0,this.length),this._selection=null}get selection(){return this._selection?{...this._selection}:null}setSelection(e,t){const i=pe.normalizeSelection(e,t,this.length);return this._selection=i.start===i.end?null:i,this._cursor=pe.clamp(t,0,this.length),this}clearSelection(){return this._selection=null,this}moveCursor(e,t=!1){const i=pe.clamp(this._cursor+e,0,this.length);if(t){const n=this._selection?this._selection.start:this._cursor;this.setSelection(n,i)}else this.cursor=i;return this}selectAll(){return this.setSelection(0,this.length),this}insertText(e,t){const{start:i,end:n}=this.getActiveRange();return _p(this._ast,i,n-i,e,t),this._cursor=i+e.length,this._selection=null,this}deleteBackward(e=1){if(this.hasSelection()){const{start:i,end:n}=this.getActiveRange();return mn(this._ast,i,n-i),this._cursor=i,this._selection=null,this}if(e<=0||this._cursor<=0)return this;const t=Math.min(e,this._cursor);return mn(this._ast,this._cursor-t,t),this._cursor-=t,this}deleteForward(e=1){if(this.hasSelection()){const{start:t,end:i}=this.getActiveRange();return mn(this._ast,t,i-t),this._cursor=t,this._selection=null,this}return e<=0||this._cursor>=this.length?this:(mn(this._ast,this._cursor,e),this)}replaceSelection(e,t){return this.insertText(e,t)}toMText(){return Cp(this._ast)}transaction(e){const t={ast:pe.cloneAst(this._ast),cursor:this._cursor,selection:this._selection?{...this._selection}:null};try{e(this)}catch(i){throw this._ast=t.ast,this._cursor=t.cursor,this._selection=t.selection,i}return this}hasSelection(){return!!(this._selection&&this._selection.start!==this._selection.end)}getActiveRange(){return this._selection?{...this._selection}:{start:this._cursor,end:this._cursor}}getReferenceStyle(e){return ja(this._ast,e)??ui(new D.MTextContext)}static cloneAst(e){return{nodes:e.nodes.map(t=>t.type==="char"?{...t,style:he(t.style)}:t.type==="stack"?{...t,style:he(t.style)}:{...t,style:he(t.style)})}}static normalizeSelection(e,t,i){const n=pe.clamp(e,0,i),r=pe.clamp(t,0,i);return n<=r?{start:n,end:r}:{start:r,end:n}}static clamp(e,t,i){return Math.max(t,Math.min(i,e))}}class nr{constructor(e){E(this,"document");E(this,"selectionAnchor",null);this.document=e}get anchor(){return this.selectionAnchor}execute(e){switch(e.type){case"setCursor":this.document.cursor=e.index,this.selectionAnchor=null;break;case"setSelection":this.document.setSelection(e.start,e.end),this.selectionAnchor=e.start;break;case"clearSelection":this.document.clearSelection(),this.selectionAnchor=null;break;case"moveLeft":this.moveCursorTo(this.document.cursor-1,e.extend??!1);break;case"moveRight":this.moveCursorTo(this.document.cursor+1,e.extend??!1);break;case"moveToStart":this.moveCursorTo(0,e.extend??!1);break;case"moveToEnd":this.moveCursorTo(this.document.length,e.extend??!1);break;case"selectAll":this.document.selectAll(),this.selectionAnchor=0;break;case"insertText":this.document.insertText(e.text,e.style),this.selectionAnchor=null;break;case"replaceSelection":this.document.replaceSelection(e.text,e.style),this.selectionAnchor=null;break;case"backspace":this.document.deleteBackward(e.count??1),this.selectionAnchor=null;break;case"delete":this.document.deleteForward(e.count??1),this.selectionAnchor=null;break}return this}handleKeyEvent(e){const t=!!(e.metaKey||e.ctrlKey);return t&&!e.altKey&&e.key.toLowerCase()==="a"?(this.execute({type:"selectAll"}),!0):e.key==="ArrowLeft"?(this.execute({type:"moveLeft",extend:!!e.shiftKey}),!0):e.key==="ArrowRight"?(this.execute({type:"moveRight",extend:!!e.shiftKey}),!0):e.key==="Home"?(this.execute({type:"moveToStart",extend:!!e.shiftKey}),!0):e.key==="End"?(this.execute({type:"moveToEnd",extend:!!e.shiftKey}),!0):e.key==="Backspace"?(this.execute({type:"backspace"}),!0):e.key==="Delete"?(this.execute({type:"delete"}),!0):e.key==="Enter"?(this.execute({type:"insertText",text:`
5
- `}),!0):e.key==="Tab"?(this.execute({type:"insertText",text:" "}),!0):!t&&!e.altKey&&e.key.length===1?(this.execute({type:"insertText",text:e.key}),!0):!1}moveCursorTo(e,t){var n;const i=Math.max(0,Math.min(e,this.document.length));if(t){this.selectionAnchor===null&&(this.selectionAnchor=((n=this.document.selection)==null?void 0:n.start)??this.document.cursor),this.document.setSelection(this.selectionAnchor,i);return}this.document.cursor=i,this.selectionAnchor=null}}const Ip={bold:'<svg viewBox="0 0 24 24"><path d="M7.8 19c-.3 0-.5 0-.6-.2l-.2-.5V5.7c0-.2 0-.4.2-.5l.6-.2h5c1.5 0 2.7.3 3.5 1 .7.6 1.1 1.4 1.1 2.5a3 3 0 0 1-.6 1.9c-.4.6-1 1-1.6 1.2.4.1.9.3 1.3.6s.8.7 1 1.2c.4.4.5 1 .5 1.6 0 1.3-.4 2.3-1.3 3-.8.7-2.1 1-3.8 1H7.8Zm5-8.3c.6 0 1.2-.1 1.6-.5.4-.3.6-.7.6-1.3 0-1.1-.8-1.7-2.3-1.7H9.3v3.5h3.4Zm.5 6c.7 0 1.3-.1 1.7-.4.4-.4.6-.9.6-1.5s-.2-1-.7-1.4c-.4-.3-1-.4-2-.4H9.4v3.8h4Z" fill-rule="evenodd"></path></svg>',italic:'<svg viewBox="0 0 24 24"><path d="m16.7 4.7-.1.9h-.3c-.6 0-1 0-1.4.3-.3.3-.4.6-.5 1.1l-2.1 9.8v.6c0 .5.4.8 1.4.8h.2l-.2.8H8l.2-.8h.2c1.1 0 1.8-.5 2-1.5l2-9.8.1-.5c0-.6-.4-.8-1.4-.8h-.3l.2-.9h5.8Z" fill-rule="evenodd"></path></svg>',underline:'<svg viewBox="0 0 24 24"><path d="M16 5c.6 0 1 .4 1 1v5.5a4 4 0 0 1-.4 1.8l-1 1.4a5.3 5.3 0 0 1-5.5 1 5 5 0 0 1-1.6-1c-.5-.4-.8-.9-1.1-1.4a4 4 0 0 1-.4-1.8V6c0-.6.4-1 1-1s1 .4 1 1v5.5c0 .3 0 .6.2 1l.6.7a3.3 3.3 0 0 0 2.2.8 3.4 3.4 0 0 0 2.2-.8c.3-.2.4-.5.6-.8l.2-.9V6c0-.6.4-1 1-1ZM8 17h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 0 1 0-2Z" fill-rule="evenodd"></path></svg>',overline:'<svg viewBox="0 0 24 24"><path d="M5 4h14v1.5H5V4zm7 3.5c3.04 0 5.5 2.46 5.5 5.5v4.5h-2.25v-4.5c0-1.79-1.46-3.25-3.25-3.25S8.75 11.21 8.75 13v4.5H6.5V13c0-3.04 2.46-5.5 5.5-5.5z"></path></svg>',strike:'<svg viewBox="0 0 24 24"><g fill-rule="evenodd"><path d="M15.6 8.5c-.5-.7-1-1.1-1.3-1.3-.6-.4-1.3-.6-2-.6-2.7 0-2.8 1.7-2.8 2.1 0 1.6 1.8 2 3.2 2.3 4.4.9 4.6 2.8 4.6 3.9 0 1.4-.7 4.1-5 4.1A6.2 6.2 0 0 1 7 16.4l1.5-1.1c.4.6 1.6 2 3.7 2 1.6 0 2.5-.4 3-1.2.4-.8.3-2-.8-2.6-.7-.4-1.6-.7-2.9-1-1-.2-3.9-.8-3.9-3.6C7.6 6 10.3 5 12.4 5c2.9 0 4.2 1.6 4.7 2.4l-1.5 1.1Z"></path><path d="M5 11h14a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Z" fill-rule="nonzero"></path></g></svg>',superscript:'<svg viewBox="0 0 24 24"><path d="M15 9.4 10.4 14l4.6 4.6-1.4 1.4L9 15.4 4.4 20 3 18.6 7.6 14 3 9.4 4.4 8 9 12.6 13.6 8 15 9.4Zm5.9 1.6h-5v-1l1-.8 1.7-1.6c.3-.5.5-.9.5-1.3 0-.3 0-.5-.2-.7-.2-.2-.5-.3-.9-.3l-.8.2-.7.4-.4-1.2c.2-.2.5-.4 1-.5.3-.2.8-.2 1.2-.2.8 0 1.4.2 1.8.6.4.4.6 1 .6 1.6 0 .5-.2 1-.5 1.5l-1.3 1.4-.6.5h2.6V11Z" fill-rule="nonzero"></path></svg>',subscript:'<svg viewBox="0 0 24 24"><path d="m10.4 10 4.6 4.6-1.4 1.4L9 11.4 4.4 16 3 14.6 7.6 10 3 5.4 4.4 4 9 8.6 13.6 4 15 5.4 10.4 10ZM21 19h-5v-1l1-.8 1.7-1.6c.3-.4.5-.8.5-1.2 0-.3 0-.6-.2-.7-.2-.2-.5-.3-.9-.3a2 2 0 0 0-.8.2l-.7.3-.4-1.1 1-.6 1.2-.2c.8 0 1.4.3 1.8.7.4.4.6.9.6 1.5s-.2 1.1-.5 1.6a8 8 0 0 1-1.3 1.3l-.6.6h2.6V19Z" fill-rule="nonzero"></path></svg>',stack:'<svg viewBox="0 0 24 24"><path d="M12.4065 5.44832C12.8151 5.44832 13.1994 5.56542 13.5595 5.7996C13.9265 6.0267 14.2208 6.36024 14.4424 6.80022C14.664 7.23312 14.7748 7.74407 14.7748 8.33309C14.7748 8.9292 14.664 9.44725 14.4424 9.88724C14.2208 10.3201 13.9265 10.6501 13.5595 10.8772C13.1994 11.1043 12.8151 11.2179 12.4065 11.2179C12.0464 11.2179 11.7037 11.1291 11.3782 10.9517C11.0527 10.7743 10.7931 10.5082 10.5992 10.1534C10.5715 10.4585 10.5507 10.7743 10.5368 11.1008H9.75781V3H10.6407V6.4383C10.8415 6.11185 11.0977 5.86702 11.4094 5.7038C11.721 5.53348 12.0534 5.44832 12.4065 5.44832ZM12.2923 10.3663C12.7631 10.3663 13.1405 10.1888 13.4245 9.83402C13.7084 9.47919 13.8503 8.97888 13.8503 8.33309C13.8503 7.69439 13.7084 7.19763 13.4245 6.8428C13.1405 6.48797 12.7631 6.31056 12.2923 6.31056C11.8422 6.31056 11.4544 6.47378 11.1289 6.80022C10.8034 7.12667 10.6407 7.63762 10.6407 8.33309C10.6407 8.80856 10.7203 9.19887 10.8796 9.50402C11.0389 9.80918 11.2432 10.0292 11.4925 10.164C11.7417 10.2988 12.0083 10.3663 12.2923 10.3663Z"></path><path d="M12.0949 14.9531C12.7043 14.9531 13.2029 15.1447 13.5906 15.5279C13.9784 15.9041 14.1723 16.4434 14.1723 17.146V20.6056H13.3933C13.3725 20.2436 13.3587 20.0094 13.3517 19.903C13.1856 20.1727 12.9605 20.3785 12.6766 20.5204C12.3996 20.6552 12.0811 20.7227 11.721 20.7227C11.3747 20.7227 11.0493 20.6588 10.7446 20.531C10.4468 20.3962 10.2079 20.2011 10.0279 19.9456C9.84783 19.683 9.75781 19.3708 9.75781 19.0088C9.75781 18.4624 9.97248 18.033 10.4018 17.7208C10.8381 17.4014 11.399 17.2418 12.0845 17.2418C12.4723 17.2418 12.8739 17.295 13.2894 17.4014V17.3056C13.2894 16.7876 13.1856 16.4044 12.9778 16.156C12.777 15.9005 12.4688 15.7728 12.0534 15.7728C11.721 15.7728 11.444 15.8437 11.2224 15.9857C11.0008 16.1276 10.8138 16.337 10.6615 16.6137L9.98633 16.2199C10.1525 15.8367 10.4226 15.5315 10.7965 15.3044C11.1774 15.0702 11.6102 14.9531 12.0949 14.9531ZM13.2894 18.1572C12.8532 18.0437 12.455 17.9869 12.0949 17.9869C11.6448 17.9869 11.2951 18.0756 11.0458 18.253C10.8034 18.4305 10.6823 18.6788 10.6823 18.9982C10.6823 19.2962 10.7861 19.5304 10.9939 19.7007C11.2016 19.864 11.4717 19.9456 11.8041 19.9456C12.2126 19.9456 12.5623 19.8249 12.8532 19.5836C13.144 19.3353 13.2894 18.9946 13.2894 18.5617V18.1572Z""></path><rect x="6.02344" y="12.7119" width="11.9532" height="0.747077"></rect></svg>'},Na="mlightcad-mtext-toolbar-style",Ra=["Arial","Helvetica","Verdana","Tahoma","Trebuchet MS","Times New Roman","Georgia","Courier New","system-ui","sans-serif","serif","monospace"];function Mp(){if(document.getElementById(Na))return;const s=document.createElement("style");s.id=Na,s.textContent=`
1
+ (function(y,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("@mlightcad/data-model"),require("@mlightcad/three-renderer"),require("three"),require("three/examples/jsm/libs/stats.module"),require("three/examples/jsm/renderers/CSS2DRenderer.js"),require("lodash-es"),require("@mlightcad/mtext-renderer"),require("three/examples/jsm/lines/Line2.js"),require("three/examples/jsm/lines/LineGeometry.js"),require("three/examples/jsm/lines/LineMaterial.js")):typeof define=="function"&&define.amd?define(["exports","@mlightcad/data-model","@mlightcad/three-renderer","three","three/examples/jsm/libs/stats.module","three/examples/jsm/renderers/CSS2DRenderer.js","lodash-es","@mlightcad/mtext-renderer","three/examples/jsm/lines/Line2.js","three/examples/jsm/lines/LineGeometry.js","three/examples/jsm/lines/LineMaterial.js"],d):(y=typeof globalThis<"u"?globalThis:y||self,d(y["cad-simple-viewer"]={},y.dataModel,y.threeRenderer,y.THREE,y.Stats,y.CSS2DRenderer_js,y.lodashEs,y.mtextRenderer,y.Line2_js,y.LineGeometry_js,y.LineMaterial_js))})(this,(function(y,d,M,qh,Jh,Qh,Ko,D,ep,tp,ip){"use strict";var Wb=Object.defineProperty;var $b=(y,d,M)=>d in y?Wb(y,d,{enumerable:!0,configurable:!0,writable:!0,value:M}):y[d]=M;var E=(y,d,M)=>$b(y,typeof d!="symbol"?d+"":d,M);function np(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const L=np(qh),Uo='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" aria-hidden="true"><path fill="currentColor" d="M737.216 357.952 704 349.824l-11.776-32a192.064 192.064 0 0 0-367.424 23.04l-8.96 39.04-39.04 8.96A192.064 192.064 0 0 0 320 768h368a207.81 207.81 0 0 0 207.808-208 208.32 208.32 0 0 0-158.592-202.048m15.168-62.208A272.32 272.32 0 0 1 959.744 560a271.81 271.81 0 0 1-271.552 272H320a256 256 0 0 1-57.536-505.536 256.128 256.128 0 0 1 489.92-30.72"/><text x="512" y="580" text-anchor="middle" dominant-baseline="middle" font-size="300" font-family="Arial,sans-serif" fill="currentColor" font-weight="bold">ML</text></svg>',nn="mlightcad",Ho="https://mlightcad.github.io/cad-viewer/",Wo="https://mlightcad.github.io/cad-viewer/docs/",$o="https://github.com/mlightcad/cad-viewer";function zs(s){const e=document.createElement("span");e.className=(s==null?void 0:s.className)??"ml-brand-mark-icon",e.setAttribute("role","img"),e.setAttribute("aria-label",nn),e.innerHTML=Uo;const t=(s==null?void 0:s.size)??"40px";return e.style.width=t,e.style.height=t,e}function Yo(s){const e=document.createElement("div");e.className=(s==null?void 0:s.className)??"ml-brand-mark",e.setAttribute("role","img"),e.setAttribute("aria-label",nn);const t=zs({className:"ml-brand-mark-icon",size:(s==null?void 0:s.iconSize)??"40px"});t.removeAttribute("role"),t.removeAttribute("aria-label");const i=document.createElement("span");return i.className="ml-brand-mark-label",i.textContent=nn,e.appendChild(t),e.appendChild(i),e}function kt(s,e,t,i,n,r){const o=n-t,a=r-i,l=o*o+a*a;if(l<1e-10)return Math.hypot(s-t,e-i);let c=((s-t)*o+(e-i)*a)/l;return c=Math.max(0,Math.min(1,c)),Math.hypot(s-(t+c*o),e-(i+c*a))}function Ns(s,e,t,i=!1){if(t.length===0)return 1/0;if(t.length===1)return Math.hypot(s-t[0].x,e-t[0].y);let n=1/0;const r=i?t.length:t.length-1;for(let o=0;o<r;o++){const a=t[o],l=t[(o+1)%t.length];n=Math.min(n,kt(s,e,a.x,a.y,l.x,l.y))}return n}function sn(s,e,t,i){const n=Math.min(t.x,i.x),r=Math.max(t.x,i.x),o=Math.min(t.y,i.y),a=Math.max(t.y,i.y);return Ns(s,e,[{x:n,y:o},{x:r,y:o},{x:r,y:a},{x:n,y:a}],!0)}function Zo(s,e,t,i){const n=Math.min(t.x,i.x),r=Math.max(t.x,i.x),o=Math.min(t.y,i.y),a=Math.max(t.y,i.y);return s>=n&&s<=r&&e>=o&&e<=a}function Rs(s,e,t,i,n){return Math.abs(Math.hypot(s-t,e-i)-n)}function Xo(s,e,t){let i=!1;for(let n=0,r=t.length-1;n<t.length;r=n++){const o=t[n].x,a=t[n].y,l=t[r].x,c=t[r].y;a>e!=c>e&&s<(l-o)*(e-a)/(c-a+1e-15)+o&&(i=!i)}return i}function Vs(s,e,t,i,n,r,o,a){const l=Math.PI*2,c=24;let h=1/0,p=a?r-o:o-r;p<=0&&(p+=l);for(let m=0;m<=c;m++){const g=m/c,f=a?r-g*p:r+g*p,w=t+n*Math.cos(f),v=i+n*Math.sin(f);h=Math.min(h,Math.hypot(s-w,e-v))}return h}const sp=8;function ae(s,e,t){return{x:s.x+e,y:s.y+t}}function rn(s,e,t){return{tip:ae(s.tip,e,t),anchor:ae(s.anchor,e,t),text:s.text}}function on(s){switch(s.type){case"cloud":case"rect":case"highlight":return{x:(s.corner1.x+s.corner2.x)/2,y:(s.corner1.y+s.corner2.y)/2};case"circle":return{...s.center};case"callout":return{x:(s.tip.x+s.anchor.x)/2,y:(s.tip.y+s.anchor.y)/2};case"arrow":case"line":return{x:(s.start.x+s.end.x)/2,y:(s.start.y+s.end.y)/2};case"text":case"stamp":case"symbol":return{...s.position};default:return}}function Gs(s,e,t){switch(s.type){case"cloud":return{...s,corner1:ae(s.corner1,e,t),corner2:ae(s.corner2,e,t),callout:s.callout?rn(s.callout,e,t):void 0};case"rect":return{...s,corner1:ae(s.corner1,e,t),corner2:ae(s.corner2,e,t),callout:s.callout?rn(s.callout,e,t):void 0};case"highlight":return{...s,corner1:ae(s.corner1,e,t),corner2:ae(s.corner2,e,t)};case"circle":return{...s,center:ae(s.center,e,t),callout:s.callout?rn(s.callout,e,t):void 0};case"callout":return{...s,tip:ae(s.tip,e,t),anchor:ae(s.anchor,e,t)};case"arrow":case"line":return{...s,start:ae(s.start,e,t),end:ae(s.end,e,t)};case"text":case"stamp":case"symbol":return{...s,position:ae(s.position,e,t)}}}function an(s,e,t,i){const n=t(s.tip),r=t(s.anchor);return kt(e.x,e.y,n.x,n.y,r.x,r.y)<=i}function qo(s,e){e&&(s.expandByPoint(e.tip),s.expandByPoint(e.anchor))}function Jo(s){const e=new d.AcGeBox2d;switch(s.type){case"line":case"arrow":e.expandByPoint(s.start).expandByPoint(s.end);break;case"rect":case"cloud":e.expandByPoint(s.corner1).expandByPoint(s.corner2),qo(e,s.callout);break;case"highlight":e.expandByPoint(s.corner1).expandByPoint(s.corner2);break;case"circle":e.expandByPoint({x:s.center.x-s.radius,y:s.center.y-s.radius}).expandByPoint({x:s.center.x+s.radius,y:s.center.y+s.radius}),qo(e,s.callout);break;case"callout":e.expandByPoint(s.tip).expandByPoint(s.anchor);break;case"text":case"stamp":case"symbol":e.expandByPoint(s.position);break;default:return}return e.isEmpty()?void 0:e}function Ks(s,e,t,i){switch(s.type){case"line":case"arrow":{const n=t(s.start),r=t(s.end);return kt(e.x,e.y,n.x,n.y,r.x,r.y)<=i}case"rect":return sn(e.x,e.y,t(s.corner1),t(s.corner2))<=i?!0:s.callout?an(s.callout,e,t,i):!1;case"cloud":return sn(e.x,e.y,t(s.corner1),t(s.corner2))<=i+sp?!0:s.callout?an(s.callout,e,t,i):!1;case"circle":{const n=t(s.center),r=t({x:s.center.x+s.radius,y:s.center.y}),o=Math.hypot(r.x-n.x,r.y-n.y);return Rs(e.x,e.y,n.x,n.y,o)<=i?!0:s.callout?an(s.callout,e,t,i):!1}case"highlight":return Zo(e.x,e.y,t(s.corner1),t(s.corner2))||sn(e.x,e.y,t(s.corner1),t(s.corner2))<=i;case"callout":return an(s,e,t,i);case"text":case"stamp":case"symbol":return!1}}const ln="markup",le="markup-live";class Qo{constructor(){this.records=new Map,this.listeners=new Set,this._dirty=!1}get drawingName(){return this._drawingName}set drawingName(e){this._drawingName=e}get dirty(){return this._dirty}get selectedId(){return this._selectedId}list(){return[...this.records.values()]}get(e){return this.records.get(e)}has(e){return this.records.has(e)}get size(){return this.records.size}upsert(e,t){this.records.set(e.id,e),(t==null?void 0:t.markDirty)!==!1&&(this._dirty=!0),this.emit()}updateMeta(e,t){const i=this.records.get(e);if(!i)return;const n={...i,...t,geometry:t.text!==void 0?rp(i.geometry,t.text):i.geometry,updatedAt:new Date().toISOString()};return this.records.set(e,n),this._dirty=!0,this.emit(),n}updateStyle(e,t){const i=this.records.get(e);if(!i)return;const n={...i,style:{...i.style,...t},updatedAt:new Date().toISOString()};return this.records.set(e,n),this._dirty=!0,this.emit(),n}updateGeometry(e,t){const i=this.records.get(e);if(!i)return;const n={...i,geometry:t,updatedAt:new Date().toISOString()};return this.records.set(e,n),this._dirty=!0,this.emit(),n}removeRecord(e,t){return this.records.delete(e)?(this._selectedId===e&&(this._selectedId=void 0),(t==null?void 0:t.markDirty)!==!1&&(this._dirty=!0),this.emit(),!0):!1}replaceAll(e,t){this.records.clear();for(const i of e)this.records.set(i.id,i);t!==void 0&&(this._drawingName=t),this._selectedId=void 0,this._dirty=!1,this.emit()}restore(e,t){this.records.clear();for(const i of e)this.records.set(i.id,i);this._selectedId=void 0,(t==null?void 0:t.dirty)!==void 0&&(this._dirty=t.dirty),this.emit()}clear(e){this.records.size===0&&this._selectedId==null||(this.records.clear(),this._selectedId=void 0,(e==null?void 0:e.markDirty)!==!1&&(this._dirty=!0),this.emit())}reset(){this.records.clear(),this._selectedId=void 0,this._dirty=!1,this._drawingName=void 0,this.emit()}setSelectedId(e){this._selectedId!==e&&(this._selectedId=e,this.emit())}toSidecar(){return{version:1,drawingName:this._drawingName,markups:this.list()}}markClean(){this._dirty=!1,this.emit()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(){for(const e of[...this.listeners])try{e()}catch{}}}let Us;function K(){return Us||(Us=new Qo),Us}function rp(s,e){return(s.type==="cloud"||s.type==="rect"||s.type==="circle")&&s.callout?{...s,callout:{...s.callout,text:e}}:s}const ea=["open","question","answered","closed"];function ta(s){const e=new d.AcGeBox2d;switch(s.type){case"distance":e.expandByPoint(s.start).expandByPoint(s.end);break;case"angle":e.expandByPoint(s.vertex).expandByPoint(s.arm1).expandByPoint(s.arm2);break;case"area":for(const t of s.points)e.expandByPoint(t);break;case"arc":e.expandByPoint({x:s.center.x-s.radius,y:s.center.y-s.radius}).expandByPoint({x:s.center.x+s.radius,y:s.center.y+s.radius});break;case"point":e.expandByPoint(s.position);break;default:return}return e.isEmpty()?void 0:e}function Hs(s,e,t,i){switch(s.type){case"distance":{const n=t(s.start),r=t(s.end);return kt(e.x,e.y,n.x,n.y,r.x,r.y)<=i}case"angle":{const n=t(s.vertex),r=t(s.arm1),o=t(s.arm2);if(kt(e.x,e.y,n.x,n.y,r.x,r.y)<=i||kt(e.x,e.y,n.x,n.y,o.x,o.y)<=i)return!0;const a=Math.hypot(r.x-n.x,r.y-n.y),l=Math.hypot(o.x-n.x,o.y-n.y),c=Math.max(Math.min(a,l)*.3,15),h=Math.atan2(r.y-n.y,r.x-n.x),p=Math.atan2(o.y-n.y,o.x-n.x),m=d.AcGeMathUtil.normalizeAngle(p-h)>Math.PI;return Vs(e.x,e.y,n.x,n.y,c,h,p,m)<=i}case"area":{const n=s.points.map(t);return n.length<2?!1:Xo(e.x,e.y,n)?!0:Ns(e.x,e.y,n,!0)<=i}case"arc":{const n=t(s.center),r=t(s.start),o=t(s.end),a=Math.hypot(r.x-n.x,r.y-n.y);if(!(a>0))return Rs(e.x,e.y,n.x,n.y,0)<=i;const l=Math.atan2(r.y-n.y,r.x-n.x),c=Math.atan2(o.y-n.y,o.x-n.x);let h=d.AcGeMathUtil.normalizeAngle(c-l)>Math.PI;if(s.through){const p=t(s.through),m=Math.atan2(p.y-n.y,p.x-n.x);h=!d.AcGeMathUtil.isAngleOnCcwSweep(l,m,c)}return Vs(e.x,e.y,n.x,n.y,a,l,c,h)<=i}case"point":return!1}}const ia={showUnits:!0,showApproximate:!0},na={showUnits:!0,showApproximate:!0,applyAngbaseAngdir:!1};let Ue={};function Yb(s){return s}function Ws(s){return{lunits:Ue.lunits??s.lunits,luprec:Ue.luprec??s.luprec,aunits:Ue.aunits??s.aunits,auprec:Ue.auprec??s.auprec}}function op(){return{...Ue}}function ap(s){s.lunits!=null&&(Ue.lunits=s.lunits),s.luprec!=null&&(Ue.luprec=s.luprec),s.aunits!=null&&(Ue.aunits=s.aunits),s.auprec!=null&&(Ue.auprec=s.auprec)}function sa(){Ue={}}function lp(s){const e=Ws(s);return e.lunits!==s.lunits||e.luprec!==s.luprec||e.aunits!==s.aunits||e.auprec!==s.auprec}function ra(s,e){if(!lp(s))return e();const t=Ws(s),i=s,n={lunits:i._lunits,luprec:i._luprec,aunits:i._aunits,auprec:i._auprec};i._lunits=t.lunits,i._luprec=t.luprec,i._aunits=t.aunits,i._auprec=t.auprec;try{return e()}finally{i._lunits=n.lunits,i._luprec=n.luprec,i._aunits=n.aunits,i._auprec=n.auprec}}function _e(s,e,t=ia){return ra(s,()=>s.formatter.formatLength(e,t))}function cn(s,e,t=na){return ra(s,()=>s.formatter.formatAngle(e,t))}function $s(s,e){switch(e.kind){case"length":return _e(s,e.value);case"area":return`${_e(s,e.value)}²`;case"angle":return cn(s,e.radians);case"coordinate":{const t=_e(s,e.x),i=_e(s,e.y);return`X ${t} Y ${i}`}}}function li(s){if(!s.isByColor)return s;const e=s.RGB;if(e==null)return s;const t=d.AcCmColorUtil.getIndexByColor(e);if(t==null)return s;const i=new d.AcCmColor;return i.colorIndex=t,i}const Bt=d.AcGiLineWeight.LineWeight070,jt=13;let dn,Ys=Bt,Zs=jt;function Oe(s){return dn?dn.clone():d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.MEASUREMENTCOLOR,s)}function tt(){return Ys}function Be(){return Zs}function oa(s){dn=s.clone()}function aa(s){s>0&&(Ys=s)}function la(s){!Number.isFinite(s)||s<=0||(Zs=s)}function cp(){dn=void 0,Ys=Bt,Zs=jt}function ut(s){return{color:Oe(s),lineWeight:tt(),fontSize:Be()}}function ci(s){return{color:s.color.clone(),lineWeight:s.lineWeight,fontSize:s.fontSize}}function Ee(s){const e=Number(s);return!Number.isFinite(e)||e<=0?2:Math.max(1,e/28)}function Xs(s,e){return`rgba(${s.red}, ${s.green}, ${s.blue}, ${e})`}function ve(s){return s.cssColor??`rgb(${s.red}, ${s.green}, ${s.blue})`}function qs(s){const e=d.AcCmColor.fromString(s);if(e)return li(e);try{return li(new d.AcCmColor().setRGBFromCss(s))}catch{const t=new d.AcCmColor;return t.setRGB(123,135,148),t}}function dp(s){return{all:s=s||new Map,on:function(e,t){var i=s.get(e);i?i.push(t):s.set(e,[t])},off:function(e,t){var i=s.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):s.set(e,[]))},emit:function(e,t){var i=s.get(e);i&&i.slice().map(function(n){n(t)}),(i=s.get("*"))&&i.slice().map(function(n){n(e,t)})}}}const ee=dp();function ht(){ee.emit("undo-stack-changed",{})}function pt(s,e,t){var n;const i=((n=s.isUndoRecording)==null?void 0:n.call(s))??!1;s.runDatabaseEdit(e,t),i||(ee.emit("session-db-edit-committed",{}),ht())}let Z;function ca(s){Z=s}class da{constructor(){this.undoStack=[],this.redoStack=[],this.depth=0}get isBusy(){return this.depth>0}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clearRedo(){this.redoStack.length=0}clear(){this.undoStack.length=0,this.redoStack.length=0}run(e,t,i){if(this.depth>0){i();return}const n=K(),r=ha(n.list()),o=n.dirty;this.depth++;try{i()}finally{this.depth--}const a=ha(n.list()),l=n.dirty;up(r,a)&&o===l||(this.undoStack.push({label:t,before:r,after:a,beforeDirty:o,afterDirty:l}),this.redoStack.length=0,xt().recordMarkup(),ht())}undo(){const e=this.undoStack.pop();return e?(this.apply(e.before,e.beforeDirty),this.redoStack.push(e),!0):!1}redo(){const e=this.redoStack.pop();return e?(this.apply(e.after,e.afterDirty),this.undoStack.push(e),!0):!1}apply(e,t){this.depth++;try{K().restore(e,{dirty:t})}finally{this.depth--}}}class ua{constructor(){this.undoKinds=[],this.redoKinds=[]}recordDb(){this.undoKinds.push("db"),this.redoKinds.length=0,fe().clearRedo(),Z==null||Z.clearRedo()}recordMarkup(){this.undoKinds.push("markup"),this.redoKinds.length=0,Z==null||Z.clearRedo()}recordOverlay(){this.undoKinds.push("overlay"),this.redoKinds.length=0,fe().clearRedo()}canUndo(e){var t;return this.undoKinds.length>0||fe().canUndo()||((Z==null?void 0:Z.canUndo())??!1)||(((t=e.transactionManager)==null?void 0:t.canUndo())??!1)}canRedo(e){var t;return this.redoKinds.length>0||fe().canRedo()||((Z==null?void 0:Z.canRedo())??!1)||(((t=e.transactionManager)==null?void 0:t.canRedo())??!1)}undo(e){var t;for(;;){const i=this.undoKinds.pop();if(i==="markup"){if(fe().undo())return this.redoKinds.push("markup"),"markup";continue}if(i==="overlay"){if(Z!=null&&Z.undo())return this.redoKinds.push("overlay"),"overlay";continue}if(i==="db"){if(e.transactionManager.undo())return this.redoKinds.push("db"),"db";continue}return fe().undo()?(this.redoKinds.push("markup"),"markup"):Z!=null&&Z.undo()?(this.redoKinds.push("overlay"),"overlay"):(t=e.transactionManager)!=null&&t.undo()?(this.redoKinds.push("db"),"db"):!1}}redo(e){var t;for(;;){const i=this.redoKinds.pop();if(i==="markup"){if(fe().redo())return this.undoKinds.push("markup"),"markup";continue}if(i==="overlay"){if(Z!=null&&Z.redo())return this.undoKinds.push("overlay"),"overlay";continue}if(i==="db"){if(e.transactionManager.redo())return this.undoKinds.push("db"),"db";continue}return fe().redo()?(this.undoKinds.push("markup"),"markup"):Z!=null&&Z.redo()?(this.undoKinds.push("overlay"),"overlay"):(t=e.transactionManager)!=null&&t.redo()?(this.undoKinds.push("db"),"db"):!1}}clear(){this.undoKinds.length=0,this.redoKinds.length=0,Z==null||Z.clear()}}let Js,Qs;function fe(){return Js||(Js=new da),Js}function xt(){return Qs||(Qs=new ua),Qs}function ke(s,e,t){fe().run(s,e,t)}ee.on("session-db-edit-committed",()=>{xt().recordDb()});function ha(s){return structuredClone(s)}function up(s,e){return s.length!==e.length?!1:JSON.stringify(s)===JSON.stringify(e)}class pa{constructor(){this.undoStack=[],this.redoStack=[],this.depth=0}get isBusy(){return this.depth>0}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clearRedo(){for(const e of this.redoStack)ya(e);this.redoStack.length=0}clear(){for(const e of[...this.undoStack,...this.redoStack])ya(e);this.undoStack.length=0,this.redoStack.length=0}run(e,t,i){if(this.depth>0){i();return}const n=e,r=er(n),o=ma(r);this.depth++;try{i()}finally{this.depth--}const a=er(n),l=a.filter(p=>r.indexOf(p)<0),c=r.filter(p=>a.indexOf(p)<0),h=ma(a);l.length===0&&c.length===0&&!hp(o,h)||(this.undoStack.push({label:t,view:n,added:l,removed:c,stylesBefore:o,stylesAfter:h}),this.clearRedo(),xt().recordOverlay(),ht())}undo(){const e=this.undoStack.pop();return e?(this.apply(e,"undo"),this.redoStack.push(e),!0):!1}redo(){const e=this.redoStack.pop();return e?(this.apply(e,"redo"),this.undoStack.push(e),!0):!1}apply(e,t){this.depth++;try{const i=e.view.htmlTransientManager,n=t==="undo"?e.added:e.removed,r=t==="undo"?e.removed:e.added;for(const a of n)i.detach(a.id);for(const a of r)i.reattach(a);const o=t==="undo"?e.stylesBefore:e.stylesAfter;for(const a of er(e.view)){const l=o[a.id];l&&sr(e.view,a,l)}e.view.isHtmlDirty=!0}finally{this.depth--}}}function er(s){return s.htmlTransientManager.groupsOnLayer(W)}function ma(s){const e={};for(const t of s){const i=St(t.id);i&&(e[t.id]=ci(i))}return e}function hp(s,e){const t=Object.keys(s),i=Object.keys(e);if(t.length!==i.length)return!0;for(const n of t){const r=s[n],o=e[n];if(!o||r.lineWeight!==o.lineWeight||r.fontSize!==o.fontSize||r.color.red!==o.color.red||r.color.green!==o.color.green||r.color.blue!==o.color.blue)return!0}return!1}function ya(s){const e=s.view.htmlTransientManager;for(const t of[...s.added,...s.removed])if(!e.has(t.id)){for(const i of t.children)i.dispose();t.dispose()}}let tr;function it(){return tr||(tr=new pa),tr}function Ft(s,e,t){it().run(s,e,t)}function ga(){it().clear(),La(),sa(),xa()}function fa(){ca({canUndo:()=>it().canUndo(),canRedo:()=>it().canRedo(),undo:()=>it().undo(),redo:()=>it().redo(),clearRedo:()=>it().clearRedo(),clear:()=>it().clear()})}fa();const pp=["distance","angle","area","arc","point"];function di(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function je(s){return di(s)&&typeof s.x=="number"&&typeof s.y=="number"&&Number.isFinite(s.x)&&Number.isFinite(s.y)}function mp(s){return typeof s=="string"&&pp.includes(s)}function yp(s){if(!di(s)||typeof s.color!="string")return;const e=typeof s.lineWeight=="number"&&s.lineWeight>0?s.lineWeight:Bt,t=typeof s.fontSize=="number"&&s.fontSize>0?s.fontSize:jt;return{color:s.color,lineWeight:e,fontSize:t}}function gp(s,e){if(!(!di(e)||e.type!==s))switch(s){case"distance":return!je(e.start)||!je(e.end)?void 0:{type:s,start:e.start,end:e.end};case"angle":return!je(e.vertex)||!je(e.arm1)||!je(e.arm2)?void 0:{type:s,vertex:e.vertex,arm1:e.arm1,arm2:e.arm2};case"area":return!Array.isArray(e.points)||e.points.length<3||!e.points.every(je)?void 0:{type:s,points:e.points};case"arc":return!je(e.center)||typeof e.radius!="number"||!(e.radius>0)||!je(e.start)||!je(e.end)?void 0:{type:s,center:e.center,radius:e.radius,start:e.start,end:e.end,...je(e.through)?{through:e.through}:{}};case"point":return je(e.position)?{type:s,position:e.position}:void 0}}function fp(s){if(!di(s)||typeof s.id!="string"||!mp(s.type))return;const e=yp(s.style),t=gp(s.type,s.geometry);if(!(!e||!t))return{id:s.id,type:s.type,layoutId:typeof s.layoutId=="string"?s.layoutId:void 0,style:e,geometry:t}}function mt(s){return{color:ve(s.color),lineWeight:s.lineWeight,fontSize:s.fontSize}}function ba(s){return{color:qs(s.color),lineWeight:s.lineWeight>0?s.lineWeight:Bt,fontSize:s.fontSize>0?s.fontSize:jt}}function wa(s){let e;try{e=JSON.parse(s)}catch{throw new Error("Invalid measurement sidecar: not JSON")}if(!di(e)||e.version!==1)throw new Error("Invalid measurement sidecar: expected version 1");if(!Array.isArray(e.measurements))throw new Error("Invalid measurement sidecar: measurements must be an array");const t=[];for(const i of e.measurements){const n=fp(i);n&&t.push(n)}return{version:1,drawingName:typeof e.drawingName=="string"?e.drawingName:void 0,measurements:t}}function va(s){return`${JSON.stringify(s,null,2)}
2
+ `}function ka(s){return s?`${s.replace(/\.(dwg|dxf)$/i,"")}.measurement.json`:"drawing.measurement.json"}const W="measurement",oe="measurement-live";let ui=!0;function ir(){return ui}function xa(){ui=!0}function Sa(s,e){ui=e;const t=s.activeLayoutBtrId,i=s.htmlTransientManager;for(const n of i.groupsOnLayer(W))(n.layoutId==null||n.layoutId===t)&&n.setVisible(e);i.setVisible(e,oe),s.isHtmlDirty=!0}const yt=new Map,zt=new Map,nr=new Set;let nt;function St(s){const e=zt.get(s);return e?ci(e):void 0}function Pa(){return nt}function Aa(){return nt?St(nt):void 0}function Ca(s){return nr.add(s),()=>{nr.delete(s)}}function un(){for(const s of nr)s()}function _a(s,e){zt.set(s,ci(e))}function sr(s,e,t){var a;const i=zt.get(e.id),n=((a=t.color)==null?void 0:a.clone())??(i==null?void 0:i.color.clone());if(!n)return;const r={color:n,lineWeight:t.lineWeight??(i==null?void 0:i.lineWeight)??Bt,fontSize:t.fontSize??(i==null?void 0:i.fontSize)??jt};_a(e.id,r);const o=yt.get(e.id);o&&(o.style=ci(r),o.snapshot&&(o.snapshot={...o.snapshot,style:mt(r)})),bp(s,e,r)}function hn(s,e){const t=s.htmlTransientManager.getSelectedGroups().filter(i=>i.layer===W);t.length!==0&&Ft(s,"Measurement Style",()=>{for(const i of t)sr(s,i,e)})}function bp(s,e,t){var n,r,o;for(const a of e.children){const l=a;(n=l.setColor)==null||n.call(l,t.color),(r=l.setFontSize)==null||r.call(l,t.fontSize)}const i=yt.get(e.id);(o=i==null?void 0:i.redraw)==null||o.call(i,t),s.isHtmlDirty=!0}function wp(s,e){var t;for(const i of s.htmlTransientManager.groupsOnLayer(W)){const n=yt.get(i.id);if(!(n!=null&&n.value))continue;const r=$s(e,n.value);for(const o of i.children){const a=o;(t=a.setText)==null||t.call(a,r)}}s.isHtmlDirty=!0}function Ea(s){const e=[];for(const t of s.htmlTransientManager.groupsOnLayer(W)){const i=yt.get(t.id);if(!(i!=null&&i.snapshot))continue;const n=i.style??zt.get(t.id);e.push({...i.snapshot,id:t.id,layoutId:t.layoutId,style:n?mt(n):i.snapshot.style})}return e}function La(){yt.clear(),zt.clear(),nt=void 0,un()}function Ta(s,e,t){const i=(t==null?void 0:t.entityIds)??[];yt.set(e.id,t??{}),t!=null&&t.style&&_a(e.id,t.style);const n=e.onSelectedChanged;e.onSelectedChanged=(a,l)=>{n==null||n(a,l),a?(nt=l.id,un(),i.length>0&&s.highlight(i)):(nt===l.id&&(nt=void 0,un()),i.length>0&&s.unhighlight(i))};const r=e.onVisibleChanged;e.onVisibleChanged=(a,l)=>{r==null||r(a,l);for(const c of i)s.setTransientEntityVisible(c,a)};const o=e.onDispose;e.onDispose=()=>{var a;o==null||o(),yt.delete(e.id),zt.delete(e.id),nt===e.id&&(nt=void 0,un()),i.length>0&&s.unhighlight(i);try{(a=t==null?void 0:t.dispose)==null||a.call(t)}catch{}},Ft(s,"Create Measurement",()=>{s.htmlTransientManager.add(e)}),!ui&&(e.layoutId==null||e.layoutId===s.activeLayoutBtrId)&&e.setVisible(!1),s.isHtmlDirty=!0}function rr(s){var e,t;return(t=(e=yt.get(s))==null?void 0:e.snapshot)==null?void 0:t.geometry}function Ia(s,e,t,i){if(!ui)return;const n={x:e,y:t},r=a=>s.worldToScreen(a),o=s.htmlTransientManager.groupsOnLayer(W);for(let a=o.length-1;a>=0;a--){const l=o[a];if(!l.visible)continue;const c=rr(l.id);if(c&&Hs(c,n,r,i))return l.id}}function Nt(s,e){return s.minX>=e.minX&&s.maxX<=e.maxX&&s.minY>=e.minY&&s.maxY<=e.maxY}function vp(s){var e;return 80+(((e=s.id)==null?void 0:e.length)??0)*2}function Ma(s,e=32){const t=s.length;if(t===0)return 0;const i=Math.min(t,e);let n=0;for(let r=0;r<i;r++)n+=vp(s[r]);return Math.round(n/i*t)}const Da=10;function Oa(s){return{minX:s.min.x,minY:s.min.y,maxX:s.max.x,maxY:s.max.y}}function kp(s,e){return!(s.maxX<e.minX||s.minX>e.maxX||s.maxY<e.minY||s.minY>e.maxY)}function Ba(s,e,t){const i=Oa(s);return t==="window"?Nt(i,e):kp(i,e)}function xp(s,e,t,i){const n={x:e,y:t},r=l=>s.worldToScreen(l),o=s.activeLayoutBtrId,a=K().list();for(let l=a.length-1;l>=0;l--){const c=a[l];if(c.layoutId!=null&&c.layoutId!==o)continue;const h=s.htmlTransientManager.getGroup(c.id);if(h!=null&&h.visible&&Ks(c.geometry,n,r,i))return c.id}}function ja(s,e,t){const i=Oa(e),n=s.activeLayoutBtrId,r=[];for(const o of K().list()){if(o.layoutId!=null&&o.layoutId!==n)continue;const a=s.htmlTransientManager.getGroup(o.id);if(!(a!=null&&a.visible))continue;const l=Jo(o.geometry);l&&Ba(l,i,t)&&r.push(o.id)}if(!ir())return r;for(const o of s.htmlTransientManager.groupsOnLayer(W)){if(!o.visible||o.layoutId!=null&&o.layoutId!==n)continue;const a=rr(o.id);if(!a)continue;const l=ta(a);l&&Ba(l,i,t)&&r.push(o.id)}return r}function Sp(s,e,t){const i=s.htmlTransientManager;return t==="remove"?i.deselectGroup(e):t==="add"?i.selectGroup(e,!1):(i.selectGroup(e,!0),!0)}function Pp(s,e,t){const i=s.htmlTransientManager;let n=!1;if(t==="replace"){const r=i.hasSelection();i.deselectAll();for(const o of e)i.selectGroup(o,!1)&&(n=!0);return r||n}if(e.length===0)return!1;if(t==="add"){for(const r of e)i.selectGroup(r,!1)&&(n=!0);return n}for(const r of e)i.deselectGroup(r)&&(n=!0);return n}function Fa(s,e,t,i){const n=Math.max(s.selectionBoxSize*2,Da),r=xp(s,e,t,n),o=Ia(s,e,t,n),a=r??o;if(!a)return!1;const l=Sp(s,a,i);return l&&(s.isHtmlDirty=!0),l}function za(s,e,t,i){const n=ja(s,e,t),r=Pp(s,n,i);return r&&(s.isHtmlDirty=!0),r}const pn="simkai";function Ap(){return{fontFamily:pn,fontSize:24,bold:!1,italic:!1,underline:!1,overline:!1,strike:!1,script:"normal",aci:null,rgb:16777215,obliqueAngle:0,widthFactor:1,tracking:1,paragraphAlignment:D.MTextParagraphAlignment.DEFAULT}}function Na(s,e){return s.fontFamily===e.fontFamily&&s.fontSize===e.fontSize&&s.bold===e.bold&&s.italic===e.italic&&s.underline===e.underline&&s.overline===e.overline&&s.strike===e.strike&&s.script===e.script&&s.aci===e.aci&&s.rgb===e.rgb&&s.obliqueAngle===e.obliqueAngle&&s.widthFactor===e.widthFactor&&s.tracking===e.tracking&&s.paragraphAlignment===e.paragraphAlignment}function xe(s,e,t){return Math.min(t,Math.max(e,s))}function Cp(s,e){const t=Math.max(s.y-s.height/2,e.y-e.height/2),i=Math.min(s.y+s.height/2,e.y+e.height/2);return Math.max(0,i-t)}class _p{constructor(e){E(this,"containerBox");E(this,"charBoxes");E(this,"explicitLineBreakIndices",[]);E(this,"explicitLineLayouts",[]);E(this,"cursorLineHint",null);E(this,"verticalAlign");E(this,"lineTolerance");E(this,"debug");E(this,"lines",[]);E(this,"cursorIndex",0);E(this,"selection",null);E(this,"dragAnchor",null);E(this,"preferredX",null);E(this,"handlers",{cursorMove:new Set,selectionChange:new Set,linesUpdate:new Set});this.containerBox={...e.containerBox};const t=this.normalizeCharLayout(e.charBoxes,e.lineBreakIndices);this.charBoxes=t.charBoxes,this.explicitLineBreakIndices=t.lineBreakIndices,this.explicitLineLayouts=this.normalizeLineLayouts(e.lineLayouts),this.verticalAlign=e.verticalAlign??"center",this.lineTolerance=e.lineTolerance??5,this.debug=e.debug??!1,this.cursorIndex=xe(e.initialIndex??0,0,this.charBoxes.length),this.recomputeLines(),e.initialSelection&&this.setSelection(e.initialSelection.start,e.initialSelection.end)}moveLeft(){if(this.selection&&!this.selection.isCollapsed){this.cursorIndex=this.selection.start,this.cursorLineHint=null,this.clearSelection(),this.emitCursor();return}const e=this.getCurrentLineIndex();if(e>=0){const t=this.lines[e];if(t){if(this.cursorIndex>t.startIndex&&this.cursorIndex<=t.endIndex+1){this.moveTo(this.cursorIndex-1,e);return}if(this.cursorIndex===t.startIndex&&e>0){this.moveTo(this.cursorIndex,e-1);return}}}this.moveTo(this.cursorIndex-1)}moveRight(){if(this.selection&&!this.selection.isCollapsed){this.cursorIndex=this.selection.end,this.cursorLineHint=null,this.clearSelection(),this.emitCursor();return}const e=this.getCurrentLineIndex();if(e>=0){const t=this.lines[e],i=e+1;if(t&&this.cursorIndex===t.endIndex&&i<this.lines.length&&this.isHardBreakChar(t.endIndex)){this.moveTo(t.endIndex+1,i);return}if(t&&this.cursorIndex===t.endIndex+1&&i<this.lines.length){this.moveTo(this.cursorIndex,i);return}}this.cursorIndex>=this.charBoxes.length||this.moveTo(this.cursorIndex+1)}moveUp(){this.moveVertical(-1)}moveDown(){this.moveVertical(1)}moveTo(e,t=null){const i=xe(e,0,this.charBoxes.length);i===this.cursorIndex&&this.cursorLineHint===t||(this.cursorIndex=i,this.cursorLineHint=t,this.preferredX=null,this.emitCursor())}moveToStart(){this.moveTo(0)}moveToEnd(){this.moveTo(this.charBoxes.length)}moveToLineStart(){const e=this.getCurrentLineIndex();if(e<0){this.moveToStart();return}const t=this.lines[e];t&&this.moveTo(t.startIndex,e)}moveToLineEnd(){const e=this.getCurrentLineIndex();if(e<0){this.moveToEnd();return}const t=this.lines[e];t&&this.moveTo(t.endIndex+1,e)}setSelection(e,t){const i=xe(e,0,this.charBoxes.length),n=xe(t,0,this.charBoxes.length);this.setSelectionWithDirection(i,n)}clearSelection(){this.selection&&(this.selection=null,this.dragAnchor=null,this.emit("selectionChange",null))}selectAll(){this.setSelectionWithDirection(0,this.charBoxes.length),this.cursorIndex=this.charBoxes.length,this.cursorLineHint=null,this.emitCursor()}setSelectionWithDirection(e,t){const i=xe(e,0,this.charBoxes.length),n=xe(t,0,this.charBoxes.length),r=Math.min(i,n),o=Math.max(i,n);this.selection={start:r,end:o,isCollapsed:r===o,anchor:i,active:n,isBackwards:n<i,selectedLines:this.resolveSelectedLines(r,o)},this.cursorIndex=n,this.cursorLineHint=null,this.emit("selectionChange",this.selection),this.emitCursor()}extendSelection(e){var n;const t=xe(e,0,this.charBoxes.length),i=((n=this.selection)==null?void 0:n.anchor)??this.cursorIndex;this.setSelectionWithDirection(i,t)}getSelection(){return this.selection?{...this.selection,selectedLines:[...this.selection.selectedLines]}:null}getSelectedCharBoxes(){return!this.selection||this.selection.isCollapsed?[]:this.charBoxes.slice(this.selection.start,this.selection.end).map(e=>({...e}))}getSelectedLines(){if(!this.selection||this.selection.isCollapsed)return[];const e=[],{start:t,end:i}=this.selection;for(let n=0;n<this.lines.length;n++){const r=this.lines[n];if(!r)continue;const o=r.startIndex,a=r.endIndex+1,l=Math.max(t,o),c=Math.min(i,a);l<c&&e.push({lineIndex:n,startOffset:l-o,endOffset:c-o})}return e}hasSelection(){return!!this.selection&&!this.selection.isCollapsed}moveToClick(e,t){const i=this.hitTest(e,t);if(i<0)return!1;const n=this.hitTestLine(t);return this.clearSelection(),this.moveTo(i,n>=0?n:null),!0}extendSelectionToClick(e,t){const i=this.hitTestClamped(e,t);i<0||(this.dragAnchor===null&&(this.dragAnchor=this.cursorIndex),this.setSelectionWithDirection(this.dragAnchor,i))}updateSelectionDrag(e,t){const i=this.hitTestClamped(e,t);i<0||(this.dragAnchor===null&&(this.dragAnchor=this.cursorIndex),this.setSelectionWithDirection(this.dragAnchor,i))}hitTest(e,t){if(!this.isInContainer(e,t))return-1;if(this.charBoxes.length===0)return 0;const i=this.hitTestLine(t);return i<0?-1:this.closestIndexInLine(i,e)}hitTestLine(e){if(this.lines.length===0)return-1;let t=-1,i=Number.POSITIVE_INFINITY;for(let n=0;n<this.lines.length;n++){const r=this.lines[n];if(!r)continue;const o=r.y-r.height/2,a=r.y+r.height/2;if(e>=o&&e<=a)return n;const l=e<o?o-e:e-a;l<i&&(i=l,t=n)}return t}getLines(){return this.lines.map(e=>({...e}))}getLineCount(){return this.lines.length}getLineIndex(e){if(this.lines.length===0)return-1;const t=xe(e,0,this.charBoxes.length);for(let i=0;i<this.lines.length;i++){const n=this.lines[i];if(n&&t>=n.startIndex&&t<=n.endIndex+1)return i}return this.lines.length-1}getLineInfo(e){const t=this.lines[e];if(!t)throw new Error(`Line index out of range: ${e}`);return{...t}}getCurrentLineInfo(){const e=this.getCurrentLineIndex();if(e<0)return{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0};const t=this.lines[e];return t?{...t}:{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0}}getCursorState(){var n,r;const e=this.getCurrentLineIndex(),t=this.getCursorPosition(),i=e>=0&&this.lines[e]?this.lines[e]:{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0};return{index:this.cursorIndex,position:t,lineIndex:e,lineInfo:{...i},isAtStart:this.cursorIndex===0,isAtEnd:this.cursorIndex===this.charBoxes.length,isAtLineStart:e<0?!0:this.cursorIndex===(((n=this.lines[e])==null?void 0:n.startIndex)??this.cursorIndex),isAtLineEnd:e<0?!0:this.cursorIndex===(((r=this.lines[e])==null?void 0:r.endIndex)??this.cursorIndex-1)+1}}getCurrentIndex(){return this.cursorIndex}getCursorPosition(){if(this.lines.length===0)return{x:this.containerBox.x,y:this.alignY(this.containerBox.y,this.containerBox.height)};const e=this.getCurrentLineIndex(),t=this.lines[Math.max(0,e)];if(!t)return{x:this.containerBox.x,y:this.alignY(this.containerBox.y,this.containerBox.height)};const i=this.alignY(t.y,t.height);return{x:this.indexToX(this.cursorIndex,e),y:i}}getCharBoxes(){return this.charBoxes.map(e=>({...e}))}getContainerBox(){return{...this.containerBox}}updateData(e,t,i,n){this.containerBox={...e};const r=this.normalizeCharLayout(t,i);if(this.charBoxes=r.charBoxes,this.explicitLineBreakIndices=r.lineBreakIndices,this.explicitLineLayouts=this.normalizeLineLayouts(n),this.recomputeLines(),this.cursorIndex=xe(this.cursorIndex,0,this.charBoxes.length),this.cursorLineHint=null,this.selection){const o=xe(this.selection.anchor,0,this.charBoxes.length),a=xe(this.selection.active,0,this.charBoxes.length);o===a?this.selection=null:this.setSelectionWithDirection(o,a)}this.emit("linesUpdate",this.getLines()),this.emitCursor()}setLineTolerance(e){this.lineTolerance=Math.max(0,e),this.recomputeLines(),this.emit("linesUpdate",this.getLines()),this.emitCursor(),this.selection&&(this.selection.selectedLines=this.resolveSelectedLines(this.selection.start,this.selection.end),this.emit("selectionChange",this.selection))}on(e,t){this.handlers[e].add(t)}off(e,t){(e==="cursorMove"||e==="selectionChange"||e==="linesUpdate")&&this.handlers[e].delete(t)}enableDebug(){this.debug=!0}disableDebug(){this.debug=!1}getDebugInfo(){return{debug:this.debug,container:this.getContainerBox(),cursor:this.getCursorState(),selection:this.getSelection(),lines:this.getLines(),gaps:this.lines.map((e,t)=>this.getGapPositions(t))}}destroy(){this.handlers.cursorMove.clear(),this.handlers.selectionChange.clear(),this.handlers.linesUpdate.clear(),this.selection=null,this.dragAnchor=null,this.preferredX=null}emitCursor(){this.emit("cursorMove",this.getCursorState())}emit(e,t){for(const i of this.handlers[e])i(t)}moveVertical(e){const t=this.getCurrentLineIndex();if(t<0)return;const i=this.lines[t],n=t+e;if(n<0||n>=this.lines.length)return;(this.preferredX===null||(i==null?void 0:i.charCount)===0)&&(this.preferredX=this.getCursorPosition().x);const r=this.closestIndexInLine(n,this.preferredX);this.cursorIndex=r,this.cursorLineHint=n,this.emitCursor()}getCurrentLineIndex(){const e=this.getLineIndex(this.cursorIndex);if(e<0||this.cursorLineHint===null)return e;const t=this.lines[this.cursorLineHint];return t&&this.cursorIndex>=t.startIndex&&this.cursorIndex<=t.endIndex+1?this.cursorLineHint:e}isHardBreakChar(e){const t=this.charBoxes[e];return t?t.width===0:!1}resolveSelectedLines(e,t){if(e===t)return[];const i=[];for(let n=0;n<this.lines.length;n++){const r=this.lines[n];r&&t>r.startIndex&&e<r.endIndex+1&&i.push(n)}return i}isInContainer(e,t){return e>=this.containerBox.x&&e<=this.containerBox.x+this.containerBox.width&&t>=this.containerBox.y&&t<=this.containerBox.y+this.containerBox.height}hitTestClamped(e,t){if(this.charBoxes.length===0)return 0;const i=this.lines.length===0?-1:this.hitTestLine(t);return i<0?e<=this.containerBox.x?0:e>=this.containerBox.x+this.containerBox.width?this.charBoxes.length:xe(this.cursorIndex,0,this.charBoxes.length):this.closestIndexInLine(i,e)}recomputeLines(){if(this.explicitLineBreakIndices.length>0){this.lines=this.linesFromBreakIndices(this.charBoxes,this.explicitLineBreakIndices,this.explicitLineLayouts);return}this.lines=this.detectLines(this.charBoxes,this.lineTolerance)}normalizeCharLayout(e,t){const i=[],n=[];for(const a of e){if(!a){n.push(i.length);continue}i.push({...a})}const r=[...n,...t??[]],o=this.normalizeBreakIndices(r,i.length);return{charBoxes:i,lineBreakIndices:o}}normalizeBreakIndices(e,t){if(e.length===0)return[];const i=[];for(const n of e){if(!Number.isFinite(n))continue;const r=xe(Math.round(n),0,t);i.push(r)}return i.sort((n,r)=>n-r)}normalizeLineLayouts(e){if(!e||e.length===0)return[];const t=[];for(const i of e)i&&(!Number.isFinite(i.y)||!Number.isFinite(i.height)||t.push({y:i.y,height:Math.max(1,i.height)}));return t}linesFromBreakIndices(e,t,i){if(e.length===0&&t.length===0)return[];if(t.length===0)return this.detectLines(e,this.lineTolerance);const n=[];let r=0;for(const o of t)if(!(o<r||o>e.length)){if(o===r){n.push(this.createEmptyLine(r,n[n.length-1],i[n.length]));continue}n.push(this.withLineLayout(this.aggregateLine(e,r,o-1),i[n.length])),r=o}return r<e.length?n.push(this.withLineLayout(this.aggregateLine(e,r,e.length-1),i[n.length])):n.push(this.createEmptyLine(r,n[n.length-1],i[n.length])),n}detectLines(e,t){if(e.length===0)return[];const i=[],n=.65;let r=0;for(let o=1;o<e.length;o++){const a=e[o-1],l=e[o];if(!a||!l)continue;const c=Math.abs(l.y-a.y),h=l.x+t<a.x,p=Cp(a,l),m=Math.min(a.height,l.height),f=(m>0?p/m:0)<n;(h||c>t&&f)&&(i.push(this.aggregateLine(e,r,o-1)),r=o)}return i.push(this.aggregateLine(e,r,e.length-1)),i}aggregateLine(e,t,i){let n=0,r=0,o=0;for(let a=t;a<=i;a++){const l=e[a];l&&(n+=l.y,r+=1,o=Math.max(o,l.height))}return r===0?{startIndex:t,endIndex:i,y:this.containerBox.y,height:this.containerBox.height,charCount:Math.max(0,i-t+1)}:{startIndex:t,endIndex:i,y:n/r,height:o,charCount:i-t+1}}withLineLayout(e,t){return t?{...e,y:t.y,height:Math.max(1,t.height)}:e}createEmptyLine(e,t,i){if(i)return{startIndex:e,endIndex:e-1,y:i.y,height:Math.max(1,i.height),charCount:0};const n=Math.max(1,(t==null?void 0:t.height)??this.containerBox.height),r=t!==void 0?t.y+n:this.alignY(this.containerBox.y,this.containerBox.height);return{startIndex:e,endIndex:e-1,y:r,height:n,charCount:0}}alignY(e,t){return this.verticalAlign==="top"?e-t/2:this.verticalAlign==="bottom"?e+t/2:e}indexToX(e,t){if(this.charBoxes.length===0)return this.containerBox.x;if(e<=0)return this.containerBox.x;const i=t??this.getLineIndex(e);if(i<0)return this.containerBox.x;const n=this.lines[i];if(!n)return this.containerBox.x;if(e<=n.startIndex)return this.containerBox.x;if(e>n.endIndex+1){const o=this.charBoxes[this.charBoxes.length-1];return o?o.x+o.width:this.containerBox.x}const r=this.charBoxes[e-1];return r?r.x+r.width:this.containerBox.x}getGapPositions(e){const t=this.lines[e];if(!t)return[];const i=[{index:t.startIndex,x:this.containerBox.x}];for(let n=t.startIndex;n<=t.endIndex;n++){const r=this.charBoxes[n];r&&i.push({index:n+1,x:r.x+r.width})}return i}closestIndexInLine(e,t){const i=this.getGapPositions(e);if(i.length===0)return 0;let n=i[0],r=Math.abs(t-n.x);for(let o=1;o<i.length;o++){const a=i[o];if(!a)continue;const l=Math.abs(t-a.x);l<r&&(n=a,r=l)}return n.index}}const Ep={width:4,height:24,heightMode:"lineHeight",color:"#00f5ff",glowColor:"#00f5ff",glowIntensity:.9,blinkSpeed:1.05,blinkEnabled:!0,billboard:!0,depthTest:!1,renderOrder:100,mode:"plane"},Lp={fillColor:"rgba(0,120,255,0.30)",blendMode:"normal",animate:!1,strategy:"perChar"},Tp={charBoxColor:"rgba(64,160,255,0.55)",charBoxFill:"rgba(64,160,255,0.10)",charIndexColor:"rgba(255,255,255,0.85)",rowHoverColor:"rgba(200,200,200,0.10)",rowBoundaryColor:"rgba(255,255,255,0.22)",gapColor:"rgba(255,153,0,0.7)",baselineColor:"rgba(255,51,51,0.55)",containerColor:"rgba(255,255,255,0.30)"},Ip={showCharBoxes:!0,showLineIndices:!0,showCharIndices:!0,showChars:!0};class Mp{constructor(e){E(this,"renderer");E(this,"cursorStyle");E(this,"selectionStyle");E(this,"debugStyle");E(this,"debugVisibility");E(this,"enableSelection");E(this,"enableDebug");E(this,"debugYAxisUp");E(this,"visible",!0);E(this,"cursorState",null);E(this,"selectionBoxes",[]);E(this,"debugData",null);E(this,"viewTransform",{x:0,y:0,scaleX:1,scaleY:1,rotation:0});this.renderer=e.renderer,this.cursorStyle={...Ep,...e.cursorStyle},this.selectionStyle={...Lp,...e.selectionStyle},this.debugStyle={...Tp,...e.debugStyle},this.debugVisibility={...Ip,...e.debugVisibility},this.enableSelection=e.enableSelection??!0,this.enableDebug=e.enableDebug??!1,this.debugYAxisUp=e.debugYAxisUp??!1}updateCursor(e,t){this.cursorState={position:e,lineHeight:t}}updateSelection(e){this.selectionBoxes=e.map(t=>({...t}))}updateDebugInfo(e){const t={containerBox:{...e.containerBox},charBoxes:e.charBoxes.map(i=>({...i})),lines:e.lines.map(i=>({...i}))};e.chars&&(t.chars=[...e.chars]),e.gapPositions&&(t.gapPositions=[...e.gapPositions]),e.hoverLineIndex!==void 0&&(t.hoverLineIndex=e.hoverLineIndex),this.debugData=t}setCursorStyle(e){this.cursorStyle={...this.cursorStyle,...e}}setSelectionStyle(e){this.selectionStyle={...this.selectionStyle,...e}}setDebugMode(e){this.enableDebug=e}setDebugVisibility(e){this.debugVisibility={...this.debugVisibility,...e}}setViewTransform(e){this.viewTransform={...this.viewTransform,...e}}show(){this.visible=!0}hide(){this.visible=!1}toggle(){this.visible=!this.visible}render(){if(this.renderer.beginFrame(),!this.visible){this.renderer.endFrame();return}this.renderer.setTransform({x:this.viewTransform.x??0,y:this.viewTransform.y??0,scaleX:this.viewTransform.scaleX??1,scaleY:this.viewTransform.scaleY??1,rotation:this.viewTransform.rotation??0}),this.enableDebug&&this.debugData&&this.drawDebug(this.debugData),this.enableSelection&&this.selectionBoxes.length>0&&this.drawSelection(this.selectionBoxes),this.cursorState&&this.drawCursor(this.cursorState.position,this.cursorState.lineHeight),this.renderer.resetTransform(),this.renderer.endFrame()}dispose(){this.renderer.destroy(),this.selectionBoxes=[],this.cursorState=null,this.debugData=null}drawCursor(e,t){const i=Math.max(.2,this.cursorStyle.blinkSpeed)*1e3;if(!(!this.cursorStyle.blinkEnabled||Date.now()%i<i/2))return;const r=this.cursorStyle.heightMode==="fixed"?this.cursorStyle.height:Math.max(this.cursorStyle.height,t*.8);this.cursorStyle.glowColor&&(this.cursorStyle.glowIntensity??0)>0&&this.renderer.drawLine({x1:e.x,y1:e.y-r/2,x2:e.x,y2:e.y+r/2,color:this.cursorStyle.glowColor,width:this.cursorStyle.width+2,opacity:Math.min(1,this.cursorStyle.glowIntensity??0)}),this.renderer.drawLine({x1:e.x,y1:e.y-r/2,x2:e.x,y2:e.y+r/2,color:this.cursorStyle.color,width:this.cursorStyle.width,opacity:1})}drawSelection(e){if(this.selectionStyle.strategy==="merged"){this.mergeBoxes(e).forEach(t=>this.drawSelectionQuad(t));return}e.forEach(t=>this.drawSelectionQuad(t))}drawSelectionQuad(e){const t={x:e.x,y:e.y,width:e.width,height:e.height,fillColor:this.selectionStyle.fillColor,blendMode:this.selectionStyle.blendMode==="additive"?"lighter":this.selectionStyle.blendMode==="multiply"?"multiply":"source-over"};this.renderer.drawQuad({...t,...this.selectionStyle.borderColor?{borderColor:this.selectionStyle.borderColor}:{},...this.selectionStyle.borderWidth!==void 0?{borderWidth:this.selectionStyle.borderWidth}:{},...this.selectionStyle.cornerRadius!==void 0?{cornerRadius:this.selectionStyle.cornerRadius}:{}})}drawDebug(e){var i;this.renderer.drawBox({box:{x:e.containerBox.x,y:e.containerBox.y+e.containerBox.height/2,width:e.containerBox.width,height:e.containerBox.height},color:this.debugStyle.containerColor,opacity:1,lineWidth:1});const t=e.containerBox.x+e.containerBox.width+60;e.lines.forEach((n,r)=>{const o=this.debugYAxisUp?n.y+n.height/2:n.y-n.height/2,a=this.debugYAxisUp?n.y-n.height/2:n.y+n.height/2;e.hoverLineIndex===r&&this.renderer.drawQuad({x:0,y:n.y,width:t,height:n.height,fillColor:this.debugStyle.rowHoverColor}),this.renderer.drawLine({x1:0,y1:o,x2:t,y2:o,color:this.debugStyle.rowBoundaryColor,dashed:[5,5]}),this.renderer.drawLine({x1:0,y1:a,x2:t,y2:a,color:this.debugStyle.rowBoundaryColor,dashed:[5,5]}),this.debugVisibility.showLineIndices&&this.renderer.drawText({text:`L${r}`,x:8,y:o+(this.debugYAxisUp?-2:2),color:"rgba(255,255,255,0.65)",font:"12px monospace"})}),e.charBoxes.forEach((n,r)=>{var c;const o=this.debugYAxisUp?n.y+n.height/2:n.y-n.height/2,a=this.debugYAxisUp?-2:2,l=this.debugYAxisUp?-Math.max(8,n.height*.2):Math.max(8,n.height*.2);if(this.debugVisibility.showCharBoxes&&this.renderer.drawQuad({x:n.x,y:n.y,width:n.width,height:n.height,fillColor:this.debugStyle.charBoxFill,borderColor:this.debugStyle.charBoxColor,borderWidth:1}),this.debugVisibility.showCharIndices&&this.renderer.drawText({text:String(r),x:n.x+2,y:o+a,color:this.debugStyle.charIndexColor,font:"10px monospace"}),this.debugVisibility.showChars){const h=(c=e.chars)==null?void 0:c[r];if(!h)return;this.renderer.drawText({text:h,x:n.x+2,y:o+l,color:"rgba(255,255,255,0.95)",font:`${Math.max(12,Math.round(n.height*.6))}px monospace`})}}),(i=e.gapPositions)==null||i.forEach(n=>{this.renderer.drawLine({x1:n.x,y1:n.y-n.height/2,x2:n.x,y2:n.y+n.height/2,color:this.debugStyle.gapColor,opacity:n.strong?.9:.55,width:1})})}mergeBoxes(e){if(e.length===0)return[];const t=[...e].sort((n,r)=>n.y===r.y?n.x-r.x:n.y-r.y),i=[];for(const n of t){const r=i[i.length-1];if(!r){i.push({...n});continue}const o=Math.abs(r.y-n.y)<=1,a=n.x<=r.x+r.width+1,l=Math.abs(r.height-n.height)<=1;o&&a&&l?r.width=Math.max(r.x+r.width,n.x+n.width)-r.x:i.push({...n})}return i}}function mn(s){const e=s.match(/rgba?\(([^)]+)\)/i);if(e){const n=(e[1]??"").split(",").map(c=>Number(c.trim())),[r=255,o=255,a=255,l=1]=n;return{color:new L.Color(r/255,o/255,a/255),alpha:Number.isFinite(l)?l:1}}const t=new L.Color;return t.setStyle(s),{color:t,alpha:1}}class Dp{constructor(e){E(this,"scene");E(this,"camera");E(this,"frameGroup",new L.Group);E(this,"currentTransform",{x:0,y:0,scaleX:1,scaleY:1,rotation:0});E(this,"canvas",null);this.scene=e.scene,this.camera=e.camera,this.scene.add(this.frameGroup)}initialize(e){this.canvas=e}destroy(){this.clearFrame(),this.scene.remove(this.frameGroup)}beginFrame(){this.clearFrame()}endFrame(){this.camera}drawQuad(e){const t=this.currentTransform.scaleX??1,i=this.currentTransform.scaleY??1,n=this.transformPoint(e.x+e.width/2,e.y),r=this.createQuadMesh(n.x-e.width*t/2,n.y,Math.abs(e.width*t),Math.abs(e.height*i),e.fillColor,e.opacity);if(r&&this.frameGroup.add(r),e.borderColor){const o=this.createRectBorder(n.x-e.width*t/2,n.y,Math.abs(e.width*t),Math.abs(e.height*i),e.borderColor,e.borderWidth??1,e.opacity??1);this.frameGroup.add(o)}}drawLine(e){const t=this.transformPoint(e.x1,e.y1),i=this.transformPoint(e.x2,e.y2),n=mn(e.color),r=(e.opacity??1)*n.alpha;if(e.dashed&&e.dashed.length>0){const h=[new L.Vector3(t.x,t.y,0),new L.Vector3(i.x,i.y,0)],p=new L.BufferGeometry().setFromPoints(h),m=new L.LineDashedMaterial({color:n.color,linewidth:e.width??1,transparent:r<1,opacity:r,dashSize:e.dashed[0]??4,gapSize:e.dashed[1]??2,depthTest:!1}),g=new L.Line(p,m);g.computeLineDistances(),g.renderOrder=e.renderOrder??1,this.frameGroup.add(g);return}const o=new tp.LineGeometry;o.setPositions([t.x,t.y,0,i.x,i.y,0]);const a=new ip.LineMaterial({color:n.color,linewidth:e.width??1,worldUnits:!1,transparent:r<1,opacity:r,depthTest:!1}),l=this.getResolution();a.resolution.set(l.x,l.y);const c=new ep.Line2(o,a);c.computeLineDistances(),c.renderOrder=e.renderOrder??1,this.frameGroup.add(c)}drawText(e){var G;const t=e.font??"20px monospace",i=Number(((G=t.match(/(\d+(?:\.\d+)?)px/))==null?void 0:G[1])??20),n=4,r=document.createElement("canvas");let o=r.getContext("2d");if(!o)return;o.font=t;const l=Math.max(1,Math.ceil(o.measureText(e.text).width))+n*2,c=Math.max(1,Math.ceil(i*1.4));if(r.width=l,r.height=c,o=r.getContext("2d"),!o)return;o.clearRect(0,0,r.width,r.height),o.font=t;const h=e.align??"left",p=e.baseline??"top";o.textAlign=h,o.textBaseline=p;const m=mn(e.color);o.fillStyle=`rgba(${Math.round(m.color.r*255)}, ${Math.round(m.color.g*255)}, ${Math.round(m.color.b*255)}, ${e.opacity??m.alpha})`;const g=h==="center"?r.width/2:h==="right"?r.width-n:n,f=p==="middle"?r.height/2:p==="bottom"?r.height-n:n;o.fillText(e.text,g,f);const w=this.isYAxisUp(),v=new L.CanvasTexture(r);v.flipY=w,v.needsUpdate=!0;const x=Math.abs(this.currentTransform.scaleX??1),S=Math.abs(this.currentTransform.scaleY??1),P=Math.max(1,r.width*x),A=Math.max(1,r.height*S),_=new L.PlaneGeometry(P,A),C=new L.MeshBasicMaterial({map:v,transparent:!0,depthTest:!1,depthWrite:!1,side:L.DoubleSide}),O=new L.Mesh(_,C),B=this.transformPoint(e.x,e.y),I=h==="center"?0:h==="right"?-P/2:P/2,N=p==="middle"?0:p==="bottom"?w?A/2:-A/2:w?-A/2:A/2;O.position.set(B.x+I,B.y+N,.2),O.renderOrder=10,this.frameGroup.add(O)}drawBox(e){const t=this.currentTransform.scaleX??1,i=this.currentTransform.scaleY??1,n=this.transformPoint(e.box.x+e.box.width/2,e.box.y),r=this.createRectBorder(n.x-e.box.width*t/2,n.y,Math.abs(e.box.width*t),Math.abs(e.box.height*i),e.color,e.lineWidth??1,e.opacity??1);r.renderOrder=e.renderOrder??2,this.frameGroup.add(r)}setTransform(e){this.currentTransform={x:e.x??0,y:e.y??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,rotation:e.rotation??0}}resetTransform(){this.currentTransform={x:0,y:0,scaleX:1,scaleY:1,rotation:0}}transformPoint(e,t){const i=this.currentTransform.scaleX??1,n=this.currentTransform.scaleY??1,r=(this.currentTransform.x??0)+e*i,o=(this.currentTransform.y??0)+t*n,a=this.currentTransform.rotation??0;if(a===0)return{x:r,y:o};const l=Math.cos(a),c=Math.sin(a);return{x:r*l-o*c,y:r*c+o*l}}isYAxisUp(){return this.camera instanceof L.OrthographicCamera?this.camera.top>=this.camera.bottom:!0}createLineQuad(e,t,i,n,r){const o=t.x-e.x,a=t.y-e.y,l=Math.max(.001,Math.hypot(o,a)),c=Math.atan2(a,o),h=new L.PlaneGeometry(l,i),p=new L.MeshBasicMaterial({color:n,transparent:r<1,opacity:r,side:L.DoubleSide,depthTest:!1}),m=new L.Mesh(h,p);return m.position.set((e.x+t.x)/2,(e.y+t.y)/2,0),m.rotation.z=c,m}createQuadMesh(e,t,i,n,r,o=1){if(!r)return null;const a=new L.PlaneGeometry(i,n),l=mn(r),c=new L.MeshBasicMaterial({color:l.color,transparent:o*l.alpha<1,opacity:o*l.alpha,side:L.DoubleSide,depthTest:!1}),h=new L.Mesh(a,c);return h.position.set(e+i/2,t,0),h.renderOrder=1,h}createRectBorder(e,t,i,n,r,o,a){const l=mn(r),c=i/2,h=n/2,p=e+c,m=t,g=[new L.Vector3(p-c,m-h,0),new L.Vector3(p+c,m-h,0),new L.Vector3(p+c,m+h,0),new L.Vector3(p-c,m+h,0)],f=new L.BufferGeometry().setFromPoints(g),w=new L.LineBasicMaterial({color:l.color,transparent:a*l.alpha<1,opacity:a*l.alpha,linewidth:o,depthTest:!1});return new L.LineLoop(f,w)}clearFrame(){for(;this.frameGroup.children.length>0;){const e=this.frameGroup.children.pop();e&&this.disposeObject(e)}}disposeObject(e){if("geometry"in e&&e.geometry instanceof L.BufferGeometry&&e.geometry.dispose(),"material"in e){const t=e.material;Array.isArray(t)?t.forEach(i=>this.disposeMaterial(i)):t&&this.disposeMaterial(t)}"children"in e&&e.children.length>0&&[...e.children].forEach(t=>this.disposeObject(t)),e.removeFromParent()}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),e.dispose()}getResolution(){return this.canvas?{x:this.canvas.width||1,y:this.canvas.height||1}:typeof window<"u"?{x:window.innerWidth||1,y:window.innerHeight||1}:{x:1,y:1}}}function Op(s){return s===D.MTextLineAlignment.TOP?"superscript":s===D.MTextLineAlignment.BOTTOM?"subscript":"normal"}function Bp(s){return s==="superscript"?D.MTextLineAlignment.TOP:s==="subscript"?D.MTextLineAlignment.BOTTOM:D.MTextLineAlignment.MIDDLE}function Ra(s){return{...s,align:Bp(s.script)}}function hi(s){return{underline:s.underline,overline:s.overline,strikeThrough:s.strikeThrough,script:Op(s.align),aci:s.aci,rgb:s.rgb?[...s.rgb]:null,align:s.align,fontFace:{...s.fontFace},capHeight:{...s.capHeight},widthFactor:{...s.widthFactor},charTrackingFactor:{...s.charTrackingFactor},oblique:s.oblique,paragraph:{indent:s.paragraph.indent,left:s.paragraph.left,right:s.paragraph.right,align:s.paragraph.align,tabs:[...s.paragraph.tabs]}}}function pe(s){return{underline:s.underline,overline:s.overline,strikeThrough:s.strikeThrough,script:s.script,aci:s.aci,rgb:s.rgb?[...s.rgb]:null,align:s.align,fontFace:{...s.fontFace},capHeight:{...s.capHeight},widthFactor:{...s.widthFactor},charTrackingFactor:{...s.charTrackingFactor},oblique:s.oblique,paragraph:{indent:s.paragraph.indent,left:s.paragraph.left,right:s.paragraph.right,align:s.paragraph.align,tabs:[...s.paragraph.tabs]}}}function pi(s){return s.type==="char"||s.type==="stack"||s.type==="paragraphBreak"||s.type==="columnBreak"||s.type==="wrapAtDimLine"}function jp(s,e){return s.underline===e.underline&&s.overline===e.overline&&s.strikeThrough===e.strikeThrough&&s.script===e.script&&s.aci===e.aci&&JSON.stringify(s.rgb)===JSON.stringify(e.rgb)&&s.align===e.align&&s.fontFace.family===e.fontFace.family&&s.fontFace.style===e.fontFace.style&&s.fontFace.weight===e.fontFace.weight&&s.capHeight.value===e.capHeight.value&&s.capHeight.isRelative===e.capHeight.isRelative&&s.widthFactor.value===e.widthFactor.value&&s.widthFactor.isRelative===e.widthFactor.isRelative&&s.charTrackingFactor.value===e.charTrackingFactor.value&&s.charTrackingFactor.isRelative===e.charTrackingFactor.isRelative&&s.oblique===e.oblique&&s.paragraph.indent===e.paragraph.indent&&s.paragraph.left===e.paragraph.left&&s.paragraph.right===e.paragraph.right&&s.paragraph.align===e.paragraph.align&&JSON.stringify(s.paragraph.tabs)===JSON.stringify(e.paragraph.tabs)}function Va(s,e){const t=s??hi(new D.MTextContext),i=Ra(t),n=Ra(e);if(jp(i,n))return"";let r="";if(i.underline!==n.underline&&(r+=n.underline?"\\L":"\\l"),i.overline!==n.overline&&(r+=n.overline?"\\O":"\\o"),i.strikeThrough!==n.strikeThrough&&(r+=n.strikeThrough?"\\K":"\\k"),i.align!==n.align&&(r+=`\\A${n.align};`),(i.aci!==n.aci||JSON.stringify(i.rgb)!==JSON.stringify(n.rgb))&&(n.rgb?r+=`\\c${D.rgb2int(n.rgb)};`:r+=`\\C${n.aci??256};`),i.fontFace.family!==n.fontFace.family||i.fontFace.style!==n.fontFace.style||i.fontFace.weight!==n.fontFace.weight){const o=n.fontFace.weight>=700?1:0,a=n.fontFace.style==="Italic"?1:0;r+=`\\f${n.fontFace.family}|b${o}|i${a};`}return(i.capHeight.value!==n.capHeight.value||i.capHeight.isRelative!==n.capHeight.isRelative)&&(r+=`\\H${or(n.capHeight)};`),(i.widthFactor.value!==n.widthFactor.value||i.widthFactor.isRelative!==n.widthFactor.isRelative)&&(r+=`\\W${or(n.widthFactor)};`),(i.charTrackingFactor.value!==n.charTrackingFactor.value||i.charTrackingFactor.isRelative!==n.charTrackingFactor.isRelative)&&(r+=`\\T${or(n.charTrackingFactor)};`),i.oblique!==n.oblique&&(r+=`\\Q${mi(n.oblique)};`),JSON.stringify(i.paragraph)!==JSON.stringify(n.paragraph)&&(r+=`\\p${Fp(n.paragraph)};`),r}function or(s){return`${mi(s.value)}${s.isRelative?"x":""}`}function mi(s){return Number.isInteger(s),s.toString()}function Fp(s){const e=[`i${mi(s.indent)}`,`l${mi(s.left)}`,`r${mi(s.right)}`];return s.align!==D.MTextParagraphAlignment.DEFAULT&&e.push(`q${zp(s.align)}`),s.tabs.length>0&&e.push(`t${s.tabs.map(t=>String(t)).join(",")}`),e.join(",")}function zp(s){switch(s){case D.MTextParagraphAlignment.LEFT:return"l";case D.MTextParagraphAlignment.RIGHT:return"r";case D.MTextParagraphAlignment.CENTER:return"c";case D.MTextParagraphAlignment.JUSTIFIED:return"j";case D.MTextParagraphAlignment.DISTRIBUTED:return"d";default:return"x"}}function Ga(s,e,t={}){const i=new D.MTextParser(s,e,{...t,yieldPropertyCommands:!1}),n=[];for(const r of i.parse()){const o=hi(r.ctx);switch(r.type){case D.TokenType.WORD:{const a=r.data;for(const l of a)n.push({type:"char",value:l,style:pe(o)});break}case D.TokenType.SPACE:n.push({type:"char",value:" ",style:pe(o)});break;case D.TokenType.NBSP:n.push({type:"char",value:" ",style:pe(o)});break;case D.TokenType.TABULATOR:n.push({type:"char",value:" ",style:pe(o)});break;case D.TokenType.STACK:{const[a,l,c]=r.data,h=pe(o);c==="^"&&(a.length===0&&l.length>0?h.script="subscript":a.length>0&&l.length===0?h.script="superscript":h.script="normal"),n.push({type:"stack",numerator:a,denominator:l,divider:c,style:h});break}case D.TokenType.NEW_PARAGRAPH:n.push({type:"paragraphBreak",style:pe(o)});break;case D.TokenType.NEW_COLUMN:n.push({type:"columnBreak",style:pe(o)});break;case D.TokenType.WRAP_AT_DIMLINE:n.push({type:"wrapAtDimLine",style:pe(o)});break}}return{nodes:n}}function Np(s){const e=hi(new D.MTextContext);let t="",i=0;for(;i<s.nodes.length;){const n=s.nodes[i];if(!n)break;if(!pi(n)){t+=Wa(n),i+=1;continue}const r=n.style;let o="",a=i;for(;a<s.nodes.length;){const l=s.nodes[a];if(!l||!pi(l)||!Ha(r,l.style))break;o+=Wa(l),a+=1}Ha(r,e)?t+=o:t+=`{${Va(null,r)}${o}}`,i=a}return t}function yn(s,e,t){if(t<=0)return s;const i=gn(e,0,s.nodes.length),n=gn(t,0,s.nodes.length-i);return s.nodes.splice(i,n),s}function Rp(s,e,t,i,n){const r=gn(e,0,s.nodes.length),o=gn(t,0,s.nodes.length-r),a=n??Ka(s,r)??hi(new D.MTextContext),l=Kp(i,a);return s.nodes.splice(r,o,...l),s}function Ka(s,e){for(let t=e-1;t>=0;t--){const i=s.nodes[t];if(i&&pi(i))return pe(i.style)}for(let t=e;t<s.nodes.length;t++){const i=s.nodes[t];if(i&&pi(i))return pe(i.style)}}function Vp(s){return s===" "?"\\~":s===" "?"^I":s==="\\"?"\\\\":s==="{"?"\\{":s==="}"?"\\}":s==="^"?"\\U+005E":s==="%"?"\\U+0025":s===`
3
+ `?"\\P":s==="\r"?"":s}function Ua(s){return s.replace(/[\\;/#^]/g,"\\$&")}function Ha(s,e){return Va(s,e)===""}function Wa(s){switch(s.type){case"char":return Vp(s.value);case"stack":return Gp(s.numerator,s.denominator,s.divider);case"paragraphBreak":return"\\P";case"columnBreak":return"\\N";case"wrapAtDimLine":return"\\X"}}function Gp(s,e,t){const i=Ua(s),n=Ua(e);if(t==="^"){if(i.length===0&&n.length>0)return`\\S^ ${n};`;if(i.length>0&&n.length===0)return`\\S${i}^ ;`;if(i.length===0&&n.length===0)return"\\S^ ;"}return`\\S${i}${t}${n};`}function Kp(s,e){const t=[];for(const i of s){if(i===`
4
+ `){t.push({type:"paragraphBreak",style:pe(e)});continue}t.push({type:"char",value:i,style:pe(e)})}return t}function gn(s,e,t){return Math.max(e,Math.min(t,s))}class me{constructor(e={nodes:[]}){E(this,"_ast");E(this,"_cursor");E(this,"_selection",null);this._ast=typeof e=="string"?Ga(e):me.cloneAst(e),this._cursor=this._ast.nodes.length}static fromMText(e,t){return new me(Ga(e,t))}get ast(){return this._ast}get length(){return this._ast.nodes.length}get cursor(){return this._cursor}set cursor(e){this._cursor=me.clamp(e,0,this.length),this._selection=null}get selection(){return this._selection?{...this._selection}:null}setSelection(e,t){const i=me.normalizeSelection(e,t,this.length);return this._selection=i.start===i.end?null:i,this._cursor=me.clamp(t,0,this.length),this}clearSelection(){return this._selection=null,this}moveCursor(e,t=!1){const i=me.clamp(this._cursor+e,0,this.length);if(t){const n=this._selection?this._selection.start:this._cursor;this.setSelection(n,i)}else this.cursor=i;return this}selectAll(){return this.setSelection(0,this.length),this}insertText(e,t){const{start:i,end:n}=this.getActiveRange();return Rp(this._ast,i,n-i,e,t),this._cursor=i+e.length,this._selection=null,this}deleteBackward(e=1){if(this.hasSelection()){const{start:i,end:n}=this.getActiveRange();return yn(this._ast,i,n-i),this._cursor=i,this._selection=null,this}if(e<=0||this._cursor<=0)return this;const t=Math.min(e,this._cursor);return yn(this._ast,this._cursor-t,t),this._cursor-=t,this}deleteForward(e=1){if(this.hasSelection()){const{start:t,end:i}=this.getActiveRange();return yn(this._ast,t,i-t),this._cursor=t,this._selection=null,this}return e<=0||this._cursor>=this.length?this:(yn(this._ast,this._cursor,e),this)}replaceSelection(e,t){return this.insertText(e,t)}toMText(){return Np(this._ast)}transaction(e){const t={ast:me.cloneAst(this._ast),cursor:this._cursor,selection:this._selection?{...this._selection}:null};try{e(this)}catch(i){throw this._ast=t.ast,this._cursor=t.cursor,this._selection=t.selection,i}return this}hasSelection(){return!!(this._selection&&this._selection.start!==this._selection.end)}getActiveRange(){return this._selection?{...this._selection}:{start:this._cursor,end:this._cursor}}getReferenceStyle(e){return Ka(this._ast,e)??hi(new D.MTextContext)}static cloneAst(e){return{nodes:e.nodes.map(t=>t.type==="char"?{...t,style:pe(t.style)}:t.type==="stack"?{...t,style:pe(t.style)}:{...t,style:pe(t.style)})}}static normalizeSelection(e,t,i){const n=me.clamp(e,0,i),r=me.clamp(t,0,i);return n<=r?{start:n,end:r}:{start:r,end:n}}static clamp(e,t,i){return Math.max(t,Math.min(i,e))}}class ar{constructor(e){E(this,"document");E(this,"selectionAnchor",null);this.document=e}get anchor(){return this.selectionAnchor}execute(e){switch(e.type){case"setCursor":this.document.cursor=e.index,this.selectionAnchor=null;break;case"setSelection":this.document.setSelection(e.start,e.end),this.selectionAnchor=e.start;break;case"clearSelection":this.document.clearSelection(),this.selectionAnchor=null;break;case"moveLeft":this.moveCursorTo(this.document.cursor-1,e.extend??!1);break;case"moveRight":this.moveCursorTo(this.document.cursor+1,e.extend??!1);break;case"moveToStart":this.moveCursorTo(0,e.extend??!1);break;case"moveToEnd":this.moveCursorTo(this.document.length,e.extend??!1);break;case"selectAll":this.document.selectAll(),this.selectionAnchor=0;break;case"insertText":this.document.insertText(e.text,e.style),this.selectionAnchor=null;break;case"replaceSelection":this.document.replaceSelection(e.text,e.style),this.selectionAnchor=null;break;case"backspace":this.document.deleteBackward(e.count??1),this.selectionAnchor=null;break;case"delete":this.document.deleteForward(e.count??1),this.selectionAnchor=null;break}return this}handleKeyEvent(e){const t=!!(e.metaKey||e.ctrlKey);return t&&!e.altKey&&e.key.toLowerCase()==="a"?(this.execute({type:"selectAll"}),!0):e.key==="ArrowLeft"?(this.execute({type:"moveLeft",extend:!!e.shiftKey}),!0):e.key==="ArrowRight"?(this.execute({type:"moveRight",extend:!!e.shiftKey}),!0):e.key==="Home"?(this.execute({type:"moveToStart",extend:!!e.shiftKey}),!0):e.key==="End"?(this.execute({type:"moveToEnd",extend:!!e.shiftKey}),!0):e.key==="Backspace"?(this.execute({type:"backspace"}),!0):e.key==="Delete"?(this.execute({type:"delete"}),!0):e.key==="Enter"?(this.execute({type:"insertText",text:`
5
+ `}),!0):e.key==="Tab"?(this.execute({type:"insertText",text:" "}),!0):!t&&!e.altKey&&e.key.length===1?(this.execute({type:"insertText",text:e.key}),!0):!1}moveCursorTo(e,t){var n;const i=Math.max(0,Math.min(e,this.document.length));if(t){this.selectionAnchor===null&&(this.selectionAnchor=((n=this.document.selection)==null?void 0:n.start)??this.document.cursor),this.document.setSelection(this.selectionAnchor,i);return}this.document.cursor=i,this.selectionAnchor=null}}const Up={bold:'<svg viewBox="0 0 24 24"><path d="M7.8 19c-.3 0-.5 0-.6-.2l-.2-.5V5.7c0-.2 0-.4.2-.5l.6-.2h5c1.5 0 2.7.3 3.5 1 .7.6 1.1 1.4 1.1 2.5a3 3 0 0 1-.6 1.9c-.4.6-1 1-1.6 1.2.4.1.9.3 1.3.6s.8.7 1 1.2c.4.4.5 1 .5 1.6 0 1.3-.4 2.3-1.3 3-.8.7-2.1 1-3.8 1H7.8Zm5-8.3c.6 0 1.2-.1 1.6-.5.4-.3.6-.7.6-1.3 0-1.1-.8-1.7-2.3-1.7H9.3v3.5h3.4Zm.5 6c.7 0 1.3-.1 1.7-.4.4-.4.6-.9.6-1.5s-.2-1-.7-1.4c-.4-.3-1-.4-2-.4H9.4v3.8h4Z" fill-rule="evenodd"></path></svg>',italic:'<svg viewBox="0 0 24 24"><path d="m16.7 4.7-.1.9h-.3c-.6 0-1 0-1.4.3-.3.3-.4.6-.5 1.1l-2.1 9.8v.6c0 .5.4.8 1.4.8h.2l-.2.8H8l.2-.8h.2c1.1 0 1.8-.5 2-1.5l2-9.8.1-.5c0-.6-.4-.8-1.4-.8h-.3l.2-.9h5.8Z" fill-rule="evenodd"></path></svg>',underline:'<svg viewBox="0 0 24 24"><path d="M16 5c.6 0 1 .4 1 1v5.5a4 4 0 0 1-.4 1.8l-1 1.4a5.3 5.3 0 0 1-5.5 1 5 5 0 0 1-1.6-1c-.5-.4-.8-.9-1.1-1.4a4 4 0 0 1-.4-1.8V6c0-.6.4-1 1-1s1 .4 1 1v5.5c0 .3 0 .6.2 1l.6.7a3.3 3.3 0 0 0 2.2.8 3.4 3.4 0 0 0 2.2-.8c.3-.2.4-.5.6-.8l.2-.9V6c0-.6.4-1 1-1ZM8 17h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 0 1 0-2Z" fill-rule="evenodd"></path></svg>',overline:'<svg viewBox="0 0 24 24"><path d="M5 4h14v1.5H5V4zm7 3.5c3.04 0 5.5 2.46 5.5 5.5v4.5h-2.25v-4.5c0-1.79-1.46-3.25-3.25-3.25S8.75 11.21 8.75 13v4.5H6.5V13c0-3.04 2.46-5.5 5.5-5.5z"></path></svg>',strike:'<svg viewBox="0 0 24 24"><g fill-rule="evenodd"><path d="M15.6 8.5c-.5-.7-1-1.1-1.3-1.3-.6-.4-1.3-.6-2-.6-2.7 0-2.8 1.7-2.8 2.1 0 1.6 1.8 2 3.2 2.3 4.4.9 4.6 2.8 4.6 3.9 0 1.4-.7 4.1-5 4.1A6.2 6.2 0 0 1 7 16.4l1.5-1.1c.4.6 1.6 2 3.7 2 1.6 0 2.5-.4 3-1.2.4-.8.3-2-.8-2.6-.7-.4-1.6-.7-2.9-1-1-.2-3.9-.8-3.9-3.6C7.6 6 10.3 5 12.4 5c2.9 0 4.2 1.6 4.7 2.4l-1.5 1.1Z"></path><path d="M5 11h14a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Z" fill-rule="nonzero"></path></g></svg>',superscript:'<svg viewBox="0 0 24 24"><path d="M15 9.4 10.4 14l4.6 4.6-1.4 1.4L9 15.4 4.4 20 3 18.6 7.6 14 3 9.4 4.4 8 9 12.6 13.6 8 15 9.4Zm5.9 1.6h-5v-1l1-.8 1.7-1.6c.3-.5.5-.9.5-1.3 0-.3 0-.5-.2-.7-.2-.2-.5-.3-.9-.3l-.8.2-.7.4-.4-1.2c.2-.2.5-.4 1-.5.3-.2.8-.2 1.2-.2.8 0 1.4.2 1.8.6.4.4.6 1 .6 1.6 0 .5-.2 1-.5 1.5l-1.3 1.4-.6.5h2.6V11Z" fill-rule="nonzero"></path></svg>',subscript:'<svg viewBox="0 0 24 24"><path d="m10.4 10 4.6 4.6-1.4 1.4L9 11.4 4.4 16 3 14.6 7.6 10 3 5.4 4.4 4 9 8.6 13.6 4 15 5.4 10.4 10ZM21 19h-5v-1l1-.8 1.7-1.6c.3-.4.5-.8.5-1.2 0-.3 0-.6-.2-.7-.2-.2-.5-.3-.9-.3a2 2 0 0 0-.8.2l-.7.3-.4-1.1 1-.6 1.2-.2c.8 0 1.4.3 1.8.7.4.4.6.9.6 1.5s-.2 1.1-.5 1.6a8 8 0 0 1-1.3 1.3l-.6.6h2.6V19Z" fill-rule="nonzero"></path></svg>',stack:'<svg viewBox="0 0 24 24"><path d="M12.4065 5.44832C12.8151 5.44832 13.1994 5.56542 13.5595 5.7996C13.9265 6.0267 14.2208 6.36024 14.4424 6.80022C14.664 7.23312 14.7748 7.74407 14.7748 8.33309C14.7748 8.9292 14.664 9.44725 14.4424 9.88724C14.2208 10.3201 13.9265 10.6501 13.5595 10.8772C13.1994 11.1043 12.8151 11.2179 12.4065 11.2179C12.0464 11.2179 11.7037 11.1291 11.3782 10.9517C11.0527 10.7743 10.7931 10.5082 10.5992 10.1534C10.5715 10.4585 10.5507 10.7743 10.5368 11.1008H9.75781V3H10.6407V6.4383C10.8415 6.11185 11.0977 5.86702 11.4094 5.7038C11.721 5.53348 12.0534 5.44832 12.4065 5.44832ZM12.2923 10.3663C12.7631 10.3663 13.1405 10.1888 13.4245 9.83402C13.7084 9.47919 13.8503 8.97888 13.8503 8.33309C13.8503 7.69439 13.7084 7.19763 13.4245 6.8428C13.1405 6.48797 12.7631 6.31056 12.2923 6.31056C11.8422 6.31056 11.4544 6.47378 11.1289 6.80022C10.8034 7.12667 10.6407 7.63762 10.6407 8.33309C10.6407 8.80856 10.7203 9.19887 10.8796 9.50402C11.0389 9.80918 11.2432 10.0292 11.4925 10.164C11.7417 10.2988 12.0083 10.3663 12.2923 10.3663Z"></path><path d="M12.0949 14.9531C12.7043 14.9531 13.2029 15.1447 13.5906 15.5279C13.9784 15.9041 14.1723 16.4434 14.1723 17.146V20.6056H13.3933C13.3725 20.2436 13.3587 20.0094 13.3517 19.903C13.1856 20.1727 12.9605 20.3785 12.6766 20.5204C12.3996 20.6552 12.0811 20.7227 11.721 20.7227C11.3747 20.7227 11.0493 20.6588 10.7446 20.531C10.4468 20.3962 10.2079 20.2011 10.0279 19.9456C9.84783 19.683 9.75781 19.3708 9.75781 19.0088C9.75781 18.4624 9.97248 18.033 10.4018 17.7208C10.8381 17.4014 11.399 17.2418 12.0845 17.2418C12.4723 17.2418 12.8739 17.295 13.2894 17.4014V17.3056C13.2894 16.7876 13.1856 16.4044 12.9778 16.156C12.777 15.9005 12.4688 15.7728 12.0534 15.7728C11.721 15.7728 11.444 15.8437 11.2224 15.9857C11.0008 16.1276 10.8138 16.337 10.6615 16.6137L9.98633 16.2199C10.1525 15.8367 10.4226 15.5315 10.7965 15.3044C11.1774 15.0702 11.6102 14.9531 12.0949 14.9531ZM13.2894 18.1572C12.8532 18.0437 12.455 17.9869 12.0949 17.9869C11.6448 17.9869 11.2951 18.0756 11.0458 18.253C10.8034 18.4305 10.6823 18.6788 10.6823 18.9982C10.6823 19.2962 10.7861 19.5304 10.9939 19.7007C11.2016 19.864 11.4717 19.9456 11.8041 19.9456C12.2126 19.9456 12.5623 19.8249 12.8532 19.5836C13.144 19.3353 13.2894 18.9946 13.2894 18.5617V18.1572Z""></path><rect x="6.02344" y="12.7119" width="11.9532" height="0.747077"></rect></svg>'},$a="mlightcad-mtext-toolbar-style",Ya=["Arial","Helvetica","Verdana","Tahoma","Trebuchet MS","Times New Roman","Georgia","Courier New","system-ui","sans-serif","serif","monospace"];function Hp(){if(document.getElementById($a))return;const s=document.createElement("style");s.id=$a,s.textContent=`
6
6
  .ml-mtext-toolbar {
7
7
  position: fixed;
8
8
  left: 0;
@@ -118,21 +118,24 @@
118
118
  .ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn:hover {
119
119
  background: #edf3ff;
120
120
  }
121
- `,document.head.appendChild(s)}function sr(s){return Math.max(0,Math.min(16777215,Math.round(s)))}function Va(s){return`#${(s===null?16777215:sr(s)).toString(16).padStart(6,"0")}`}function Dp(s){return/^#[0-9a-fA-F]{6}$/.test(s)?Number.parseInt(s.slice(1),16):16777215}function Op(s){return s.isRgb&&s.rgbValue!==null?Va(s.rgbValue):s.isAci&&s.aci!==null?Va(D.getColorByIndex(s.aci)):"#ffffff"}function Ga(s){const e=new D.MTextColor;return e.rgbValue=Dp(s),e}function Ka(s){const e=new D.MTextColor;return s.aci!==null&&Number.isFinite(s.aci)?(e.aci=s.aci,e):s.rgb!==null?(e.rgbValue=sr(s.rgb),e):(e.rgbValue=16777215,e)}function jp(s){const e=s.trim().toLowerCase();return/^#[0-9a-f]{6}$/.test(e)?e:/^[0-9a-f]{6}$/.test(e)?`#${e}`:null}function pt(s,e){const t=document.createElement("button");return t.type="button",t.className="ml-mtext-toolbar__btn",t.title=s,t.setAttribute("aria-label",s),t.setAttribute("aria-pressed","false"),t.innerHTML=Ip[e],t}function Bp(s){const e=s&&s.length>0?s:Ra,t=[],i=new Set;for(const n of e){const r=n.trim();!r||i.has(r)||(i.add(r),t.push(r))}return t.length>0?t:[...Ra]}class Fp{constructor(e){E(this,"anchorElement");E(this,"root");E(this,"controls");E(this,"onFormatChange");E(this,"onToggleStack");E(this,"onToggleSuperscript");E(this,"onToggleSubscript");E(this,"theme");E(this,"colorPicker");Mp(),this.anchorElement=e.anchorElement,this.onFormatChange=e.onFormatChange,this.onToggleStack=e.onToggleStack??(()=>{}),this.onToggleSuperscript=e.onToggleSuperscript??(()=>!1),this.onToggleSubscript=e.onToggleSubscript??(()=>!1),this.theme=e.theme,this.root=document.createElement("div"),this.root.className="ml-mtext-toolbar";const t=document.createElement("div");t.className="ml-mtext-toolbar__group";const i=document.createElement("select");i.className="ml-mtext-toolbar__select";for(const w of Bp(e.fontFamilies)){const v=document.createElement("option");v.value=w,v.textContent=w,i.appendChild(v)}const n=document.createElement("input");n.className="ml-mtext-toolbar__input",n.type="number",n.min="1",n.max="1024",n.step="1",this.colorPicker=this.createColorPicker(e.colorPicker,e.initialFormat),t.append(i,n,this.colorPicker.host);const r=document.createElement("div");r.className="ml-mtext-toolbar__separator";const o=document.createElement("div");o.className="ml-mtext-toolbar__group";const a=pt("Bold","bold"),l=pt("Italic","italic"),c=pt("Underline","underline"),h=pt("Overline","overline"),p=pt("Strike Through","strike"),m=pt("Superscript","superscript"),g=pt("Subscript","subscript"),f=pt("Stack","stack");o.append(a,l,c,h,p,m,g,f),this.root.append(t,r,o),this.controls={fontFamily:i,fontSize:n,boldBtn:a,italicBtn:l,underlineBtn:c,overlineBtn:h,strikeBtn:p,superscriptBtn:m,subscriptBtn:g,stackBtn:f},this.setTheme(this.theme),this.bindEvents(),(e.container??document.body).appendChild(this.root)}setTheme(e){this.theme=e,this.root.dataset.theme=e,this.colorPicker.setTheme(e)}getTheme(){return this.theme}setVisible(e){this.root.style.display=e?"inline-flex":"none"}setSession(e){this.anchorElement=e.anchorElement,this.onFormatChange=e.onFormatChange,this.onToggleStack=e.onToggleStack,this.onToggleSuperscript=e.onToggleSuperscript??(()=>!1),this.onToggleSubscript=e.onToggleSubscript??(()=>!1)}setAnchor(e,t){const i=this.root.offsetWidth||0,n=this.root.offsetHeight||0,r=8,o=8,a=Math.max(r,window.innerWidth-i-8),l=Math.max(o,window.innerHeight-n-8),c=Math.max(r,Math.min(a,Math.round(e))),h=Math.max(o,Math.min(l,Math.round(t-n)));this.root.style.left=`${c}px`,this.root.style.top=`${h}px`}setFormat(e){this.ensureSelectValue(e.fontFamily),this.controls.fontSize.value=String(Math.max(1,Math.round(e.fontSize)));const t=Ka(e);this.colorPicker.setValue(t),this.setToggleState(this.controls.boldBtn,e.bold),this.setToggleState(this.controls.italicBtn,e.italic),this.setToggleState(this.controls.underlineBtn,e.underline),this.setToggleState(this.controls.overlineBtn,e.overline),this.setToggleState(this.controls.strikeBtn,e.strike),this.setToggleState(this.controls.superscriptBtn,e.script==="superscript"),this.setToggleState(this.controls.subscriptBtn,e.script==="subscript")}dispose(){this.colorPicker.dispose(),this.root.remove()}setStackActive(e){this.setToggleState(this.controls.stackBtn,e)}setToggleState(e,t){e.classList.toggle("is-active",t),e.setAttribute("aria-pressed",t?"true":"false")}ensureSelectValue(e){if(!Array.from(this.controls.fontFamily.options).some(i=>i.value===e)){const i=document.createElement("option");i.value=e,i.textContent=e,this.controls.fontFamily.appendChild(i)}this.controls.fontFamily.value=e}bindEvents(){const e=()=>{const t=Math.max(1,Number(this.controls.fontSize.value)||1);this.controls.fontSize.value=String(Math.round(t)),this.onFormatChange({fontSize:t})};this.controls.fontFamily.addEventListener("change",()=>{this.onFormatChange({fontFamily:this.controls.fontFamily.value})}),this.controls.fontSize.addEventListener("input",e),this.controls.fontSize.addEventListener("change",e),this.controls.fontSize.addEventListener("blur",e),this.controls.fontSize.addEventListener("keydown",t=>{t.key==="Enter"&&(e(),this.anchorElement.focus({preventScroll:!0}))}),this.controls.boldBtn.addEventListener("click",()=>{this.onFormatChange({bold:!this.controls.boldBtn.classList.contains("is-active")})}),this.controls.italicBtn.addEventListener("click",()=>{this.onFormatChange({italic:!this.controls.italicBtn.classList.contains("is-active")})}),this.controls.underlineBtn.addEventListener("click",()=>{this.onFormatChange({underline:!this.controls.underlineBtn.classList.contains("is-active")})}),this.controls.overlineBtn.addEventListener("click",()=>{this.onFormatChange({overline:!this.controls.overlineBtn.classList.contains("is-active")})}),this.controls.strikeBtn.addEventListener("click",()=>{this.onFormatChange({strike:!this.controls.strikeBtn.classList.contains("is-active")})}),this.controls.superscriptBtn.addEventListener("click",()=>{if(this.onToggleSuperscript())return;const t=this.controls.superscriptBtn.classList.contains("is-active");this.onFormatChange({script:t?"normal":"superscript"})}),this.controls.subscriptBtn.addEventListener("click",()=>{if(this.onToggleSubscript())return;const t=this.controls.subscriptBtn.classList.contains("is-active");this.onFormatChange({script:t?"normal":"subscript"})}),this.controls.stackBtn.addEventListener("click",()=>{this.onToggleStack()}),this.root.addEventListener("mousedown",t=>{const i=t.target;i&&(i.closest('[data-ml-mtext-toolbar-interactive="true"]')||i.tagName==="INPUT"||i.tagName==="SELECT"||i.tagName==="OPTION"||(t.preventDefault(),this.anchorElement.focus({preventScroll:!0})))})}createColorPicker(e,t){if(!e){const a=document.createElement("input");return a.className="ml-mtext-toolbar__color",a.type="color",a.dataset.mlMtextToolbarInteractive="true",a.addEventListener("input",()=>{this.applyColorChange(Ga(a.value))}),{host:a,setValue:l=>{const c=jp(Op(l));c&&(a.value=c)},setTheme:()=>{},dispose:()=>{}}}const i=document.createElement("div");i.className="ml-mtext-toolbar__color",i.dataset.mlMtextToolbarInteractive="true";const n=t?Ka(t):Ga("#ffffff"),o=e({container:i,theme:this.theme,initialColor:n,onChange:a=>{this.applyColorChange(a)}})??{};return{host:i,setValue:a=>{var l;(l=o.setValue)==null||l.call(o,a)},setTheme:a=>{var l;(l=o.setTheme)==null||l.call(o,a)},dispose:()=>{var a;(a=o.dispose)==null||a.call(o)}}}applyColorChange(e){if(e.isAci&&e.aci!==null){this.onFormatChange({aci:e.aci});return}if(e.isRgb&&e.rgbValue!==null){this.onFormatChange({aci:null,rgb:sr(e.rgbValue)});return}this.onFormatChange({aci:null,rgb:16777215})}}function Ua(s,e){const t=Math.max(1,s),i=e;return i===void 0||i===1||i===4||i===7||i===10?0:i===2||i===5||i===8||i===11?-t/2:i===3||i===6||i===9||i===12?-t:0}const gn="__mlightcadMTextInputBoxSceneRoot",V=class V{constructor(e){E(this,"scene");E(this,"camera");E(this,"mtextRenderer");E(this,"cursorRenderer");E(this,"width");E(this,"position");E(this,"mtextInsertionOffset",new T.Vector3(0,0,0));E(this,"enableWordWrap");E(this,"mtextString","");E(this,"editorLineSpaceFactor",null);E(this,"editorAttachmentPoint",D.MTextAttachmentPoint.TopLeft);E(this,"cursorIndex",0);E(this,"selectionStart",0);E(this,"selectionEnd",0);E(this,"baseFormat");E(this,"currentFormat");E(this,"defaultTextStyle");E(this,"cursorLogic");E(this,"layoutContainer",{x:0,y:0,width:1,height:1});E(this,"isDragging",!1);E(this,"pendingCursorLineHint",null);E(this,"latestCursorLayoutData",{containerBox:{x:0,y:0,width:1,height:1},charBoxes:[]});E(this,"renderedObject",null);E(this,"boundingBoxObject",null);E(this,"boundingBoxPadding",1);E(this,"boundingBoxZOffset",.01);E(this,"rendererReady",!1);E(this,"pendingFontLoad",null);E(this,"lastFontKey","");E(this,"toolbarTheme","dark");E(this,"toolbarOffsetY",10);E(this,"debugMode",!1);E(this,"colorSettings");E(this,"debugVisibility",{showCharBoxes:!0,showLineIndices:!0,showCharIndices:!0,showChars:!0});E(this,"maxHistorySize",100);E(this,"undoStack",[]);E(this,"redoStack",[]);E(this,"document");E(this,"uiAdapter");E(this,"imeInput",null);E(this,"imeTarget",null);E(this,"lastImeTarget",null);E(this,"reopenTarget",null);E(this,"pointerTarget",null);E(this,"imeComposing",!1);E(this,"imeFocusTimer",null);E(this,"closed",!1);E(this,"toolbarEnabled",!0);E(this,"toolbarContainer",null);E(this,"toolbarFontFamilies",null);E(this,"toolbarColorPicker");E(this,"onImeKeyDown",e=>{if(!this.isActiveEditor()||!(e.ctrlKey||e.metaKey)&&!e.altKey&&e.key.length===1||e.isComposing||e.key==="Process")return;this.handleKeyDown(e)&&e.preventDefault()});E(this,"onWindowKeyDown",e=>{if(!this.isActiveEditor()||e.defaultPrevented)return;const t=e.target,i=(t==null?void 0:t.tagName)??"";if((i==="INPUT"||i==="TEXTAREA"||i==="SELECT"||!!(t!=null&&t.isContentEditable))&&t!==this.imeInput)return;if(!(e.ctrlKey||e.metaKey)&&!e.altKey&&e.key.length===1||this.imeComposing||e.isComposing||e.key==="Process"){this.refocusImeInputSoon();return}this.handleKeyDown(e)&&(e.preventDefault(),this.refocusImeInputSoon())});E(this,"onImeBeforeInput",e=>{if(!this.isActiveEditor()||e.isComposing)return;const t=e.inputType;if(t==="insertText"||t==="insertCompositionText"){this.handleTextInput(e.data??"")&&e.preventDefault();return}t==="insertParagraph"&&this.handleTextInput(`
122
- `)&&e.preventDefault()});E(this,"onImeCompositionStart",()=>{this.isActiveEditor()&&(this.imeComposing=!0,this.updateImeAnchorPosition(),this.refocusImeInputSoon())});E(this,"onImeCompositionEnd",e=>{if(!this.isActiveEditor())return;this.imeComposing=!1;const t=e.data??"";this.handleTextInput(t)&&this.imeInput&&(this.imeInput.value=""),this.refocusImeInputSoon()});E(this,"onImeTargetMouseDown",()=>{this.isActiveEditor()&&this.refocusImeInputSoon()});E(this,"onPointerMouseDown",e=>{if(this.closed||e.altKey||e.button===1)return;const t=this.pointerEventToEditorLocal(e);if(!t)return;if(!this.isPointInContainer(t.x,t.y)){this.isActiveEditor()&&this.closeEditor();return}this.activateEditor(),this.handleMouseDown(t.x,t.y,e.shiftKey),this.refocusImeInputSoon()});E(this,"onPointerMouseMove",e=>{if(!this.isActiveEditor()||e.buttons===0||!this.isDragging)return;const t=this.pointerEventToEditorLocal(e);t&&this.handleMouseMove(t.x,t.y)});E(this,"onPointerMouseUp",()=>{this.isActiveEditor()&&this.handleMouseUp()});E(this,"onPointerDoubleClick",e=>{if(!this.isActiveEditor())return;const t=this.pointerEventToEditorLocal(e);t&&(this.handleDoubleClick(t.x,t.y),this.refocusImeInputSoon())});E(this,"onReopenDoubleClick",e=>{this.closed&&this.shouldReopenFromDoubleClick(e)&&this.showEditor()});E(this,"handlers",{change:new Set,selectionChange:new Set,cursorMove:new Set,show:new Set,close:new Set});var o,a,l,c,h,p,m,g;V.instances.add(this),this.scene=e.scene,this.camera=e.camera,this.toolbarTheme=((o=e.toolbar)==null?void 0:o.theme)??"dark",this.toolbarOffsetY=Math.max(0,((a=e.toolbar)==null?void 0:a.offsetY)??10),this.toolbarEnabled=((l=e.toolbar)==null?void 0:l.enabled)??!0,this.toolbarContainer=((c=e.toolbar)==null?void 0:c.container)??null,this.toolbarFontFamilies=((h=e.toolbar)==null?void 0:h.fontFamilies)??null,this.toolbarColorPicker=(p=e.toolbar)==null?void 0:p.colorPicker,this.colorSettings=e.colorSettings,this.width=Math.max(1,e.width),this.position=((m=e.position)==null?void 0:m.clone())??new T.Vector3(0,0,0),e.initialAttachmentPoint!==void 0&&(this.editorAttachmentPoint=e.initialAttachmentPoint),this.enableWordWrap=e.enableWordWrap??!0;const t=e.textStyle??V.DEFAULT_TEXT_STYLE,i=Math.max(1,Number.isFinite(t.fixedTextHeight)?t.fixedTextHeight:V.DEFAULT_TEXT_STYLE.fixedTextHeight),n=Math.max(1,Number.isFinite(t.lastHeight)?t.lastHeight:i);this.defaultTextStyle={...t,fixedTextHeight:i,lastHeight:n,widthFactor:Number.isFinite(t.widthFactor)?t.widthFactor:1,obliqueAngle:Number.isFinite(t.obliqueAngle)?t.obliqueAngle:0,textGenerationFlag:Number.isFinite(t.textGenerationFlag)?t.textGenerationFlag:0,standardFlag:Number.isFinite(t.standardFlag)?t.standardFlag:0,font:t.font||V.DEFAULT_TEXT_STYLE.font,bigFont:t.bigFont??""},this.baseFormat=this.createBaseFormatFromTextStyle(this.defaultTextStyle,this.resolveRenderColorSettings()),this.currentFormat={...this.baseFormat},this.document=new pe,this.uiAdapter=new nr(this.document),this.mtextRenderer=new D.UnifiedRenderer("main",{workerUrl:typeof e.workerUrl=="string"?e.workerUrl:((g=e.workerUrl)==null?void 0:g.toString())??"./assets/mtext-renderer-worker.js"}),e.fontUrl&&this.mtextRenderer.setFontUrl(e.fontUrl),this.cursorLogic=new mp({containerBox:{x:0,y:0,width:this.width,height:1},charBoxes:[],lineTolerance:4});const r={...e.cursorStyle??{}};r.height===void 0&&r.heightMode!=="fixed"&&(r.height=0),r.color??(r.color="#ffffff"),r.glowColor??(r.glowColor="#ffffff"),this.cursorRenderer=new wp({renderer:new vp({scene:this.scene,camera:this.camera}),cursorStyle:r,selectionStyle:e.selectionStyle,enableDebug:!1,enableSelection:!0,debugYAxisUp:this.camera instanceof T.OrthographicCamera?this.camera.top>=this.camera.bottom:!0,debugVisibility:this.debugVisibility}),this.cursorRenderer.setViewTransform({x:this.position.x,y:this.position.y,scaleX:1,scaleY:1}),this.createBoundingBox(e.showBoundingBox??!0,e.boundingBoxStyle),this.setText(e.initialText??""),this.attachIme(e.imeTarget),this.initializeRenderer()}setText(e){this.document=this.createNormalizedDocument(e),this.document.cursor=0,this.uiAdapter=new nr(this.document),this.clearHistory(),this.syncUiStateFromDocument(),this.relayout(),this.emit("change")}getText(){return this.syncUiStateFromDocument(),this.mtextString}getPlainText(){return this.getChars().join("")}insertText(e){if(e.length!==0){if(e===`
123
- `){const t=this.cursorLogic.getCursorState().lineIndex;this.pendingCursorLineHint=t>=0?t+1:0}this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"insertText",text:e,style:this.toDocumentStyle(this.currentFormat)}),this.syncUiStateFromDocument(),this.relayout()})}}deleteBackward(){this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"backspace"}),this.syncUiStateFromDocument(),this.relayout()})}deleteForward(){this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"delete"}),this.syncUiStateFromDocument(),this.relayout()})}undo(){const e=this.undoStack.pop();return e?(this.redoStack.push(this.createHistorySnapshot()),this.restoreHistorySnapshot(e),!0):!1}redo(){const e=this.redoStack.pop();return e?(this.undoStack.push(this.createHistorySnapshot()),this.restoreHistorySnapshot(e),!0):!1}moveCursor(e){switch(e){case"left":this.cursorLogic.moveLeft();break;case"right":this.cursorLogic.moveRight();break;case"up":this.cursorLogic.moveUp();break;case"down":this.cursorLogic.moveDown();break;case"lineStart":this.cursorLogic.moveToLineStart();break;case"lineEnd":this.cursorLogic.moveToLineEnd();break;case"wordPrev":this.cursorLogic.moveTo(this.findPrevWordStart(this.cursorLogic.getCurrentIndex()));break;case"wordNext":this.cursorLogic.moveTo(this.findNextWordStart(this.cursorLogic.getCurrentIndex()));break}this.cursorLogic.clearSelection(),this.syncStateFromCursor(),this.emit("cursorMove"),this.emit("selectionChange")}extendSelection(e){const t=this.cursorLogic.getSelection(),i=t?t.anchor:this.cursorLogic.getCurrentIndex();switch(this.cursorLogic.clearSelection(),this.cursorLogic.moveTo(this.cursorIndex),e){case"left":this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex()-1);break;case"right":this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex()+1);break;case"up":this.cursorLogic.moveUp();break;case"down":this.cursorLogic.moveDown();break;case"lineStart":this.cursorLogic.moveToLineStart();break;case"lineEnd":this.cursorLogic.moveToLineEnd();break}this.cursorLogic.setSelectionWithDirection(i,this.cursorLogic.getCurrentIndex()),this.syncStateFromCursor(),this.emit("selectionChange")}selectAll(){this.cursorLogic.selectAll(),this.syncStateFromCursor(),this.emit("selectionChange")}clearSelection(){this.cursorLogic.clearSelection(),this.syncStateFromCursor(),this.emit("selectionChange")}setDebugMode(e){this.debugMode=e,this.cursorRenderer.setDebugMode(e)}isDebugMode(){return this.debugMode}setDebugVisibility(e){this.debugVisibility={...this.debugVisibility,...e},this.cursorRenderer.setDebugVisibility(e)}getDebugVisibility(){return{...this.debugVisibility}}setToolbarTheme(e){var t;this.toolbarTheme=e,this.isActiveEditor()&&((t=this.getActiveToolbar())==null||t.setTheme(e))}getToolbarTheme(){return this.toolbarTheme}attachIme(e){const t=this.closed;this.lastImeTarget=e,this.bindReopenDoubleClick(e),this.imeTarget=e,this.attachPointerInteractions(e),this.closed=!1,V.activeEditor?V.activeEditor===this?this.activateEditor():(this.cursorRenderer.hide(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!1)):this.activateEditor(),t&&this.emit("show")}detachIme(){this.imeInput&&(this.imeInput.removeEventListener("keydown",this.onImeKeyDown),this.imeInput.removeEventListener("beforeinput",this.onImeBeforeInput),this.imeInput.removeEventListener("compositionstart",this.onImeCompositionStart),this.imeInput.removeEventListener("compositionend",this.onImeCompositionEnd),window.removeEventListener("keydown",this.onWindowKeyDown),this.imeTarget&&this.imeTarget.removeEventListener("mousedown",this.onImeTargetMouseDown),this.imeInput.remove(),this.imeInput=null,this.imeComposing=!1,this.imeFocusTimer!==null&&(window.clearTimeout(this.imeFocusTimer),this.imeFocusTimer=null))}getCursorIndex(){return this.cursorIndex}getSelectionRange(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return{start:e,end:t,isCollapsed:e===t}}getCursorLayoutData(){const e={containerBox:{...this.latestCursorLayoutData.containerBox},charBoxes:this.latestCursorLayoutData.charBoxes.map(t=>({...t}))};return this.latestCursorLayoutData.lineBreakIndices&&(e.lineBreakIndices=[...this.latestCursorLayoutData.lineBreakIndices]),this.latestCursorLayoutData.lineLayouts&&(e.lineLayouts=this.latestCursorLayoutData.lineLayouts.map(t=>({...t}))),e}setCurrentFormat(e){var n;const t=this.mergeCharFormat(this.currentFormat,e);this.currentFormat=t;const i=this.getSelectionRange();i.isCollapsed||this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const r=this.getNodesByLogicalRange(i.start,i.end);for(const o of r){const a=this.toCharFormat(o.style),l=this.mergeCharFormat(a,e);o.style=this.toDocumentStyle(l,o.style)}this.syncUiStateFromDocument(),this.relayout()}),(n=this.getActiveToolbar())==null||n.setFormat(this.currentFormat)}getCurrentFormat(){return{...this.currentFormat}}setParagraphAlignment(e){const t=this.mapRibbonParagraphAlignment(e);t!==void 0&&this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const i=this.getSelectionRange(),n=this.toDocumentIndexFromLogicalIndex(Math.min(i.start,i.end),!0),r=this.toDocumentIndexFromLogicalIndex(Math.max(i.start,i.end),!1),o=this.document.ast.nodes;if(o.length===0)return;const a=m=>{var f;const g=Math.max(0,Math.min(m,o.length-1));return((f=o[g])==null?void 0:f.type)==="paragraphBreak"?Math.min(g+1,o.length):Math.min(m,o.length-1)},l=m=>{var f;const g=a(m);for(let w=g;w>=0;w--)if(((f=o[w])==null?void 0:f.type)==="paragraphBreak")return w+1;return 0},c=m=>{var f;const g=Math.min(Math.max(0,m),o.length-1);for(let w=g;w<o.length;w++)if(((f=o[w])==null?void 0:f.type)==="paragraphBreak")return w;return o.length},h=l(Math.min(n,r)),p=c(Math.max(n,r));if(!(h>=p)){for(let m=h;m<p;m++){const g=o[m];g&&hi(g)&&(g.style.paragraph.align=t)}this.syncUiStateFromDocument(),this.relayout()}})}setAttachmentPoint(e){const t=this.mapRibbonAttachmentCode(e);if(!(t===void 0||t===this.editorAttachmentPoint)){if(Number.isFinite(this.layoutContainer.width)&&Number.isFinite(this.layoutContainer.height)){const i=this.position.x+this.layoutContainer.x,n=i+this.layoutContainer.width,r=this.position.y+this.layoutContainer.y,o=r+this.layoutContainer.height;if(Number.isFinite(i)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(o)&&n>=i-1e-9&&o>=r-1e-9){const a=this.computeAttachmentAnchorOnBounds(i,n,r,o,this.editorAttachmentPoint),l=this.computeAttachmentAnchorOnBounds(i,n,r,o,t);this.position.x+=l.x-a.x,this.position.y+=l.y-a.y,this.cursorRenderer.setViewTransform({x:this.position.x,y:this.position.y,scaleX:1,scaleY:1})}}this.editorAttachmentPoint=t,this.relayout(),this.emit("change")}}getAttachmentPointCode(){return this.attachmentPointToRibbonCode(this.editorAttachmentPoint)}getMTextAttachmentPoint(){return this.editorAttachmentPoint}toggleCase(){const e=this.getSelectionRange();e.isCollapsed||this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const t=this.toDocumentIndexFromLogicalIndex(e.start,!0),i=this.toDocumentIndexFromLogicalIndex(e.end,!1);if(i<=t)return;const n=this.document.ast.nodes.slice(t,i),r=n.map(l=>l.type==="char"?l.value:l.type==="stack"?`${l.numerator}${l.denominator}`:"").join("");if(!/[a-zA-Z]/.test(r))return;const o=/[a-z]/.test(r),a=l=>o?l.toUpperCase():l.toLowerCase();this.document.transaction(()=>{for(const l of n)l.type==="char"?l.value=a(l.value):l.type==="stack"&&(l.numerator=a(l.numerator),l.denominator=a(l.denominator));this.document.setSelection(t,i)}),this.syncUiStateFromDocument(),this.relayout()})}getDefaultTextStyle(){return{...this.defaultTextStyle}}handleKeyDown(e){if(e.isComposing||e.key==="Process")return!1;if(e.key==="Escape")return this.closeEditor(),!0;const t=this.isMacPlatform(),i=t?e.metaKey:e.ctrlKey,n=t?e.altKey:e.ctrlKey;if(i&&e.key.toLowerCase()==="a")return this.selectAll(),!0;if(i&&e.key.toLowerCase()==="z")return e.shiftKey?this.redo():this.undo();if(!t&&i&&e.key.toLowerCase()==="y")return this.redo();if(e.shiftKey){if(e.key==="ArrowLeft")return this.consumeExtend("left");if(e.key==="ArrowRight")return this.consumeExtend("right");if(e.key==="ArrowUp")return this.consumeExtend("up");if(e.key==="ArrowDown")return this.consumeExtend("down");if(e.key==="Home")return this.consumeExtend("lineStart");if(e.key==="End")return this.consumeExtend("lineEnd")}return t&&e.metaKey&&e.key==="ArrowLeft"?this.consumeMove("lineStart"):t&&e.metaKey&&e.key==="ArrowRight"?this.consumeMove("lineEnd"):e.key==="ArrowLeft"?this.consumeMove(n?"wordPrev":"left"):e.key==="ArrowRight"?this.consumeMove(n?"wordNext":"right"):e.key==="ArrowUp"?this.consumeMove("up"):e.key==="ArrowDown"?this.consumeMove("down"):e.key==="Home"?this.consumeMove("lineStart"):e.key==="End"?this.consumeMove("lineEnd"):e.key==="Backspace"?(this.deleteBackward(),!0):e.key==="Delete"?(this.deleteForward(),!0):e.key==="Enter"?(this.insertText(`
124
- `),!0):!i&&!e.altKey&&e.key.length===1?(this.insertText(e.key),!0):!1}handleTextInput(e){return e?(this.insertText(e),!0):!1}handleMouseDown(e,t,i){if(i){const n=this.cursorLogic.hitTest(e,t);if(n<0)return;this.cursorLogic.setSelectionWithDirection(this.selectionStart,n)}else if(!this.cursorLogic.moveToClick(e,t))return;this.isDragging=!0,this.syncStateFromCursor(),this.emit("cursorMove"),this.emit("selectionChange")}handleMouseMove(e,t){this.isDragging&&(this.cursorLogic.updateSelectionDrag(e,t),this.syncStateFromCursor(),this.emit("selectionChange"))}handleMouseUp(){this.isDragging=!1}handleDoubleClick(e,t){const i=this.cursorLogic.hitTest(e,t);if(i<0)return;const n=this.getChars();let r=i,o=i;for(;r>0&&!/\s/.test(n[r-1]??"");)r-=1;for(;o<n.length&&!/\s/.test(n[o]??"");)o+=1;this.cursorLogic.setSelection(r,o),this.cursorLogic.moveTo(o),this.syncStateFromCursor(),this.emit("selectionChange")}update(){const e=this.cursorLogic.getCursorState(),t=this.cursorLogic.getSelection(),i=this.getActiveCursorRenderState(e.position,e.lineInfo.height),n=this.cursorLogic.getSelectedCharBoxes();this.cursorRenderer.updateCursor(i.position,i.height),this.cursorRenderer.updateSelection(n),this.cursorRenderer.updateDebugInfo({containerBox:this.layoutContainer,charBoxes:this.cursorLogic.getCharBoxes(),chars:this.getChars(),lines:this.cursorLogic.getLines()}),this.cursorRenderer.setSelectionStyle({fillColor:t!=null&&t.isBackwards?"rgba(150,0,255,0.25)":"rgba(0,120,255,0.30)"}),this.cursorRenderer.render(),this.updateImeAnchorPosition(),this.updateToolbarPosition()}dispose(){var e;V.activeEditor===this?this.deactivateEditor():this.detachIme(),this.detachPointerInteractions(),this.unbindReopenDoubleClick(),this.disposeRenderedObject(this.renderedObject),this.renderedObject=null,this.disposeBoundingBox(),this.mtextRenderer.destroy(),this.cursorRenderer.dispose(),this.cursorLogic.destroy(),this.handlers.change.clear(),this.handlers.selectionChange.clear(),this.handlers.cursorMove.clear(),this.handlers.show.clear(),this.handlers.close.clear(),V.instances.delete(this),V.instances.size===0&&((e=V.sharedToolbar)==null||e.dispose(),V.sharedToolbar=null,V.sharedToolbarContainer=null,V.sharedToolbarFontFamiliesKey="",V.sharedToolbarColorPickerFactory=null,V.activeEditor=null)}closeEditor(){this.closed||(this.closed=!0,this.detachPointerInteractions(),this.deactivateEditor(),this.emit("close"))}showEditor(){const e=this.lastImeTarget;if(!e)return!1;const t=this.closed;return this.closed=!1,this.attachPointerInteractions(e),this.activateEditor(),t&&this.emit("show"),!0}attachPointerInteractions(e){this.detachPointerInteractions(),this.pointerTarget=e,e.addEventListener("mousedown",this.onPointerMouseDown),e.addEventListener("mousemove",this.onPointerMouseMove),e.addEventListener("dblclick",this.onPointerDoubleClick),window.addEventListener("mouseup",this.onPointerMouseUp)}detachPointerInteractions(){this.pointerTarget&&(this.pointerTarget.removeEventListener("mousedown",this.onPointerMouseDown),this.pointerTarget.removeEventListener("mousemove",this.onPointerMouseMove),this.pointerTarget.removeEventListener("dblclick",this.onPointerDoubleClick),window.removeEventListener("mouseup",this.onPointerMouseUp),this.pointerTarget=null)}on(e,t){this.handlers[e].add(t)}off(e,t){(e==="change"||e==="selectionChange"||e==="cursorMove"||e==="show"||e==="close")&&this.handlers[e].delete(t)}getCursorWorldPosition(){const e=this.cursorLogic.getCursorState(),t=this.getActiveCursorRenderState(e.position,e.lineInfo.height).position;return{x:this.position.x+t.x,y:this.position.y+t.y,z:this.position.z}}getMTextInsertionPoint(){return this.position.clone()}getState(){return{mtextString:this.getText(),cursorIndex:this.cursorIndex,selectionStart:this.selectionStart,selectionEnd:this.selectionEnd,currentFormat:this.getCurrentFormat()}}isActiveEditor(){return V.activeEditor===this}activateEditor(){var i;if(this.closed)return;const e=V.activeEditor;e&&e!==this&&e.deactivateEditor(),V.activeEditor=this;const t=this.imeTarget??this.lastImeTarget;t&&this.attachImeBridge(t),this.cursorRenderer.show(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!0),t&&this.toolbarEnabled?this.mountToolbar(t):(i=V.sharedToolbar)==null||i.setVisible(!1)}deactivateEditor(){var e;this.isDragging=!1,this.detachIme(),this.cursorRenderer.hide(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!1),V.activeEditor===this&&(V.activeEditor=null,(e=V.sharedToolbar)==null||e.setVisible(!1))}attachImeBridge(e){this.detachIme(),this.imeTarget=e;const t=document.createElement("textarea");t.setAttribute("aria-hidden","true"),t.autocapitalize="off",t.autocomplete="off",t.spellcheck=!1,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.style.width="2px",t.style.height="2px",t.style.opacity="0",t.style.pointerEvents="none",t.style.zIndex="2147483647",document.body.appendChild(t),this.imeInput=t,t.addEventListener("keydown",this.onImeKeyDown),t.addEventListener("beforeinput",this.onImeBeforeInput),t.addEventListener("compositionstart",this.onImeCompositionStart),t.addEventListener("compositionend",this.onImeCompositionEnd),window.addEventListener("keydown",this.onWindowKeyDown),e.addEventListener("mousedown",this.onImeTargetMouseDown),this.updateImeAnchorPosition(),this.focusImeInput()}getActiveToolbar(){if(!this.isActiveEditor())return null;const e=V.sharedToolbar;if(!e)throw new Error("[mtext-input-box] Failed to create shared toolbar");return e}createToolbarSessionOptions(e){return{anchorElement:e,onFormatChange:t=>{this.setCurrentFormat(t)},onToggleStack:()=>{this.toggleStackSelection()},onToggleSuperscript:()=>this.toggleScriptSelection("superscript"),onToggleSubscript:()=>this.toggleScriptSelection("subscript")}}ensureSharedToolbar(e){var o,a;const t=this.toolbarContainer??document.body,i=((o=this.toolbarFontFamilies)==null?void 0:o.join("\0"))??"";if(!V.sharedToolbar||V.sharedToolbarContainer!==t||V.sharedToolbarFontFamiliesKey!==i||V.sharedToolbarColorPickerFactory!==(this.toolbarColorPicker??null)){(a=V.sharedToolbar)==null||a.dispose();const l={...this.createToolbarSessionOptions(e),container:t,theme:this.toolbarTheme,initialFormat:this.currentFormat};this.toolbarFontFamilies&&(l.fontFamilies=this.toolbarFontFamilies),this.toolbarColorPicker&&(l.colorPicker=this.toolbarColorPicker),V.sharedToolbar=new Fp(l),V.sharedToolbarContainer=t,V.sharedToolbarFontFamiliesKey=i,V.sharedToolbarColorPickerFactory=this.toolbarColorPicker??null}const r=V.sharedToolbar;if(!r)throw new Error("[mtext-input-box] Failed to create shared toolbar");return r}mountToolbar(e){if(!this.toolbarEnabled||!this.isActiveEditor())return;const t=this.ensureSharedToolbar(e);t.setTheme(this.toolbarTheme),t.setSession(this.createToolbarSessionOptions(e)),t.setVisible(!0),t.setFormat(this.currentFormat),this.updateToolbarStackState(),this.updateToolbarPosition()}updateToolbarPosition(){if(!this.toolbarEnabled||!this.isActiveEditor()||!this.imeTarget)return;const e=this.getActiveToolbar();if(!e)return;const t=this.getEditorScreenBounds();t&&e.setAnchor(t.minX,t.minY-this.toolbarOffsetY)}getEditorScreenBounds(){if(!this.imeTarget)return null;const e=this.imeTarget.getBoundingClientRect(),t=this.position.x+this.layoutContainer.x,i=t+this.layoutContainer.width,n=this.position.y+this.layoutContainer.y,r=n+this.layoutContainer.height,o=[new T.Vector3(t,n,this.position.z),new T.Vector3(i,n,this.position.z),new T.Vector3(t,r,this.position.z),new T.Vector3(i,r,this.position.z)];let a=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,c=Number.POSITIVE_INFINITY,h=Number.NEGATIVE_INFINITY;for(const p of o){const m=p.clone().project(this.camera),g=e.left+(m.x+1)*.5*e.width,f=e.top+(1-m.y)*.5*e.height;a=Math.min(a,g),l=Math.max(l,g),c=Math.min(c,f),h=Math.max(h,f)}return!Number.isFinite(a)||!Number.isFinite(c)?null:{minX:a,maxX:l,minY:c,maxY:h}}pointerEventToEditorLocal(e){const t=this.pointerTarget??this.imeTarget;return this.pointerEventToEditorLocalByTarget(e,t)}pointerEventToEditorLocalByTarget(e,t){if(!t)return null;const i=t.getBoundingClientRect();if(i.width<=0||i.height<=0)return null;const n=(e.clientX-i.left)/i.width*2-1,r=-((e.clientY-i.top)/i.height)*2+1,o=new T.Vector3(n,r,-1).unproject(this.camera),l=new T.Vector3(n,r,1).unproject(this.camera).sub(o);if(Math.abs(l.z)<1e-8)return null;const c=(this.position.z-o.z)/l.z,h=o.add(l.multiplyScalar(c));return{x:h.x-this.position.x,y:h.y-this.position.y}}shouldReopenFromDoubleClick(e){return this.hitTestRenderedObject(e)}hitTestRenderedObject(e){if(!this.renderedObject||!this.reopenTarget)return!1;const t=this.reopenTarget.getBoundingClientRect();if(t.width<=0||t.height<=0)return!1;const i=(e.clientX-t.left)/t.width*2-1,n=-((e.clientY-t.top)/t.height)*2+1,r=new T.Raycaster;return r.setFromCamera(new T.Vector2(i,n),this.camera),r.intersectObject(this.renderedObject,!0).length>0}bindReopenDoubleClick(e){this.reopenTarget!==e&&(this.unbindReopenDoubleClick(),this.reopenTarget=e,e.addEventListener("dblclick",this.onReopenDoubleClick))}unbindReopenDoubleClick(){this.reopenTarget&&(this.reopenTarget.removeEventListener("dblclick",this.onReopenDoubleClick),this.reopenTarget=null)}isPointInContainer(e,t){const i=this.layoutContainer,n=i.x+i.width,r=i.y+i.height;return e>=i.x&&e<=n&&t>=i.y&&t<=r}async initializeRenderer(){try{await this.mtextRenderer.loadFonts([hn]),this.rendererReady=!0,this.ensureFontsLoaded(),this.relayout()}catch(e){console.error("[mtext-input-box] Failed to initialize mtext renderer fonts",e)}}relayout(){if(!this.rendererReady){this.mtextInsertionOffset.set(0,0,0);const e=this.createFallbackCharBoxes();this.layoutContainer=e.containerBox,this.updateCursorData(e.charBoxes,e.lineBreakIndices,e.lineLayouts),this.updateBoundingBoxGeometry();return}this.ensureFontsLoaded();try{const e=this.createMTextData(),t=this.createTextStyle(),i=this.resolveRenderColorSettings(),n=this.mtextRenderer.syncRenderMText(e,t,i);this.pruneExtraMTextLayoutRoots(n),this.replaceRenderedObject(n);const r=this.extractBoxesFromRenderedObject(n);this.mtextInsertionOffset.set(0,0,0),this.normalizeRenderedTopAlignment(n,r),this.layoutContainer=r.containerBox,this.updateCursorData(r.charBoxes,r.lineBreakIndices,r.lineLayouts),this.updateBoundingBoxGeometry()}catch(e){console.error("[mtext-input-box] Failed to sync render MTEXT",e),this.mtextInsertionOffset.set(0,0,0);const t=this.createFallbackCharBoxes();this.layoutContainer=t.containerBox,this.updateCursorData(t.charBoxes,t.lineBreakIndices,t.lineLayouts),this.updateBoundingBoxGeometry()}}ensureFontsLoaded(){if(this.pendingFontLoad)return;const e=this.collectFontNamesForText(),t=e.map(i=>i.toLowerCase()).sort().join("|");!t||t===this.lastFontKey||(this.lastFontKey=t,this.pendingFontLoad=this.mtextRenderer.loadFonts(e).then(()=>{}).catch(i=>{console.warn("[mtext-input-box] Failed to load fonts for MTEXT",i)}).finally(()=>{this.pendingFontLoad=null,this.rendererReady&&this.relayout()}))}collectFontNamesForText(){const e=new Set,t=i=>{if(!i)return;const n=i.trim();n&&e.add(n)};t(this.defaultTextStyle.font),t(this.defaultTextStyle.bigFont);try{const i=D.MText.getFonts(this.mtextString||"",!0);for(const n of i)t(n)}catch(i){console.warn("[mtext-input-box] Failed to parse fonts from MTEXT",i)}return e.size===0&&e.add(hn),[...e]}updateCursorData(e,t,i){this.latestCursorLayoutData={containerBox:{...this.layoutContainer},charBoxes:e.map(l=>({...l})),...t?{lineBreakIndices:[...t]}:{},...i?{lineLayouts:i.map(l=>({...l}))}:{}},this.cursorLogic.updateData(this.layoutContainer,e,t,i);const n=Math.min(this.cursorIndex,this.charCount()),r=Math.max(0,this.cursorLogic.getLineCount()-1),o=this.pendingCursorLineHint===null?null:Math.max(0,Math.min(this.pendingCursorLineHint,r));this.pendingCursorLineHint=null,this.cursorLogic.moveTo(n,o),this.selectionStart!==this.selectionEnd?this.cursorLogic.setSelection(this.selectionStart,this.selectionEnd):this.cursorLogic.clearSelection(),this.syncStateFromCursor();const a=this.unionLayoutContainerWithCursorLines(this.layoutContainer);(Math.abs(a.y-this.layoutContainer.y)>1e-6||Math.abs(a.height-this.layoutContainer.height)>1e-6)&&(this.layoutContainer=a,this.latestCursorLayoutData.containerBox={...this.layoutContainer},this.cursorLogic.updateData(this.layoutContainer,e,t,i),this.cursorLogic.moveTo(n,o),this.selectionStart!==this.selectionEnd?this.cursorLogic.setSelection(this.selectionStart,this.selectionEnd):this.cursorLogic.clearSelection(),this.syncStateFromCursor())}unionLayoutContainerWithCursorLines(e){const t=this.cursorLogic.getLines();if(t.length===0)return e;let i=e.y,n=e.y+e.height;for(const r of t){if(r.charCount!==0)continue;const o=r.y-r.height/2,a=r.y+r.height/2;Number.isFinite(o)&&(i=Math.min(i,o)),Number.isFinite(a)&&(n=Math.max(n,a))}return!Number.isFinite(i)||!Number.isFinite(n)||n<i?e:{...e,y:i,height:n-i}}computeEditorVerticalBounds(e,t,i){const n=()=>({minY:i.y-i.height/2,maxY:i.y+i.height/2}),r=(l,c,h,p)=>l<p+1e-4&&c>h-1e-4;if(e.length===0&&t.length===0)return n();if(e.length===0){let l=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(const h of t)l=Math.min(l,h.y-h.height/2),c=Math.max(c,h.y+h.height/2);return Number.isFinite(l)&&Number.isFinite(c)&&c>=l?{minY:l,maxY:c}:n()}if(t.length===0){let l=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(const h of e){const p=h.y-h.height/2,m=h.y+h.height/2;l=Math.min(l,p),c=Math.max(c,m)}return Number.isFinite(l)&&Number.isFinite(c)&&c>=l?{minY:l,maxY:c}:n()}let o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const l of e){const c=l.y-l.height/2,h=l.y+l.height/2,p=t.filter(m=>{const g=m.y-m.height/2,f=m.y+m.height/2;return r(g,f,c,h)});if(p.length===0)o=Math.min(o,c),a=Math.max(a,h);else for(const m of p)o=Math.min(o,m.y-m.height/2),a=Math.max(a,m.y+m.height/2)}for(const l of t){const c=l.y-l.height/2,h=l.y+l.height/2;e.some(m=>{const g=m.y-m.height/2,f=m.y+m.height/2;return r(c,h,g,f)})||(o=Math.min(o,c),a=Math.max(a,h))}return!Number.isFinite(o)||!Number.isFinite(a)||a<o?n():{minY:o,maxY:a}}extractBoxesFromRenderedObject(e){const t=e.createLayoutData(),i=[],n=((t==null?void 0:t.lines)??[]).filter(p=>Number.isFinite(p.y)&&Number.isFinite(p.height)).map(p=>({y:p.y-this.position.y,height:Math.max(1,p.height)}));for(const p of(t==null?void 0:t.chars)??[]){const m=p.box?this.toLocalBox(p.box):void 0;!m||!(Number.isFinite(m.x)&&Number.isFinite(m.y)&&Number.isFinite(m.width)&&Number.isFinite(m.height))||i.push(m)}const r=(t.lines??[]).map(p=>p.breakIndex).filter(p=>Number.isInteger(p)).filter(p=>p>=0&&p<=i.length),o=this.toLocalBox(e.box),{minY:a,maxY:l}=this.computeEditorVerticalBounds(n,i,o),c={x:Ua(this.width,this.editorAttachmentPoint),y:a,width:Math.max(1,this.width),height:Math.max(0,l-a)},h=this.getFallbackLineAdvance();if(c.height<h){const p=h-c.height;c.y-=p,c.height=h}return{containerBox:c,charBoxes:i,...r.length>0?{lineBreakIndices:r}:{},...n.length>0?{lineLayouts:n}:{}}}normalizeRenderedTopAlignment(e,t){var r;const n=-(t.containerBox.y+t.containerBox.height);!Number.isFinite(n)||Math.abs(n)<1e-8||(this.mtextInsertionOffset.set(0,n,0),e.position.y+=n,e.updateMatrixWorld(!0),t.containerBox.y+=n,t.charBoxes.forEach(o=>{o.y+=n}),(r=t.lineLayouts)==null||r.forEach(o=>{o.y+=n}))}toLocalBox(e){const t=e.min.x-this.position.x,i=e.max.x-this.position.x,n=e.min.y-this.position.y,r=e.max.y-this.position.y,o=Math.max(0,i-t),a=Math.max(0,r-n);return{x:t,y:n+a/2,width:o,height:a}}createFallbackCharBoxes(){const e=this.getFallbackLineAdvance(),t=[],i=[],n=[];let r=0,o=0,a=-e;n.push({y:o-e/2,height:e});for(const l of this.getChars()){if(l===`
125
- `){i.push(t.length),r=0,o-=e,a=Math.min(a,o-e),n.push({y:o-e/2,height:e});continue}const c=Math.max(1,this.currentFormat.fontSize*.6);this.enableWordWrap&&r>0&&r+c>this.width&&(i.push(t.length),r=0,o-=e,a=Math.min(a,o-e),n.push({y:o-e/2,height:e})),t.push({x:r,y:o-e/2,width:c,height:e}),r+=c}return{containerBox:{x:Ua(this.width,this.editorAttachmentPoint),y:a,width:this.width,height:Math.max(1,-a)},charBoxes:t,lineBreakIndices:i,lineLayouts:n}}createBoundingBox(e,t){if(!e)return;const i=typeof(t==null?void 0:t.color)=="number"?t.color:new T.Color((t==null?void 0:t.color)??"#58a6ff");this.boundingBoxPadding=Math.max(0,(t==null?void 0:t.padding)??1),this.boundingBoxZOffset=(t==null?void 0:t.zOffset)??.01;const n=new T.LineBasicMaterial({color:i,transparent:!0,opacity:(t==null?void 0:t.opacity)??.9,depthTest:!1,depthWrite:!1}),r=new T.BufferGeometry;this.boundingBoxObject=new T.LineLoop(r,n),this.boundingBoxObject.position.z=this.boundingBoxZOffset,this.scene.add(this.boundingBoxObject)}updateBoundingBoxGeometry(){if(!this.boundingBoxObject)return;this.boundingBoxObject.geometry.dispose();const t=this.boundingBoxPadding,i=this.position.x+this.layoutContainer.x-t,n=this.position.y+this.layoutContainer.y-t,r=this.position.x+this.layoutContainer.x+this.layoutContainer.width+t,o=this.position.y+this.layoutContainer.y+this.layoutContainer.height+t,a=this.position.z;this.boundingBoxObject.geometry=new T.BufferGeometry().setFromPoints([new T.Vector3(i,n,a),new T.Vector3(r,n,a),new T.Vector3(r,o,a),new T.Vector3(i,o,a)])}disposeBoundingBox(){if(!this.boundingBoxObject)return;this.boundingBoxObject.removeFromParent(),this.boundingBoxObject.geometry.dispose();const e=Array.isArray(this.boundingBoxObject.material)?this.boundingBoxObject.material:[this.boundingBoxObject.material];for(const t of e)t.dispose();this.boundingBoxObject=null}replaceRenderedObject(e){this.disposeRenderedObject(this.renderedObject),this.removeStrayInputBoxSceneRootsExcept(e),this.forceVisibleMaterialState(e),e.userData[gn]=this,this.renderedObject=e,this.scene.add(e)}removeStrayInputBoxSceneRootsExcept(e){const t=e;for(let i=this.scene.children.length-1;i>=0;i--){const n=this.scene.children[i];if(!n||n===t)continue;n.userData[gn]===this&&(this.scene.remove(n),this.disposeMTextRootResources(n),delete n.userData[gn])}}forceVisibleMaterialState(e){e.traverse(t=>{const i=t,n=i.material?Array.isArray(i.material)?i.material:[i.material]:[];for(const r of n){const o=r;typeof o.side<"u"&&(o.side=T.DoubleSide),typeof o.depthTest<"u"&&(o.depthTest=!1),typeof o.depthWrite<"u"&&(o.depthWrite=!1),typeof o.transparent<"u"&&typeof o.opacity<"u"&&(o.transparent=o.opacity<1),o.needsUpdate=!0}})}disposeDetachedThreeSubtree(e){e.traverse(t=>{const i=t;i.geometry&&i.geometry.dispose();const n=i.material?Array.isArray(i.material)?i.material:[i.material]:[];for(const r of n){const o=r;o.map&&o.map.dispose(),r.dispose()}})}pruneExtraMTextLayoutRoots(e){for(;e.children.length>1;){const t=e.children[0];if(!t)break;e.remove(t),this.disposeDetachedThreeSubtree(t)}}disposeMTextRootResources(e){const t=e;if(typeof t.dispose=="function"){t.dispose();return}this.disposeDetachedThreeSubtree(e)}disposeRenderedObject(e){e&&(e.removeFromParent(),delete e.userData[gn],this.disposeMTextRootResources(e))}isExplicitAci(e){return e!==null&&Number.isInteger(e)&&e>0&&e<256}normalizeColorNumber(e){return Math.max(0,Math.min(16777215,Math.round(e)))}resolveAciColor(e){const t=D.getColorByIndex(e);return this.normalizeColorNumber(Number.isFinite(t)?t:16777215)}resolveBaseColor(){return this.isExplicitAci(this.baseFormat.aci)?this.resolveAciColor(this.baseFormat.aci):this.baseFormat.rgb!==null?this.normalizeColorNumber(this.baseFormat.rgb):16777215}resolveBaseFormatColor(e){const t=e.color;if(t.isRgb&&t.rgbValue!==null)return{aci:null,rgb:this.normalizeColorNumber(t.rgbValue)};if(t.isAci&&t.aci!==null){const i=t.aci;return Number.isInteger(i)&&i>=1&&i<=255?{aci:i,rgb:null}:i===0?{aci:null,rgb:this.normalizeColorNumber(e.byBlockColor)}:{aci:null,rgb:this.normalizeColorNumber(e.byLayerColor)}}return{aci:null,rgb:this.normalizeColorNumber(e.byLayerColor)}}createBaseFormatFromTextStyle(e,t){const i=hp();i.fontFamily=e.font||i.fontFamily,i.fontSize=Math.max(1,e.fixedTextHeight);const n=this.resolveBaseFormatColor(t);i.aci=n.aci,i.rgb=n.rgb;const r=e.widthFactor;i.widthFactor=typeof r=="number"&&Number.isFinite(r)?Math.max(.01,r):1;const o=e.obliqueAngle;return i.obliqueAngle=typeof o=="number"&&Number.isFinite(o)?o:0,i.tracking=1,i}createMTextData(){const e={text:this.mtextString,height:Math.max(1,this.defaultTextStyle.fixedTextHeight),width:this.width,position:{x:this.position.x,y:this.position.y,z:this.position.z},attachmentPoint:this.editorAttachmentPoint,drawingDirection:D.MTextFlowDirection.LEFT_TO_RIGHT,widthFactor:1,collectCharBoxes:!0};return this.editorLineSpaceFactor!=null&&Number.isFinite(this.editorLineSpaceFactor)&&(e.lineSpaceFactor=this.editorLineSpaceFactor),e}getLineSpacingFactor(){return this.editorLineSpaceFactor??V.DEFAULT_LINE_SPACE_FACTOR}setLineSpacingFactor(e){if(!Number.isFinite(e)||e<=0)return;const t=V.DEFAULT_LINE_SPACE_FACTOR,i=e>=1?Math.max(.01,t+(e-1)/D.LINE_SPACING_SCALE_FACTOR):e;this.editorLineSpaceFactor=i,this.relayout(),this.emit("change")}clearLineSpacing(){this.editorLineSpaceFactor=null,this.relayout(),this.emit("change")}getFallbackLineAdvance(){return Math.max(1,this.currentFormat.fontSize*V.FALLBACK_LINE_ADVANCE_RATIO)}createTextStyle(){return{...this.defaultTextStyle}}resolveRenderColorSettings(){if(this.colorSettings)return this.colorSettings;const e=this.toolbarTheme==="light"?0:16777215;return{byLayerColor:e,byBlockColor:e,color:new D.MTextColor(256)}}focusImeInput(){this.imeInput&&this.imeInput.focus({preventScroll:!0})}refocusImeInputSoon(){this.imeInput&&(this.imeFocusTimer!==null&&window.clearTimeout(this.imeFocusTimer),this.imeFocusTimer=window.setTimeout(()=>{this.focusImeInput(),this.imeFocusTimer=null},0))}updateImeAnchorPosition(){if(!this.imeInput||!this.imeTarget)return;const e=this.getCursorWorldPosition(),i=new T.Vector3(e.x,e.y,e.z).project(this.camera),n=this.imeTarget.getBoundingClientRect(),r=n.left+(i.x+1)*.5*n.width,o=n.top+(1-i.y)*.5*n.height;this.imeInput.style.left=`${Math.round(r)}px`,this.imeInput.style.top=`${Math.round(o)}px`}syncStateFromCursor(){this.cursorIndex=this.cursorLogic.getCurrentIndex();const e=this.cursorLogic.getSelection();e?(this.selectionStart=e.start,this.selectionEnd=e.end):(this.selectionStart=this.cursorIndex,this.selectionEnd=this.cursorIndex),this.syncDocumentFromUiState(),this.refreshCurrentFormatFromDocument()}consumeMove(e){return this.moveCursor(e),!0}consumeExtend(e){return this.extendSelection(e),!0}isMacPlatform(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}emit(e){for(const t of this.handlers[e])t()}findPrevWordStart(e){const t=this.getChars();let i=Math.max(0,e-1);for(;i>0&&/\s/.test(t[i]??"");)i-=1;for(;i>0&&!/\s/.test(t[i-1]??"");)i-=1;return i}findNextWordStart(e){const t=this.getChars();let i=Math.min(t.length,e);for(;i<t.length&&!/\s/.test(t[i]??"");)i+=1;for(;i<t.length&&/\s/.test(t[i]??"");)i+=1;return i}getChars(){const e=[];for(const t of this.document.ast.nodes){if(t.type==="char"){e.push(t.value);continue}if(t.type==="stack"){e.push("");continue}(t.type==="paragraphBreak"||t.type==="columnBreak"||t.type==="wrapAtDimLine")&&e.push(`
126
- `)}return e}charCount(){return this.getChars().length}getActiveCursorRenderState(e,t){var a;const i=this.cursorLogic.getCharBoxes(),n=this.cursorLogic.getCurrentIndex(),r=this.cursorLogic.getCurrentLineInfo();if(i.length===0){const l=(a=this.latestCursorLayoutData.lineLayouts)==null?void 0:a[0];if(l&&Number.isFinite(l.y)&&Number.isFinite(l.height)){const h=Math.max(1,l.height);return{position:{x:e.x,y:l.y},height:h}}const c=Math.max(1,this.getFallbackLineAdvance());return{position:{x:e.x,y:this.layoutContainer.y+c/2},height:c}}if(n<=0||n===r.startIndex){if(!(r.charCount<=0||r.endIndex<r.startIndex)){const h=Math.max(0,Math.min(r.startIndex,i.length-1)),p=i[h];if(p)return{position:{x:e.x,y:p.y},height:Math.max(1,p.height)}}const c=r.height??t;return{position:{x:e.x,y:r.y??e.y},height:Math.max(1,c)}}const o=i[Math.min(n-1,i.length-1)];return o?{position:{x:o.x+o.width,y:o.y},height:Math.max(1,o.height)}:{position:e,height:Math.max(1,t)}}getNodeLogicalSpan(e){switch(e.type){case"char":return 1;case"stack":return 1;case"paragraphBreak":case"columnBreak":case"wrapAtDimLine":return 0;default:return 0}}toLogicalIndexFromDocumentIndex(e){const t=Math.max(0,Math.min(e,this.document.ast.nodes.length));let i=0;for(let n=0;n<t;n+=1){const r=this.document.ast.nodes[n];r&&(i+=this.getNodeLogicalSpan(r))}return i}toDocumentIndexFromLogicalIndex(e,t=!0,i){var h,p;const n=this.document.ast.nodes;if(n.length===0)return 0;const r=this.charCount(),o=Math.max(0,Math.min(e,r)),a=[];let l=0,c=0;for(let m=0;m<=n.length&&(l===o&&a.push({index:m,lineIndex:c}),m!==n.length);m+=1){const g=n[m];if(!g)continue;const f=this.getNodeLogicalSpan(g);f===0?c+=1:l+=f}if(a.length===0)return n.length;if(i!==void 0&&Number.isFinite(i)){const m=this,f=(typeof m.resolveCandidateByVisualLineHint=="function"?m.resolveCandidateByVisualLineHint:V.prototype.resolveCandidateByVisualLineHint).call(this,a,o,i);if(f!==void 0)return f;const w=((h=a[0])==null?void 0:h.lineIndex)??0,v=((p=a[a.length-1])==null?void 0:p.lineIndex)??0;if(i<w||i>v)return t?a[a.length-1].index:a[0].index;let x=a[0],S=Math.abs(x.lineIndex-i);for(let P=1;P<a.length;P+=1){const A=a[P],_=Math.abs(A.lineIndex-i);_<S&&(x=A,S=_)}return x.index}return t?a[a.length-1].index:a[0].index}resolveCandidateByVisualLineHint(e,t,i){if(e.length<=1||this.cursorLogic==null||typeof this.cursorLogic.getLines!="function")return;const n=this.cursorLogic.getLines();if(!Array.isArray(n)||n.length===0)return;const r=[];for(let l=0;l<n.length;l+=1){const c=n[l];c&&t>=c.startIndex&&t<=c.endIndex+1&&r.push(l)}if(r.length!==e.length)return;const o=r.indexOf(i);if(o<0)return;const a=e[o];return a==null?void 0:a.index}syncUiStateFromDocument(){this.mtextString=this.document.toMText();const e=this.charCount();this.cursorIndex=Math.min(this.toLogicalIndexFromDocumentIndex(this.document.cursor),e);const t=this.document.selection;t?(this.selectionStart=this.toLogicalIndexFromDocumentIndex(t.start),this.selectionEnd=this.toLogicalIndexFromDocumentIndex(t.end)):(this.selectionStart=this.cursorIndex,this.selectionEnd=this.cursorIndex),this.refreshCurrentFormatFromDocument()}syncDocumentFromUiState(){const e=this.getSelectionRange();if(!e.isCollapsed){const r=this.toDocumentIndexFromLogicalIndex(e.start,!0),o=this.toDocumentIndexFromLogicalIndex(e.end,!1);this.document.setSelection(r,o);return}this.document.clearSelection();const t=this.cursorLogic.getCursorState(),i=t.lineIndex,n=!(t.isAtLineEnd&&!t.isAtLineStart);this.document.cursor=this.toDocumentIndexFromLogicalIndex(this.cursorIndex,n,i>=0?i:void 0)}refreshCurrentFormatFromDocument(){var t,i;const e=this.inferCurrentFormatFromDocument();if(this.updateToolbarStackState(),!e){(t=this.getActiveToolbar())==null||t.setFormat(this.currentFormat);return}Ia(this.currentFormat,e)||(this.currentFormat=e),(i=this.getActiveToolbar())==null||i.setFormat(this.currentFormat)}toggleStackSelection(){const e=this.getSelectionRange();e.isCollapsed||this.commitHistoryEdit(()=>{var c;this.syncDocumentFromUiState();const t=this.toDocumentIndexFromLogicalIndex(e.start,!0),i=this.toDocumentIndexFromLogicalIndex(e.end,!1);if(i<=t)return;const n=this.document.ast.nodes.slice(t,i);if(n.length===1&&((c=n[0])==null?void 0:c.type)==="stack"){const h=n[0],p=this.stackNodeToPlainText(h.numerator,h.denominator,h.divider),m=Array.from(p).map(g=>({type:"char",value:g,style:this.cloneDocumentStyle(h.style)}));if(m.length===0)return;this.document.transaction(g=>{g.ast.nodes.splice(t,1,...m),g.setSelection(t,t+m.length)}),this.syncUiStateFromDocument(),this.relayout();return}if(!n.every(h=>(h==null?void 0:h.type)==="char"))return;const r=n.map(h=>h.value).join(""),o=this.parseStackParts(r);if(!o)return;const a=n[0];if(!a)return;const l={type:"stack",numerator:o.numerator,denominator:o.denominator,divider:o.divider,style:this.cloneDocumentStyle(a.style)};this.document.transaction(h=>{h.ast.nodes.splice(t,i-t,l),h.setSelection(t,t+1)}),this.syncUiStateFromDocument(),this.relayout()})}toggleScriptSelection(e){const t=this.getSelectionRange();if(t.isCollapsed)return!1;let i=!1;return this.commitHistoryEdit(()=>{var p;this.syncDocumentFromUiState();const n=this.toDocumentIndexFromLogicalIndex(t.start,!0),r=this.toDocumentIndexFromLogicalIndex(t.end,!1);if(r<=n)return;const o=this.document.ast.nodes.slice(n,r);if(o.length===1&&((p=o[0])==null?void 0:p.type)==="stack"){const m=o[0],g=this.scriptStackToPlainText(m.numerator,m.denominator,m.divider);if(!g)return;const f=this.cloneDocumentStyle(m.style);f.script="normal",f.align=D.MTextLineAlignment.MIDDLE;const w=Array.from(g).map(v=>({type:"char",value:v,style:this.cloneDocumentStyle(f)}));if(w.length===0)return;this.document.transaction(v=>{v.ast.nodes.splice(n,1,...w),v.setSelection(n,n+w.length)}),this.syncUiStateFromDocument(),this.relayout(),i=!0;return}if(!o.every(m=>(m==null?void 0:m.type)==="char"))return;const a=o.map(m=>m.value).join("");if(a.length===0)return;const l=o[0];if(!l)return;const c=this.cloneDocumentStyle(l.style);c.script=e,c.align=e==="superscript"?D.MTextLineAlignment.TOP:D.MTextLineAlignment.BOTTOM;const h={type:"stack",numerator:e==="superscript"?a:"",denominator:e==="subscript"?a:"",divider:"^",style:this.cloneDocumentStyle(c)};this.document.transaction(m=>{m.ast.nodes.splice(n,r-n,h),m.setSelection(n,n+1)}),this.syncUiStateFromDocument(),this.relayout(),i=!0}),i}commitHistoryEdit(e){const t=this.createHistorySnapshot();e(),!this.isSameAsCurrent(t)&&(this.undoStack.push(t),this.undoStack.length>this.maxHistorySize&&this.undoStack.splice(0,this.undoStack.length-this.maxHistorySize),this.redoStack=[],this.emit("change"),this.emit("selectionChange"),this.emit("cursorMove"))}createHistorySnapshot(){return{ast:this.cloneAst(this.document.ast),cursor:this.document.cursor,selection:this.document.selection?{...this.document.selection}:null,currentFormat:{...this.currentFormat}}}restoreHistorySnapshot(e){this.document=new pe(this.cloneAst(e.ast)),e.selection?this.document.setSelection(e.selection.start,e.selection.end):(this.document.cursor=e.cursor,this.document.clearSelection()),this.uiAdapter=new nr(this.document),this.currentFormat={...e.currentFormat},this.syncUiStateFromDocument(),this.relayout(),this.emit("change"),this.emit("selectionChange"),this.emit("cursorMove")}isSameAsCurrent(e){if(e.cursor!==this.document.cursor)return!1;const t=this.document.selection;return!!e.selection!=!!t||e.selection&&t&&(e.selection.start!==t.start||e.selection.end!==t.end)||!Ia(e.currentFormat,this.currentFormat)?!1:this.document.toMText()===this.buildMTextFromAst(e.ast)}buildMTextFromAst(e){return new pe(this.cloneAst(e)).toMText()}clearHistory(){this.undoStack=[],this.redoStack=[]}cloneAst(e){return{nodes:e.nodes.map(t=>t.type==="char"?{...t,style:this.cloneDocumentStyle(t.style)}:t.type==="stack"?{...t,style:this.cloneDocumentStyle(t.style)}:{...t,style:this.cloneDocumentStyle(t.style)})}}stackNodeToPlainText(e,t,i){if(i==="^"){if(e.length===0&&t.length>0)return`^${t.trimStart()}`;if(e.length>0&&t.length===0)return`${e.trimEnd()}^`}return`${e}${i}${t}`}scriptStackToPlainText(e,t,i){if(i!=="^")return null;const n=e.trim().length>0,r=t.trim().length>0;return n===r?null:n?e.trim():t.trim()}parseStackParts(e){const t=[];for(let l=0;l<e.length;l+=1){const c=e[l];(c==="/"||c==="#"||c==="^")&&t.push({index:l,divider:c})}if(t.length!==1)return null;const i=t[0];if(!i)return null;const{index:n,divider:r}=i,o=e.slice(0,n),a=e.slice(n+1);if(r==="^"){const l=o.trim().length>0,c=a.trim().length>0;return!l&&!c?null:{numerator:o,denominator:a,divider:r}}return o.trim().length===0||a.trim().length===0?null:{numerator:o,denominator:a,divider:r}}updateToolbarStackState(){var a;const e=this.getActiveToolbar();if(!e)return;const t=this.getSelectionRange();if(t.isCollapsed){e.setStackActive(!1);return}const i=this.toDocumentIndexFromLogicalIndex(t.start,!0),n=this.toDocumentIndexFromLogicalIndex(t.end,!1),r=this.document.ast.nodes.slice(i,n),o=r.length===1&&((a=r[0])==null?void 0:a.type)==="stack"&&!this.isScriptOnlyStack(r[0]);e.setStackActive(o)}isScriptOnlyStack(e){if(e.divider!=="^")return!1;const t=e.numerator.trim().length>0,i=e.denominator.trim().length>0;return t!==i}inferCurrentFormatFromDocument(){if(this.document.ast.nodes.length===0||this.getChars().length===0)return null;const n=this.selectionStart!==this.selectionEnd?Math.min(this.selectionStart,this.selectionEnd):this.cursorIndex>0?this.cursorIndex-1:0,r=this.getNodeByLogicalCharIndex(n);if(!r)return null;if(r.type==="stack"&&this.isScriptOnlyStack(r)){const o=r.numerator.trim().length>0?"superscript":"subscript";return{...this.toCharFormat(r.style),script:o}}return this.toCharFormat(r.style)}getNodeByLogicalCharIndex(e){const t=this.document.ast.nodes;if(t.length===0)return null;let i=0;const n=Math.max(0,e);for(const r of t){const o=this.getNodeLogicalSpan(r);if(n<i+o)return r;i+=o}return t[t.length-1]??null}getNodesByLogicalRange(e,t){const i=this.document.ast.nodes;if(i.length===0)return[];const n=Math.max(0,Math.min(e,t)),r=Math.max(n,Math.max(e,t));if(n===r)return[];const o=[];let a=0;for(const l of i){const c=this.getNodeLogicalSpan(l),h=a,p=a+c;c>0&&h<r&&p>n&&o.push(l),a=p}return o}toCharFormat(e){var v,x;const t=Math.max(1,this.defaultTextStyle.fixedTextHeight),i=e.capHeight.isRelative?t*Math.max(0,e.capHeight.value):e.capHeight.value,n=this.defaultTextStyle.font||this.baseFormat.fontFamily,r=e.rgb?this.rgbArrayToColorNumber(e.rgb):this.isExplicitAci(e.aci)?this.resolveAciColor(e.aci):this.resolveBaseColor(),o=this.isExplicitAci(e.aci)?e.aci:this.isExplicitAci(this.baseFormat.aci)?this.baseFormat.aci:null,a=this.toScriptFromStyle(e,t,i),l=Math.max(1,t)*.9,c=i<=l,h=a==="normal"?i:c?i/.7:i,p=(v=e.widthFactor)==null?void 0:v.value,m=typeof p=="number"&&Number.isFinite(p)?Math.max(.01,p):1,g=(x=e.charTrackingFactor)==null?void 0:x.value,f=typeof g=="number"&&Number.isFinite(g)?Math.max(.01,g):1,w=typeof e.oblique=="number"&&Number.isFinite(e.oblique)?e.oblique:0;return{fontFamily:e.fontFace.family||n,fontSize:Math.max(1,h||t),bold:e.fontFace.weight>=700,italic:e.fontFace.style==="Italic",underline:e.underline,overline:e.overline,strike:e.strikeThrough,script:a,aci:o,rgb:r,obliqueAngle:w,widthFactor:m,tracking:f,paragraphAlignment:e.paragraph.align}}toScriptFromStyle(e,t,i){const n=Math.max(1,t)*.9,r=i<=n;return e.script&&e.script!=="normal"?r?e.script:"normal":r&&e.align===D.MTextLineAlignment.TOP?"superscript":r&&e.align===D.MTextLineAlignment.BOTTOM?"subscript":"normal"}createDefaultParseContext(){const e=new D.MTextContext;if(e.fontFace.family=this.defaultTextStyle.font||this.baseFormat.fontFamily,e.fontFace.style=this.baseFormat.italic?"Italic":"Regular",e.fontFace.weight=this.baseFormat.bold?700:400,e.capHeight={value:this.defaultTextStyle.fixedTextHeight,isRelative:!1},e.align=D.MTextLineAlignment.BOTTOM,e.widthFactor={value:this.defaultTextStyle.widthFactor??1,isRelative:!1},this.isExplicitAci(this.baseFormat.aci))e.aci=this.baseFormat.aci,e.rgb=null;else{const t=this.resolveBaseColor();e.rgb=this.colorNumberToRgbArray(t),e.aci=256}return e}createNormalizedDocument(e){const t=pe.fromMText(e,this.createDefaultParseContext()),i={nodes:[]};for(const n of t.ast.nodes)switch(n.type){case"char":i.nodes.push({type:"char",value:n.value,style:this.cloneDocumentStyle(n.style)});break;case"stack":i.nodes.push({type:"stack",numerator:n.numerator,denominator:n.denominator,divider:n.divider,style:this.cloneDocumentStyle(n.style)});break;case"paragraphBreak":i.nodes.push({type:"paragraphBreak",style:this.cloneDocumentStyle(n.style)});break;case"columnBreak":case"wrapAtDimLine":i.nodes.push({type:"paragraphBreak",style:this.cloneDocumentStyle(n.style)});break}return new pe(i)}computeAttachmentAnchorOnBounds(e,t,i,n,r){const o=(e+t)*.5,a=(i+n)*.5,l=this.position.z;switch(r){case D.MTextAttachmentPoint.TopLeft:return new T.Vector3(e,n,l);case D.MTextAttachmentPoint.TopCenter:return new T.Vector3(o,n,l);case D.MTextAttachmentPoint.TopRight:return new T.Vector3(t,n,l);case D.MTextAttachmentPoint.MiddleLeft:return new T.Vector3(e,a,l);case D.MTextAttachmentPoint.MiddleCenter:return new T.Vector3(o,a,l);case D.MTextAttachmentPoint.MiddleRight:return new T.Vector3(t,a,l);case D.MTextAttachmentPoint.BottomLeft:case D.MTextAttachmentPoint.BaselineLeft:return new T.Vector3(e,i,l);case D.MTextAttachmentPoint.BottomCenter:case D.MTextAttachmentPoint.BaselineCenter:return new T.Vector3(o,i,l);case D.MTextAttachmentPoint.BottomRight:case D.MTextAttachmentPoint.BaselineRight:return new T.Vector3(t,i,l);default:return new T.Vector3(e,n,l)}}mapRibbonParagraphAlignment(e){switch(e){case"default":return D.MTextParagraphAlignment.DEFAULT;case"left":return D.MTextParagraphAlignment.LEFT;case"center":return D.MTextParagraphAlignment.CENTER;case"right":return D.MTextParagraphAlignment.RIGHT;case"justified":return D.MTextParagraphAlignment.JUSTIFIED;case"distributed":return D.MTextParagraphAlignment.DISTRIBUTED;default:return}}mapRibbonAttachmentCode(e){switch(e.trim().toUpperCase()){case"TL":return D.MTextAttachmentPoint.TopLeft;case"TC":return D.MTextAttachmentPoint.TopCenter;case"TR":return D.MTextAttachmentPoint.TopRight;case"ML":return D.MTextAttachmentPoint.MiddleLeft;case"MC":return D.MTextAttachmentPoint.MiddleCenter;case"MR":return D.MTextAttachmentPoint.MiddleRight;case"BL":return D.MTextAttachmentPoint.BottomLeft;case"BC":return D.MTextAttachmentPoint.BottomCenter;case"BR":return D.MTextAttachmentPoint.BottomRight;default:return}}attachmentPointToRibbonCode(e){switch(e){case D.MTextAttachmentPoint.TopLeft:return"TL";case D.MTextAttachmentPoint.TopCenter:return"TC";case D.MTextAttachmentPoint.TopRight:return"TR";case D.MTextAttachmentPoint.MiddleLeft:return"ML";case D.MTextAttachmentPoint.MiddleCenter:return"MC";case D.MTextAttachmentPoint.MiddleRight:return"MR";case D.MTextAttachmentPoint.BottomLeft:case D.MTextAttachmentPoint.BaselineLeft:return"BL";case D.MTextAttachmentPoint.BottomCenter:case D.MTextAttachmentPoint.BaselineCenter:return"BC";case D.MTextAttachmentPoint.BottomRight:case D.MTextAttachmentPoint.BaselineRight:return"BR";default:return"TL"}}mergeCharFormat(e,t){const i={...e,...t};if(t.aci!==void 0)if(!this.isExplicitAci(t.aci))i.aci=null;else{const n=this.resolveAciColor(t.aci);i.aci=t.aci,i.rgb=n}return t.rgb!==void 0&&(t.rgb===null?i.rgb=null:(i.rgb=this.normalizeColorNumber(t.rgb),t.aci===void 0&&(i.aci=null))),t.paragraphAlignment!==void 0&&(i.paragraphAlignment=t.paragraphAlignment),i}cloneDocumentStyle(e){return{underline:e.underline,overline:e.overline,strikeThrough:e.strikeThrough,script:e.script,aci:e.aci,rgb:e.rgb?[...e.rgb]:null,align:e.align,fontFace:{...e.fontFace},capHeight:{...e.capHeight},widthFactor:{...e.widthFactor},charTrackingFactor:{...e.charTrackingFactor},oblique:e.oblique,paragraph:{indent:e.paragraph.indent,left:e.paragraph.left,right:e.paragraph.right,align:e.paragraph.align,tabs:[...e.paragraph.tabs]}}}toDocumentStyle(e,t){const i=this.isExplicitAci(e.aci)?e.aci:null,n=i!==null?null:this.colorNumberToRgbArray(e.rgb!==null?e.rgb:this.resolveBaseColor()),r=e.script!=="normal",o=Math.max(1,e.fontSize*(r?.7:1)),a=e.script==="superscript"?D.MTextLineAlignment.TOP:e.script==="subscript"?D.MTextLineAlignment.BOTTOM:D.MTextLineAlignment.MIDDLE,l=e.paragraphAlignment;return{underline:e.underline,overline:e.overline,strikeThrough:e.strike,script:e.script,aci:i,rgb:n,align:a,fontFace:{family:e.fontFamily,style:e.italic?"Italic":"Regular",weight:e.bold?700:400},capHeight:{value:o,isRelative:!1},widthFactor:{value:Math.max(.01,e.widthFactor),isRelative:!1},charTrackingFactor:{value:Math.max(.01,e.tracking),isRelative:!1},oblique:e.obliqueAngle,paragraph:{indent:(t==null?void 0:t.paragraph.indent)??0,left:(t==null?void 0:t.paragraph.left)??0,right:(t==null?void 0:t.paragraph.right)??0,align:l,tabs:t!=null&&t.paragraph.tabs?[...t.paragraph.tabs]:[]}}}colorNumberToRgbArray(e){const t=this.normalizeColorNumber(e);return[t>>16&255,t>>8&255,t&255]}rgbArrayToColorNumber(e){const t=Math.max(0,Math.min(255,Math.round(e[0]))),i=Math.max(0,Math.min(255,Math.round(e[1]))),n=Math.max(0,Math.min(255,Math.round(e[2])));return t<<16|i<<8|n}};E(V,"activeEditor",null),E(V,"sharedToolbar",null),E(V,"sharedToolbarContainer",null),E(V,"sharedToolbarFontFamiliesKey",""),E(V,"sharedToolbarColorPickerFactory",null),E(V,"instances",new Set),E(V,"FALLBACK_LINE_ADVANCE_RATIO",1.5),E(V,"DEFAULT_TEXT_STYLE",{name:"MTextInputBoxStyle",standardFlag:0,fixedTextHeight:24,widthFactor:1,obliqueAngle:0,textGenerationFlag:0,lastHeight:24,font:hn,bigFont:""}),E(V,"DEFAULT_LINE_SPACE_FACTOR",.3);let rr=V;function zp(s){return u.acgiContrastingForegroundColor(s)}function Np(s){if(typeof s=="number")return s===1;if(typeof s=="boolean")return s;const e=String(s).toLowerCase();return e==="light"||e==="1"||e==="true"}function Ha(s){return s.currentSpaceId===s.tables.blockTable.modelSpace.objectId}function or(s){return s?u.AcDbSystemVariables.MODELBKCOLOR:u.AcDbSystemVariables.PAPERBKCOLOR}function Wa(s,e){const t=s==null?void 0:s.RGB;return t??(e?u.ACGI_MODEL_SPACE_BACKGROUND:u.ACGI_PAPER_SPACE_BACKGROUND)}function fn(s,e){const t=or(e),i=u.AcDbSysVarManager.instance().getVar(t,s);return Wa(i,e)}function $a(s){const e=s.RGB??u.ACGI_MODEL_SPACE_BACKGROUND,t=new u.AcCmColor(u.AcCmColorMethod.ByColor);return u.acgiIsLightBackground(e)?t.setRGB(0,0,0):t.setRGB(255,255,255),t}function bn(s){return u.acgiIsLightBackground(s)?"black":"white"}function Rp(s){if(s===void 0)return;const e=s;return e>=1&&e<=12?e:D.MTextAttachmentPoint.TopLeft}function bb(s){return s}const wn="__mlightcadMTextFormatBridge",q=class q{static setDefaultColorPicker(e){q.defaultColorPicker=e}static setDefaultToolbarEnabled(e){q.defaultToolbarEnabled=e}static getActiveInputBox(){return q.activeInputBox}static addActiveInputBoxChangeListener(e){q.activeInputBoxChangeListeners.add(e)}static removeActiveInputBoxChangeListener(e){q.activeInputBoxChangeListeners.delete(e)}static setActiveInputBox(e){q.activeInputBox!==e&&(q.activeInputBox=e,q.activeInputBoxChangeListeners.forEach(t=>{t(e)}))}static createHiddenToolbarContainer(e){const t=e.ownerDocument.createElement("div");return t.setAttribute("aria-hidden","true"),Object.assign(t.style,{display:"none",pointerEvents:"none"}),e.appendChild(t),t}static attachFormatBridge(e){const t=e;if(t[wn])return;const i=new Set,n=[],r=()=>{i.forEach(a=>{a()})},o=a=>{const l=t[a];typeof l=="function"&&(t[a]=(...c)=>{const h=l.apply(t,c);return r(),h},n.push(()=>{t[a]=l}))};["setCurrentFormat","refreshCurrentFormatFromDocument","toggleCase","toggleStackSelection","toggleScriptSelection","setParagraphAlignment","setAttachmentPoint","setLineSpacingFactor","clearLineSpacing"].forEach(o),t.addCurrentFormatChangeListener=a=>{i.add(a)},t.removeCurrentFormatChangeListener=a=>{i.delete(a)},t.focusEditor=()=>{const a=t,l=a.focusImeInput;if(typeof l=="function"){l.call(t);return}const c=a.refocusImeInputSoon;typeof c=="function"&&c.call(t)},t.isStackSelectionActive=()=>{var P,A;const a=t,l=a.getSelectionRange,c=a.toDocumentIndexFromLogicalIndex,h=a.isScriptOnlyStack,p=a.document;if(typeof l!="function"||typeof c!="function")return!1;const m=l.call(t);if(!m||m.isCollapsed)return!1;const g=c.call(t,m.start,!0),f=c.call(t,m.end,!1),w=((A=(P=p==null?void 0:p.ast)==null?void 0:P.nodes)==null?void 0:A.slice(g,f))??[],v=w[0];if(w.length!==1||(v==null?void 0:v.type)!=="stack")return!1;if(typeof h=="function")return!h.call(t,v);if(v.divider!=="^")return!0;const x=(v.numerator??"").trim().length>0,S=(v.denominator??"").trim().length>0;return x===S},t[wn]={addCurrentFormatChangeListener:t.addCurrentFormatChangeListener,removeCurrentFormatChangeListener:t.removeCurrentFormatChangeListener,dispose:()=>{n.forEach(a=>{a()}),i.clear(),delete t.addCurrentFormatChangeListener,delete t.removeCurrentFormatChangeListener,delete t.focusEditor,delete t.isStackSelectionActive,delete t[wn]}}}static detachFormatBridge(e){var i;(i=e[wn])==null||i.dispose()}open(e){const{view:t,location:i,width:n,textHeight:r,initialText:o="",toolbarFontFamilies:a=[],toolbarColorPicker:l,toolbarEnabled:c=q.defaultToolbarEnabled,initialAttachmentPoint:h}=e,p=new T.Vector3(i.x,i.y,i.z??0),g=u.acgiIsLightBackground(t.backgroundColor)?"#000000":"#ffffff",f=k.instance,w=f.curDocument.database,{layerColor:v}=f.resolveColors(),x=()=>{const N=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.COLORTHEME,w);return N===0||N==="0"||N===!1||N==="dark"?"dark":"light"},S=Array.from(new Set(a.map(N=>N.trim()).filter(N=>N.length>0))),P=()=>{const N=w.tables.textStyleTable.getAt(w.textstyle);return N==null?void 0:N.textStyle},A=Math.max(1,r),_=P(),C=_?{..._,fixedTextHeight:A,lastHeight:A}:void 0,O=c?null:q.createHiddenToolbarContainer(t.container),j=Rp(h),L=new rr({scene:t.internalScene,camera:t.internalCamera,width:n,position:p.clone(),initialText:o,...j!==void 0?{initialAttachmentPoint:j}:{},textStyle:C,cursorStyle:{color:g,glowColor:g},boundingBoxStyle:{padding:0},imeTarget:t.canvas,colorSettings:{layer:w.clayer,color:new D.MTextColor,byLayerColor:v,byBlockColor:v},toolbar:{enabled:!0,theme:x(),fontFamilies:S,container:O??t.container,offsetY:10,colorPicker:l??q.defaultColorPicker??void 0}});return q.attachFormatBridge(L),q.setActiveInputBox(L),new Promise(N=>{let R=!1;const W=()=>{R||(L.update(),t.isHtmlDirty=!0)},X=re=>{re.name.toLowerCase()===u.AcDbSystemVariables.COLORTHEME.toLowerCase()&&(L.setToolbarTheme(x()),t.isHtmlDirty=!0)},$=()=>{q.activeInputBox===L&&q.setActiveInputBox(null),q.detachFormatBridge(L),L.dispose(),O==null||O.remove(),t.events.renderFrame.removeEventListener(W),L.off("close",se),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(X),t.isHtmlDirty=!0},J=re=>{R||(R=!0,$(),N(re))},se=()=>{var Mt;const re=L.getMTextInsertionPoint();J({contents:L.getText(),location:{x:re.x,y:re.y,z:re.z},width:n,height:A,lineSpacingFactor:((Mt=L.getLineSpacingFactor)==null?void 0:Mt.call(L))??q.defaultLineSpacingFactor,attachmentPoint:L.getMTextAttachmentPoint()})};L.on("close",se),t.events.renderFrame.addEventListener(W),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(X)})}};q.defaultLineSpacingFactor=.3,q.activeInputBox=null,q.activeInputBoxChangeListeners=new Set,q.defaultColorPicker=null,q.defaultToolbarEnabled=!0;let Ke=q;const Es=class Es{constructor(e){this.view=e}handleKeyDown(e){const t=this.resolveUndoRedoShortcut(e);if(this.shouldIgnoreEditableTargetShortcut(e)&&!t)return!1;if(t)return!this.shouldHandleUndoRedoShortcut(e)||Ke.getActiveInputBox()||this.view.editor.isActive?!1:(k.instance.sendStringToExecute(t),e.preventDefault(),!0);switch(e.code){case"Escape":return this.view.selectionSet.clear(),this.view.htmlTransientManager.deselectAll(),this.view.isHtmlDirty=!0,!1;case"Delete":case"Backspace":if(!this.view.editor.isActive){let n=!1;const r=this.view.htmlTransientManager;if(r.hasSelection()){const o=r.getSelectedGroups(),a=o.filter(c=>c.layer===Y);a.length>0&&Bt(this.view,"Delete Measurement",()=>{for(const c of a)r.detach(c.id)&&(n=!0)}),(o.some(c=>c.layer!==Y)||o.length===0&&r.hasSelection())&&ve(this.view,"Delete Markup",()=>{n=r.deleteSelected()||n})}if(n)return this.view.isHtmlDirty=!0,e.preventDefault(),!0;k.instance.sendStringToExecute("erase")}return!1}return!1}resolveUndoRedoShortcut(e){return!e.ctrlKey&&!e.metaKey?null:e.code==="KeyY"?"redo":e.code==="KeyZ"?e.shiftKey?"redo":"undo":null}shouldIgnoreEditableTargetShortcut(e){if(e.isComposing||e.keyCode===229)return!0;const t=e.target;return(t==null?void 0:t.tagName)==="TEXTAREA"||t!=null&&t.isContentEditable?!0:(t==null?void 0:t.tagName)==="INPUT"}shouldHandleUndoRedoShortcut(e){if(e.isComposing||e.keyCode===229)return!1;const t=e.target;if((t==null?void 0:t.tagName)==="TEXTAREA"||t!=null&&t.isContentEditable)return!1;if((t==null?void 0:t.tagName)==="INPUT"){const i=t;return i.classList.contains(Es.COMMAND_LINE_INPUT_CLASS)?i.value.trim()===""&&!i.readOnly:!1}return!0}};Es.COMMAND_LINE_INPUT_CLASS="ml-cli-text";let vn=Es;function Vp(s){return s.directBatchPrimitive!=null}function Ya(s,e){if(s.directBatchPrimitive==null)return null;e.beginDirectCapture();let t;try{t=s.worldDraw(e);const i=e.takeDirectCapture();if(!i)return null;const n=Gp(i,e);return n?n.wcsBbox.isEmpty()||e.batchDrawPolicy.resolveDrawMode({anchor:M.resolveAnchorFromBox(n.wcsBbox),position:n.position})==="unbatch"?(n.geometry.dispose(),null):{...n,objectId:s.objectId,ownerId:s.ownerId,layerName:s.layer,visible:s.visibility!==!1}:null}catch(i){throw e.cancelDirectCapture(),i}finally{t==null||t.dispose()}}function Za(s){return!(s instanceof u.AcDbRay||s instanceof u.AcDbXline)}function Gp(s,e){const t=e.subEntityTraits;if(s.kind==="lineStrip"){const i=e.styleManager.getLineMaterial(t,!1);if(M.isDirectBatchRejectedMaterial(i))return null;const n=M.buildLineGeometry(s.points,i);return n?{kind:n.kind==="fat"?"lineFat":"lineBasic",geometry:n.geometry,worldOffset:n.worldOffset,wcsBbox:n.wcsBbox,material:n.material}:null}if(s.kind==="lineSegments"){const i=e.styleManager.getLineMaterial(t,!1);return M.buildLineSegmentsGeometry(s.array,s.itemSize,s.indices,i)}if(s.kind==="point"){const i=e.styleManager.getPointsMaterial(t);return M.isDirectBatchRejectedMaterial(i)?null:M.buildPointGeometry(s.point,i)}if(s.kind==="area"){const i=M.buildAreaGeometry(s.area,t,e.context);return i?M.isDirectBatchRejectedMaterial(i.material)?(i.geometry.dispose(),null):i:null}return null}class Xa{constructor(e,t){this.getLayerTraits=e,this.renderer=t}remap(e,t,i){if(t===i)return;const n=this.getLayerTraits(i);for(const r of e)r.traverse(o=>{const a=o.userData.layerName===t;if(a&&(o.userData.layerName=i),!("material"in o)||!a)return;const l=o.material;if(Array.isArray(l)){const h=l;o.material=h.map(p=>this.shouldRemap(p,t)?this.renderer.getLayerBoundMaterial(this.promoteLayerZeroByLayerColor(p,t),i,n)??p:p),M.syncStyleMaterialIdFromMaterials(M.getSceneDrawableUserData(o),o.material);return}if(!this.shouldRemap(l,t))return;const c=this.renderer.getLayerBoundMaterial(this.promoteLayerZeroByLayerColor(l,t),i,n);c&&(o.material=c,M.syncStyleMaterialIdFromMaterials(M.getSceneDrawableUserData(o),c))})}shouldRemap(e,t){const i=M.getMaterialMetadata(e);return i.isForeground!==!0?!0:t!=="0"?!1:i.isByLayerColor===!0?!0:t==="0"&&(i.isByLayerLineType===!0||i.isByLayerLineWeight===!0||i.isByLayerTransparency===!0)}promoteLayerZeroByLayerColor(e,t){const i=M.getMaterialMetadata(e),n=M.hasByLayerBinding(i)&&i.isByLayerColor!==!0;return t==="0"&&n&&M.setMaterialMetadata(e,{isByLayerColor:!0}),e}}const ar=1,Nt=4;function lr(s){return{isOff:s.isOff,isFrozen:s.isFrozen,isLocked:((s.standardFlags??0)&Nt)!==0}}function qa(s,e){return s.isOff===e.isOff&&s.isFrozen===e.isFrozen&&s.isLocked===e.isLocked}const H="Layer",Ja="Entity";function K(s,e,t){var n;if((n=s.transactionManager)!=null&&n.hasTransaction())return t();if(typeof s.runDatabaseEdit!="function")return process.env.NODE_ENV!=="production"&&console.warn(`[cad-simple-viewer] acapRunServiceEdit("${e}"): database.runDatabaseEdit is unavailable; mutation ran without undo support.`),t();let i;return ct(s,e,()=>{i=t()}),i}const B=class B{constructor(e){this.db=e}static openLayerForWrite(e,t){const i=typeof t=="string"?e.tables.layerTable.getAt(t):t;if(i)return B.registerLayerTableRecordForWrite(e,i),i}static registerLayerTableRecordForWrite(e,t){var o,a;const i=e.transactionManager;if(!((o=i==null?void 0:i.isRecording)!=null&&o.call(i)))return;const n=(a=i.currentTransaction)==null?void 0:a.call(i);if(!n)return;B.ensureLayerUndoHooks(e);const r=t.objectId;n.openedObjects.set(r,t),n.recorder.hasModify(r)||(n.originalStates.set(r,t.clonePreservingIdentity()),n.recorder.recordModify(t)),e.getObjectById(r)!==t&&B.ensureLayerFinalizeHook(n)}static resolveLayerForHandleCollision(e,t){var r;const i=(r=t.before)==null?void 0:r.name;if(typeof i!="string")return;const n=e.tables.layerTable.getAt(i);if(!(!n||e.getObjectById(t.objectId)===n))return n}static ensureLayerUndoHooks(e){const i=e.transactionManager.changeApplier;if(!i||B.patchedChangeAppliers.has(i))return;const n=i.applyModify.bind(i);i.applyModify=(r,o)=>{const a=B.resolveLayerForHandleCollision(e,r);if(a){const l=o?r.after:r.before;if(l){a.restoreFrom(l);return}}n(r,o)},B.patchedChangeAppliers.add(i)}static ensureLayerFinalizeHook(e){const t=e.recorder;if(t.__layerFinalizePatched||typeof t.finalize!="function")return;const i=t.finalize.bind(t);t.finalize=n=>{i(n);for(const r of t.getChanges()){if(r.kind!=="modify")continue;const o=e.openedObjects.get(r.objectId);if(!o||n.getObjectById(r.objectId)===o)continue;const a=B.resolveLayerForHandleCollision(n,r);a&&(r.after=a.clonePreservingIdentity())}},t.__layerFinalizePatched=!0}static syncLayerModifiedEvent(e,t,i){Object.keys(i).length!==0&&e.getObjectById(t.objectId)!==t&&e.events.layerModified.dispatch({database:e,layer:t,changes:i})}static setLayerFrozenState(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|ar:i&~ar}static setLayerLockedState(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|Nt:i&~Nt}static isLayerLocked(e){return((e.standardFlags??0)&Nt)!==0}static applyLayerPreviousSnapshot(e,t){t.states.forEach(n=>{const r=B.openLayerForWrite(e,n.name);r&&(r.isOff=!n.isOn,B.setLayerFrozenState(r,n.isFrozen),B.setLayerLockedState(r,n.isLocked))});const i=B.openLayerForWrite(e,t.clayer);return i?(i.isOff=!1,B.setLayerFrozenState(i,!1),e.clayer=i.name,!0):!1}parseLayerNameInput(e){const t=[...this.db.tables.layerTable.newIterator()].map(r=>r.name),i=e.trim();if(!i)return[];if(i==="*")return[...t];const n=i.split(",").map(r=>r.trim()).filter(Boolean);return[...new Set(n)]}resolveLayers(e){const t=this.db.tables.layerTable,i=[],n=[];return e.forEach(r=>{const o=t.getAt(r);o?i.push(o):n.push(r)}),{layers:i,missing:n}}getLayerSummaries(){return[...this.db.tables.layerTable.newIterator()].map(e=>({name:e.name,current:this.db.clayer===e.name?"*":"",on:e.isOff?"No":"Yes",frozen:e.isFrozen?"Yes":"No",locked:B.isLayerLocked(e)?"Yes":"No",color:e.color.toString()}))}createLayers(e){return K(this.db,H,()=>{const t=this.db.tables.layerTable;let i=0;const n=[];return e.forEach(r=>{if(t.has(r)){n.push(r);return}t.add(new u.AcDbLayerTableRecord({name:r,isOff:!1,isPlottable:!0,color:new u.AcCmColor(u.AcCmColorMethod.ByACI,7),linetype:"Continuous"})),i++}),{created:i,existed:n}})}setCurrentLayer(e){const t=this.db.tables.layerTable.getAt(e);return t?K(this.db,H,()=>{const i=B.openLayerForWrite(this.db,t);return i?(i.isOff=!1,B.setLayerFrozenState(i,!1),this.db.clayer=i.name,!0):!1}):!1}makeLayer(e){return K(this.db,H,()=>{const t=this.db.tables.layerTable;let i=t.getAt(e);i||(i=new u.AcDbLayerTableRecord({name:e,isOff:!1,isPlottable:!0,color:new u.AcCmColor(u.AcCmColorMethod.ByACI,7),linetype:"Continuous"}),t.add(i));const n=B.openLayerForWrite(this.db,i);return n?(n.isOff=!1,B.setLayerFrozenState(n,!1),this.db.clayer=n.name,!0):!1})}setLayerOn(e,t,i={}){if(!e||!this.db.tables.layerTable.getAt(e))return!1;const n=i.switchCurrentLayer??!1;return K(this.db,H,()=>{if(!t&&n&&!this.switchCurrentLayerIfNeeded(e))return!1;const r=B.openLayerForWrite(this.db,e);return r?(r.isOff=!t,B.syncLayerModifiedEvent(this.db,r,{isOff:r.isOff}),!0):!1})}setLayerFrozen(e,t,i={}){if(!e||!this.db.tables.layerTable.getAt(e))return!1;const n=i.switchCurrentLayer??!1;return K(this.db,H,()=>{if(t&&n&&!this.switchCurrentLayerIfNeeded(e))return!1;const r=B.openLayerForWrite(this.db,e);return r?(B.setLayerFrozenState(r,t),B.syncLayerModifiedEvent(this.db,r,{standardFlags:r.standardFlags}),!0):!1})}setLayerLocked(e,t){return!e||!this.db.tables.layerTable.getAt(e)?!1:K(this.db,H,()=>{const i=B.openLayerForWrite(this.db,e);return i?(B.setLayerLockedState(i,t),B.syncLayerModifiedEvent(this.db,i,{standardFlags:i.standardFlags}),!0):!1})}setLayerLineWeight(e,t){return this.db.tables.layerTable.getAt(e)?K(this.db,H,()=>{const i=B.openLayerForWrite(this.db,e);return i?(i.lineWeight=t,!0):!1}):!1}setLayerPlottable(e,t){return this.db.tables.layerTable.getAt(e)?K(this.db,H,()=>{const i=B.openLayerForWrite(this.db,e);return i?(i.isPlottable=t,!0):!1}):!1}setLayerLinetype(e,t){return!t||!this.db.tables.layerTable.getAt(e)?!1:K(this.db,H,()=>{const i=B.openLayerForWrite(this.db,e);return i?(i.linetype=t,!0):!1})}setLayerTransparency(e,t){return this.db.tables.layerTable.getAt(e)?K(this.db,H,()=>{const i=B.openLayerForWrite(this.db,e);return i?(i.transparency=t,!0):!1}):!1}isolateSingleLayer(e){return this.db.tables.layerTable.getAt(e)?K(this.db,H,()=>{for(const t of this.db.tables.layerTable.newIterator()){const i=B.openLayerForWrite(this.db,t);if(!i)continue;const n=i.name===e;i.isOff=!n,n&&B.setLayerFrozenState(i,!1)}return this.db.clayer=e,!0}):!1}setLayersVisibility(e,t,i={}){const n=i.skipCurrentLayer??!0,{layers:r}=this.resolveLayers(e),o=[];return K(this.db,H,()=>{r.forEach(a=>{if(t&&n&&a.name===this.db.clayer){o.push(a.name);return}const l=B.openLayerForWrite(this.db,a);l&&(l.isOff=t,B.syncLayerModifiedEvent(this.db,l,{isOff:l.isOff}))})}),{skippedCurrent:o}}setAllLayersOn(){return K(this.db,H,()=>{let e=0;for(const t of this.db.tables.layerTable.newIterator()){if(!t.isOff)continue;const i=B.openLayerForWrite(this.db,t);i&&(i.isOff=!1,e++)}return e})}setAllLayersOffExceptCurrent(){return K(this.db,H,()=>{const e=this.db.clayer;let t=0;for(const i of this.db.tables.layerTable.newIterator()){if(i.name===e||i.isOff)continue;const n=B.openLayerForWrite(this.db,i);n&&(n.isOff=!0,t++)}return t})}setLayersFrozen(e,t,i={}){const n=i.skipCurrentLayer??!0,{layers:r}=this.resolveLayers(e),o=[];return K(this.db,H,()=>{r.forEach(a=>{if(t&&n&&a.name===this.db.clayer){o.push(a.name);return}const l=B.openLayerForWrite(this.db,a);l&&(B.setLayerFrozenState(l,t),B.syncLayerModifiedEvent(this.db,l,{standardFlags:l.standardFlags}))})}),{skippedCurrent:o}}thawAllLayers(){return K(this.db,H,()=>{let e=0;for(const t of this.db.tables.layerTable.newIterator()){if(!t.isFrozen)continue;const i=B.openLayerForWrite(this.db,t);i&&(B.setLayerFrozenState(i,!1),B.syncLayerModifiedEvent(this.db,i,{standardFlags:i.standardFlags}),e++)}return e})}setLayersLocked(e,t){const{layers:i}=this.resolveLayers(e);K(this.db,H,()=>{i.forEach(n=>{const r=B.openLayerForWrite(this.db,n);r&&(B.setLayerLockedState(r,t),B.syncLayerModifiedEvent(this.db,r,{standardFlags:r.standardFlags}))})})}parseColorInput(e){const t=e.trim();if(!t)return;if(/^\d+$/.test(t)){const n=Number(t);return n>=1&&n<=255?new u.AcCmColor(u.AcCmColorMethod.ByACI,n):void 0}const i=u.AcCmColor.fromString(t);if(i){if(i.isByACI){const n=i.colorIndex;if(n==null||n<1||n>255)return}if(!(i.isByLayer||i.isByBlock))return i}}setLayerColor(e,t){return this.db.tables.layerTable.getAt(e)?K(this.db,H,()=>{const i=B.openLayerForWrite(this.db,e);return i?(i.color=t.clone(),!0):!1}):!1}setLayersColor(e,t){const{layers:i}=this.resolveLayers(e);K(this.db,H,()=>{i.forEach(n=>{const r=B.openLayerForWrite(this.db,n);r&&(r.color=t.clone())})})}setLayerDescription(e,t){const i=this.db.tables.layerTable.getAt(e);return i?K(this.db,H,()=>{const n=B.openLayerForWrite(this.db,i);return n?(n.description=t,!0):!1}):!1}switchCurrentLayerIfNeeded(e){if(this.db.clayer!==e)return!0;let t,i;for(const o of this.db.tables.layerTable.newIterator())if(o.name!==e&&(t??(t=o.name),!o.isOff&&!o.isFrozen)){i=o.name;break}const n=i??t;if(!n)return!1;const r=B.openLayerForWrite(this.db,n);return r?(r.isOff=!1,B.setLayerFrozenState(r,!1),this.db.clayer=r.name,!0):!1}getLayerNameFromEntity(e){var i;const t=this.db.tables.blockTable.getEntityById(e);return((i=t==null?void 0:t.layer)==null?void 0:i.trim())||void 0}collectLayerNamesFromEntities(e){const t=new Set,i=new Set;return e.forEach(n=>{const r=this.getLayerNameFromEntity(n);if(!r)return;const o=this.db.tables.layerTable.getAt(r);o?t.add(o.name):i.add(r)}),{layerNames:[...t],missingLayerNames:[...i]}}freezeLayerByEntity(e){const t=this.getLayerNameFromEntity(e);if(!t)return{ok:!1,reason:"invalid_selection"};const i=this.db.tables.layerTable.getAt(t);if(!i)return{ok:!1,reason:"layer_not_found",layerName:t};if(i.name===this.db.clayer)return{ok:!1,reason:"cannot_change_current",layerName:t};if(i.isFrozen)return{ok:!1,reason:"already_frozen",layerName:t};const n=i.isFrozen;return K(this.db,H,()=>{const r=B.openLayerForWrite(this.db,i);r&&B.setLayerFrozenState(r,!0)}),{ok:!0,layerName:t,previousFrozen:n}}setLayerFrozenByName(e,t){const i=this.db.tables.layerTable.getAt(e);return i?K(this.db,H,()=>{const n=B.openLayerForWrite(this.db,i);return n?(B.setLayerFrozenState(n,t),!0):!1}):!1}turnOffLayerByEntity(e){const t=this.getLayerNameFromEntity(e);if(!t)return{ok:!1,reason:"invalid_selection"};const i=this.db.tables.layerTable.getAt(t);if(!i)return{ok:!1,reason:"layer_not_found",layerName:t};if(i.name===this.db.clayer)return{ok:!1,reason:"cannot_change_current",layerName:t};if(i.isOff)return{ok:!1,reason:"already_off",layerName:t};const n=i.isOff;return K(this.db,H,()=>{const r=B.openLayerForWrite(this.db,i);r&&(r.isOff=!0)}),{ok:!0,layerName:t,previousOff:n}}setLayerOffByName(e,t){const i=this.db.tables.layerTable.getAt(e);return i?K(this.db,H,()=>{const n=B.openLayerForWrite(this.db,i);return n?(n.isOff=t,!0):!1}):!1}lockLayerByEntity(e){const t=this.getLayerNameFromEntity(e);if(!t)return{ok:!1,reason:"invalid_selection"};const i=this.db.tables.layerTable.getAt(t);return i?B.isLayerLocked(i)?{ok:!1,reason:"already_locked",layerName:t}:(K(this.db,H,()=>{const n=B.openLayerForWrite(this.db,i);n&&B.setLayerLockedState(n,!0)}),{ok:!0,layerName:t}):{ok:!1,reason:"layer_not_found",layerName:t}}unlockLayerByEntity(e){const t=this.getLayerNameFromEntity(e);if(!t)return{ok:!1,reason:"invalid_selection"};const i=this.db.tables.layerTable.getAt(t);return i?B.isLayerLocked(i)?(K(this.db,H,()=>{const n=B.openLayerForWrite(this.db,i);n&&B.setLayerLockedState(n,!1)}),{ok:!0,layerName:t}):{ok:!1,reason:"already_unlocked",layerName:t}:{ok:!1,reason:"layer_not_found",layerName:t}}isolateLayers(e,t){if(e.length!==0)return K(this.db,H,()=>{const i=this.db.tables.layerTable,n=new Set(e),r=i.getAt(e[0]),o=this.db.clayer,a=new Map;for(const p of i.newIterator())a.set(p.name,lr(p));r&&(this.db.clayer=r.name);const l=new Set;for(const p of i.newIterator()){const m=B.openLayerForWrite(this.db,p);if(m){if(n.has(m.name)){m.isOff&&(m.isOff=!1,l.add(m.name)),m.isFrozen&&(B.setLayerFrozenState(m,!1),l.add(m.name)),B.isLayerLocked(m)&&(B.setLayerLockedState(m,!1),l.add(m.name));continue}if(t==="Off"){m.isOff||(m.isOff=!0,l.add(m.name));continue}B.isLayerLocked(m)||(B.setLayerLockedState(m,!0),l.add(m.name))}}const c=[];for(const p of i.newIterator()){const m=a.get(p.name);if(!m)continue;const g=lr(p);qa(m,g)||c.push({name:p.name,before:m,isolated:g})}const h={currentLayerBefore:o,currentLayerAfter:this.db.clayer,layers:c};return{layerNames:e,affectedLayerCount:l.size,isoSnapshot:h}})}unisolateFromSnapshot(e){return K(this.db,H,()=>{const t=this.db.tables.layerTable;let i=0;for(const n of e.layers)t.getAt(n.name)&&this.restoreLayerIfUnchanged(n)&&i++;return this.db.clayer===e.currentLayerAfter&&e.currentLayerBefore!==e.currentLayerAfter&&t.getAt(e.currentLayerBefore)&&(this.db.clayer=e.currentLayerBefore),i})}collectLayerEntities(e){const t=[];for(const i of this.db.tables.blockTable.newIterator())for(const n of i.newIterator())n.layer===e&&t.push({ownerId:i.objectId,objectId:n.objectId,entity:n.clone()});return t}removeLayerEntities(e){const t=new Map;e.forEach(({ownerId:i,objectId:n})=>{const r=t.get(i)??[];r.push(n),t.set(i,r)}),t.forEach((i,n)=>{var r;(r=this.db.tables.blockTable.getIdAt(n))==null||r.removeEntity(i)})}deleteLayer(e){const t=this.db.tables.layerTable.getAt(e);return t?t.name==="0"?{ok:!1,reason:"layer_0",layerName:e}:t.name===this.db.clayer?{ok:!1,reason:"current_layer",layerName:e}:K(this.db,H,()=>{const i=this.collectLayerEntities(t.name);this.removeLayerEntities(i);const n=t.clone();return this.db.tables.layerTable.remove(t.name),this.db.events.layerErased.dispatch({database:this.db,layer:t}),{ok:!0,layerName:t.name,layer:n,entities:i}}):{ok:!1,reason:"not_found",layerName:e}}restoreDeletedLayer(e,t){K(this.db,H,()=>{this.db.tables.layerTable.has(e.name)||this.db.tables.layerTable.add(e.clone());const i=new Map;t.forEach(({ownerId:n,entity:r})=>{const o=i.get(n)??[];o.push(r.clone()),i.set(n,o)}),i.forEach((n,r)=>{(this.db.tables.blockTable.getIdAt(r)??this.db.tables.blockTable.modelSpace).appendEntity(n)})})}restoreLayerIfUnchanged(e){const t=this.db.tables.layerTable.getAt(e.name);if(!t)return!1;const i=B.openLayerForWrite(this.db,t);if(!i)return!1;let n=!1;return i.isOff===e.isolated.isOff&&i.isOff!==e.before.isOff&&(i.isOff=e.before.isOff,n=!0),i.isFrozen===e.isolated.isFrozen&&i.isFrozen!==e.before.isFrozen&&(B.setLayerFrozenState(i,e.before.isFrozen),n=!0),B.isLayerLocked(i)===e.isolated.isLocked&&B.isLayerLocked(i)!==e.before.isLocked&&(B.setLayerLockedState(i,e.before.isLocked),n=!0),n}getEffectiveLayerTraits(e){return B.resolveLayerTraits(this.db,e)}static resolveLayerTraits(e,t){const i=e.tables.layerTable.getAt(t);if(i)return{layer:i.name,color:i.color.clone(),lineType:i.lineStyle,lineWeight:i.lineWeight,transparency:i.transparency}}};B.patchedChangeAppliers=new WeakSet;let te=B;class Qa{constructor(e,t,i){this.scene=e,this.renderer=t,this.getLayerTraits=i}layerStyleMayHaveChanged(e){return e.color!=null||e.linetype!=null||e.lineWeight!==void 0||e.transparency!=null}syncFromLiveRecord(e){const t=this.getEffectiveLayerTraits(e.name);if(!t)return;const i=this.renderer.updateLayerMaterial(e.name,t);this.scene.forEachSceneLayer(e.name,n=>n.syncAppearanceFromRecord(e.name,t,i,this.renderer))}refreshTextMaterialsInObjectTree(e,t){e.traverse(i=>{const n=i.refreshTextMaterials;typeof n=="function"&&n.call(i,t)})}getEffectiveLayerTraits(e){if(this.getLayerTraits)return this.getLayerTraits(e);const t=this.renderer.context.database;if(t)return te.resolveLayerTraits(t,e)}}const Rt=1e-5;function mi(s){return Number.isFinite(s.minX)&&Number.isFinite(s.minY)&&Number.isFinite(s.maxX)&&Number.isFinite(s.maxY)}function cr(s){const e=new T.Box3;for(const t of s.wcsChildBoxes)mi(t)&&e.union(new T.Box3(new T.Vector3(t.minX,t.minY,0),new T.Vector3(t.maxX,t.maxY,0)));return e}function Kp(s){if(s.wcsChildBoxes.length===0)return;const e=cr(s),t=s.wcsBbox;if(!(Math.abs(t.min.x-e.min.x)<=Rt&&Math.abs(t.min.y-e.min.y)<=Rt&&Math.abs(t.min.z-e.min.z)<=Rt&&Math.abs(t.max.x-e.max.x)<=Rt&&Math.abs(t.max.y-e.max.y)<=Rt&&Math.abs(t.max.z-e.max.z)<=Rt))throw new Error(`[AcTrView2d] Group wcsBbox [${t.min.x}, ${t.min.y}]–[${t.max.x}, ${t.max.y}] does not match wcsChildBoxes union [${e.min.x}, ${e.min.y}]–[${e.max.x}, ${e.max.y}]. Ensure AcDbRenderingCache.draw applied the INSERT transform before handleGroup.`)}function Up(s){Kp(s)}function kn(s,e){var o;let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const a of s)mi(a)&&(t=Math.min(t,a.minX),i=Math.min(i,a.minY),n=Math.max(n,a.maxX),r=Math.max(r,a.maxY));return{minX:t,minY:i,maxX:n,maxY:r,id:e??((o=s[0])==null?void 0:o.id)??""}}function xn(s){return!(s.children!==void 0&&s.children.length===0)}function el(s){const e=new Map;return s.map(t=>{const i=t.id;if(typeof i!="string"||i.length===0)return t;const n=e.get(i)??0;return e.set(i,n+1),n===0?t:{...t,id:`${i}#${n}`}})}const Hp=40;class Wp{constructor(){this.items=new Map,this.anonKeySeq=0}storageKey(e){return typeof e.id=="string"&&e.id.length>0?e.id:`__anon_${this.anonKeySeq++}`}insert(e){if(typeof e.id=="string"&&e.id.length>0){this.items.set(e.id,e);return}this.items.set(this.storageKey(e),e)}load(e){for(const t of e)this.insert(t)}remove(e){if(typeof e.id=="string"&&e.id.length>0){this.items.delete(e.id);return}for(const[t,i]of this.items)if(i===e||i.id===e.id&&i.minX===e.minX&&i.minY===e.minY&&i.maxX===e.maxX&&i.maxY===e.maxY){this.items.delete(t);return}}removeById(e){typeof e=="string"&&e.length>0&&this.items.delete(e)}clear(){this.items.clear()}search(e,t){const i=[];for(const n of this.items.values())tl(n,e)&&((t==null?void 0:t.selectionMode)==="window"&&!zt(n,e)||i.push(n));return i}collides(e){for(const t of this.items.values())if(tl(t,e))return!0;return!1}all(){return Array.from(this.items.values())}getStats(){const e=this.all(),t=e.length;return{kind:"linear",itemCount:t,estimatedBytes:Pa(e)+t*Hp}}}function tl(s,e){return!(s.maxX<e.minX||s.minX>e.maxX||s.maxY<e.minY||s.minY>e.maxY)}function il(s,e,t=0,i=s.length-1,n=$p){for(;i>t;){if(i-t>600){const l=i-t+1,c=e-t+1,h=Math.log(l),p=.5*Math.exp(2*h/3),m=.5*Math.sqrt(h*p*(l-p)/l)*(c-l/2<0?-1:1),g=Math.max(t,Math.floor(e-c*p/l+m)),f=Math.min(i,Math.floor(e+(l-c)*p/l+m));il(s,e,g,f,n)}const r=s[e];let o=t,a=i;for(yi(s,t,e),n(s[i],r)>0&&yi(s,t,i);o<a;){for(yi(s,o,a),o++,a--;n(s[o],r)<0;)o++;for(;n(s[a],r)>0;)a--}n(s[t],r)===0?yi(s,t,a):(a++,yi(s,a,i)),a<=e&&(t=a+1),e<=a&&(i=a-1)}}function yi(s,e,t){const i=s[e];s[e]=s[t],s[t]=i}function $p(s,e){return s<e?-1:s>e?1:0}class Yp{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const i=[];if(!Pn(e,t))return i;const n=this.toBBox,r=[];for(;t;){for(let o=0;o<t.children.length;o++){const a=t.children[o],l=t.leaf?n(a):a;Pn(e,l)&&(t.leaf?i.push(a):ur(e,l)?this._all(a,i):r.push(a))}t=r.pop()}return i}collides(e){let t=this.data;if(!Pn(e,t))return!1;const i=[];for(;t;){for(let n=0;n<t.children.length;n++){const r=t.children[n],o=t.leaf?this.toBBox(r):r;if(Pn(e,o)){if(t.leaf||ur(e,o))return!0;i.push(r)}}t=i.pop()}return!1}load(e){if(!(e&&e.length))return this;if(e.length<this._minEntries){for(let i=0;i<e.length;i++)this.insert(e[i]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(!this.data.children.length)this.data=t;else if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const i=this.data;this.data=t,t=i}this._insert(t,this.data.height-t.height-1,!0)}return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Gt([]),this}remove(e,t){if(!e)return this;let i=this.data;const n=this.toBBox(e),r=[],o=[];let a,l,c;for(;i||r.length;){if(i||(i=r.pop(),l=r[r.length-1],a=o.pop(),c=!0),i.leaf){const h=Zp(e,i.children,t);if(h!==-1)return i.children.splice(h,1),r.push(i),this._condense(r),this}!c&&!i.leaf&&ur(i,n)?(r.push(i),o.push(a),a=0,l=i,i=i.children[0]):l?(a++,i=l.children[a],c=!1):i=null}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const i=[];for(;e;)e.leaf?t.push(...e.children):i.push(...e.children),e=i.pop();return t}_build(e,t,i,n){const r=i-t+1;let o=this._maxEntries,a;if(r<=o)return a=Gt(e.slice(t,i+1)),Vt(a,this.toBBox),a;n||(n=Math.ceil(Math.log(r)/Math.log(o)),o=Math.ceil(r/Math.pow(o,n-1))),a=Gt([]),a.leaf=!1,a.height=n;const l=Math.ceil(r/o),c=l*Math.ceil(Math.sqrt(o));nl(e,t,i,c,this.compareMinX);for(let h=t;h<=i;h+=c){const p=Math.min(h+c-1,i);nl(e,h,p,l,this.compareMinY);for(let m=h;m<=p;m+=l){const g=Math.min(m+l-1,p);a.children.push(this._build(e,m,g,n-1))}}return Vt(a,this.toBBox),a}_chooseSubtree(e,t,i,n){for(;n.push(t),!(t.leaf||n.length-1===i);){let r=1/0,o=1/0,a;for(let l=0;l<t.children.length;l++){const c=t.children[l],h=dr(c),p=Jp(e,c)-h;p<o?(o=p,r=h<r?h:r,a=c):p===o&&h<r&&(r=h,a=c)}t=a||t.children[0]}return t}_insert(e,t,i){const n=i?e:this.toBBox(e),r=[],o=this._chooseSubtree(n,this.data,t,r);for(o.children.push(e),fi(o,n);t>=0&&r[t].children.length>this._maxEntries;)this._split(r,t),t--;this._adjustParentBBoxes(n,r,t)}_split(e,t){const i=e[t],n=i.children.length,r=this._minEntries;this._chooseSplitAxis(i,r,n);const o=this._chooseSplitIndex(i,r,n),a=Gt(i.children.splice(o,i.children.length-o));a.height=i.height,a.leaf=i.leaf,Vt(i,this.toBBox),Vt(a,this.toBBox),t?e[t-1].children.push(a):this._splitRoot(i,a)}_splitRoot(e,t){this.data=Gt([e,t]),this.data.height=e.height+1,this.data.leaf=!1,Vt(this.data,this.toBBox)}_chooseSplitIndex(e,t,i){let n,r=1/0,o=1/0;for(let a=t;a<=i-t;a++){const l=gi(e,0,a,this.toBBox),c=gi(e,a,i,this.toBBox),h=Qp(l,c),p=dr(l)+dr(c);h<r?(r=h,n=a,o=p<o?p:o):h===r&&p<o&&(o=p,n=a)}return n||i-t}_chooseSplitAxis(e,t,i){const n=e.leaf?this.compareMinX:Xp,r=e.leaf?this.compareMinY:qp,o=this._allDistMargin(e,t,i,n),a=this._allDistMargin(e,t,i,r);o<a&&e.children.sort(n)}_allDistMargin(e,t,i,n){e.children.sort(n);const r=this.toBBox,o=gi(e,0,t,r),a=gi(e,i-t,i,r);let l=Sn(o)+Sn(a);for(let c=t;c<i-t;c++){const h=e.children[c];fi(o,e.leaf?r(h):h),l+=Sn(o)}for(let c=i-t-1;c>=t;c--){const h=e.children[c];fi(a,e.leaf?r(h):h),l+=Sn(a)}return l}_adjustParentBBoxes(e,t,i){for(let n=i;n>=0;n--)fi(t[n],e)}_condense(e){for(let t=e.length-1,i;t>=0;t--)e[t].children.length===0?t>0?(i=e[t-1].children,i.splice(i.indexOf(e[t]),1)):this.clear():Vt(e[t],this.toBBox)}}function Zp(s,e,t){if(!t)return e.indexOf(s);for(let i=0;i<e.length;i++)if(t(s,e[i]))return i;return-1}function Vt(s,e){gi(s,0,s.children.length,e,s)}function gi(s,e,t,i,n){n||(n=Gt(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(let r=e;r<t;r++){const o=s.children[r];fi(n,s.leaf?i(o):o)}return n}function fi(s,e){return s.minX=Math.min(s.minX,e.minX),s.minY=Math.min(s.minY,e.minY),s.maxX=Math.max(s.maxX,e.maxX),s.maxY=Math.max(s.maxY,e.maxY),s}function Xp(s,e){return s.minX-e.minX}function qp(s,e){return s.minY-e.minY}function dr(s){return(s.maxX-s.minX)*(s.maxY-s.minY)}function Sn(s){return s.maxX-s.minX+(s.maxY-s.minY)}function Jp(s,e){return(Math.max(e.maxX,s.maxX)-Math.min(e.minX,s.minX))*(Math.max(e.maxY,s.maxY)-Math.min(e.minY,s.minY))}function Qp(s,e){const t=Math.max(s.minX,e.minX),i=Math.max(s.minY,e.minY),n=Math.min(s.maxX,e.maxX),r=Math.min(s.maxY,e.maxY);return Math.max(0,n-t)*Math.max(0,r-i)}function ur(s,e){return s.minX<=e.minX&&s.minY<=e.minY&&e.maxX<=s.maxX&&e.maxY<=s.maxY}function Pn(s,e){return e.minX<=s.maxX&&e.minY<=s.maxY&&e.maxX>=s.minX&&e.maxY>=s.minY}function Gt(s){return{children:s,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function nl(s,e,t,i,n){const r=[e,t];for(;r.length;){if(t=r.pop(),e=r.pop(),t-e<=i)continue;const o=e+Math.ceil((t-e)/i/2)*i;il(s,o,e,t,n),r.push(e,o,o,t)}}const em=40,tm=1.4;class sl{constructor(e){this.tree=new Yp(e),this.idMap=new Map}insert(e){const t=typeof e.id=="string"&&e.id.length>0;if(t){const i=this.idMap.get(e.id);if(i){if(i.minX===e.minX&&i.minY===e.minY&&i.maxX===e.maxX&&i.maxY===e.maxY)return;this.remove(i,(n,r)=>n.id===r.id),this.idMap.delete(e.id)}}this.tree.insert(e),t&&this.idMap.set(e.id,e)}load(e){this.tree.load(e);for(const t of e)typeof t.id=="string"&&t.id.length>0&&this.idMap.set(t.id,t)}remove(e,t){this.tree.remove(e,t??((i,n)=>i===n||i.id===n.id&&i.minX===n.minX&&i.minY===n.minY&&i.maxX===n.maxX&&i.maxY===n.maxY)),typeof e.id=="string"&&e.id.length>0&&this.idMap.delete(e.id)}removeById(e){typeof e=="string"&&e.length>0&&(this.tree.remove({minX:0,minY:0,maxX:0,maxY:0,id:e},(t,i)=>t.id===i.id),this.idMap.delete(e))}clear(){this.tree.clear(),this.idMap.clear()}search(e,t){const i=this.tree.search(e);return(t==null?void 0:t.selectionMode)!=="window"?i:i.filter(n=>zt(n,e))}collides(e){return this.tree.collides(e)}all(){return this.tree.all()}getStats(){const e=this.tree.all(),t=e.length,i=Pa(e),n=this.idMap.size*em;return{kind:"rbush",itemCount:t,estimatedBytes:Math.round(i*tm+n)}}}const Ls=class Ls{constructor(e){this.childIndexes=new Map,this.rootIndex=e??new sl}setChildIndex(e,t){this.childIndexes.set(e,t)}removeChildIndex(e){this.childIndexes.delete(e)}insert(e){this.rootIndex.insert(e)}load(e){this.rootIndex.load(e)}remove(e,t){this.rootIndex.remove(e,t),this.childIndexes.delete(e.id)}removeById(e){this.rootIndex.removeById(e),this.childIndexes.delete(e)}clear(){this.rootIndex.clear(),this.childIndexes.forEach(e=>e.clear()),this.childIndexes.clear()}search(e,t){const i=this.rootIndex.search(e),n=[];for(const r of i){const o=this.childIndexes.get(r.id);if(!o){((t==null?void 0:t.selectionMode)!=="window"||zt(r,e))&&n.push(r);continue}const a=o.search(e),l={...r,children:a};((t==null?void 0:t.selectionMode)!=="window"||this.isWindowSelectionHit(l,e))&&n.push(l)}return n}isWindowSelectionHit(e,t){const i=this.childIndexes.get(e.id);if(!i)return zt(e,t);const n=i.all().filter(mi);return n.length===0?!1:n.every(r=>zt(r,t))}collides(e){return this.rootIndex.collides(e)?this.rootIndex.search(e).some(i=>{const n=this.childIndexes.get(i.id);return n?n.collides(e):!0}):!1}all(){const e=[];for(const t of this.rootIndex.all()){const i=this.childIndexes.get(t.id);i?e.push(...i.all()):e.push(t)}return e}hasChildIndex(e){return this.childIndexes.has(e)}getStats(){const e=this.rootIndex.getStats();let t=0,i=0,n=0,r=0;for(const a of this.childIndexes.values()){const l=a.getStats();t+=l.itemCount,i+=l.estimatedBytes,l.kind==="rbush"?n++:l.kind==="linear"&&r++}const o=this.childIndexes.size*64;return{kind:"hierarchical",itemCount:e.itemCount,estimatedBytes:e.estimatedBytes+i+o,rootItemCount:e.itemCount,childIndexCount:this.childIndexes.size,childItemCount:t,rbushChildCount:n,linearChildCount:r}}ensureChildIndex(e,t){const i=el(t.filter(mi));if(i.length===0)return;const n=kn(i,e);mi(n)&&this.insert(n);const r=this.childIndexes.get(e);if(r)return r.clear(),i.forEach(a=>r.insert({...a})),r;const o=this.createIndexBySize(i.length);if(o)return i.forEach(a=>o.insert({...a})),this.setChildIndex(e,o),o}createChildIndex(e){return this.ensureChildIndex(e.objectId,e.wcsChildBoxes)}createIndexBySize(e){if(e>Ls.THRESHOLD)return new sl;if(e>0)return new Wp}};Ls.THRESHOLD=100;let hr=Ls;class Kt{static isLayerVisible(e){return!(e.isFrozen||e.isOff)}constructor(e){this._group=new M.AcTrBatchedGroup,this._name=e.name,this._cachedBox=new T.Box3,this._boxDirty=!0,this._group.visible=Kt.isLayerVisible(e)}get name(){return this._name}set name(e){this._name=e}get box(){return this._boxDirty&&(this.computeBatchBoundingBox(this._cachedBox),this._boxDirty=!1),this._cachedBox}computeBatchBoundingBox(e=new T.Box3,t,i){return this.visible?this._group.computeBoundingBox(e,{excludeObjectIds:t,includeObjectIds:i}):(e.makeEmpty(),e)}get visible(){return this._group.visible}set visible(e){this._group.visible=e}get internalObject(){return this._group}get stats(){const e=this._group.stats;return{name:this._name,...e}}get entityCount(){return this._group.entityCount}update(e){const t=this.visible;this._name=e.name,this._group.visible=Kt.isLayerVisible(e),t!==this.visible&&(this._boxDirty=!0)}updateMaterial(e,t){this._group.updateMaterial(e,t)}syncAppearanceFromRecord(e,t,i,n){const r=Object.entries(i).some(([o,a])=>a.id!==Number(o));if(r)for(const o in i){const a=Number(o),l=i[o];l.id!==a&&this.updateMaterial(a,l)}this._group.syncAppearanceFromRecord(e,t,i,r,(o,a,l)=>n.getLayerBoundMaterial(o,a,l),n.styleManager)}rebindMaterialsForLayer(e,t,i,n){this._group.rebindMaterialsForLayer(e,t,i,n)}rematerializeLayerTextDrawables(e,t,i){this._group.rematerializeLayerTextDrawables(e,t,i)}rerenderPoints(e){this._group.rerenderPoints(e)}hasEntity(e){return this._group.hasEntity(e)}setEntityVisible(e,t){return this._group.setEntityVisible(e,t)}getEntityVisible(e){return this._group.getEntityVisible(e)}createPreviewSubset(e,t){return this._group.createPreviewSubset(e,t)}addEntity(e,t=!0){this._group.addEntity(e),this._boxDirty=!0}addDirectEntity(e){const t={objectId:e.objectId,visible:e.visible,position:e.position};let i=!1;return e.kind==="lineFat"?i=this._group.appendLine2Geometry(e.geometry,e.material,e.worldOffset,t):e.kind==="lineBasic"?i=this._group.appendLineGeometry(e.geometry,e.material,e.worldOffset,t):e.kind==="point"?i=this._group.appendPointGeometry(e.geometry,e.material,e.worldOffset,t):e.kind==="mesh"&&(i=this._group.appendMeshGeometry(e.geometry,e.material,e.worldOffset,t)),i&&(this._boxDirty=!0),i}isIntersectWith(e,t){return this._group.isIntersectWith(e,t)}removeEntity(e){const t=this._group.removeEntity(e);return t&&(this._boxDirty=!0),t}updateEntity(e){return e.objectId?this._group.removeEntity(e.objectId)?(this._group.addEntity(e),this._boxDirty=!0,!0):e.visible?(this._group.addEntity(e),this._boxDirty=!0,!0):!1:!1}clear(){this._group.clear(),this._cachedBox.makeEmpty(),this._boxDirty=!0,this._group.removeFromParent()}hover(e){if(e.length!==0){if(e.length===1){this._group.hover(e[0]);return}this._group.hoverMany(e)}}unhover(e){if(e.length!==0){if(e.length===1){this._group.unhover(e[0]);return}this._group.unhoverMany(e)}}select(e){if(e.length!==0){if(e.length===1){this._group.select(e[0]);return}this._group.selectMany(e)}}unselect(e){if(e.length!==0){if(e.length===1){this._group.unselect(e[0]);return}this._group.unselectMany(e)}}}class rl{constructor(){this.isReference=!1,this._group=new T.Group,this._spatialIndex=new hr,this._cachedBox=new T.Box3,this._boxDirty=!0,this._extentExcludedObjectIds=new Set,this._layers=new Map,this._insertLayerByObjectId=new Map,this._isLoaded=!1}get internalObject(){return this._group}get layers(){return this._layers}get box(){return this._boxDirty&&this.recomputeBox(),this._cachedBox}computeBatchBoundingBox(e=new T.Box3){return this._boxDirty&&this.recomputeBox(),e.copy(this._cachedBox)}recomputeBox(){this._cachedBox.makeEmpty();const e=new T.Box3;this._layers.forEach(t=>{t.computeBatchBoundingBox(e,this._extentExcludedObjectIds),e.isEmpty()||this._cachedBox.union(e)}),this._boxDirty=!1}invalidateBox(){this._boxDirty=!0}get isLoaded(){return this._isLoaded}set isLoaded(e){this._isLoaded=e}get visible(){return this._group.visible}set visible(e){this._group.visible=e}get entityCount(){let e=0;return this._layers.forEach(t=>e+=t.entityCount),e}get spatialIndexStats(){return this._spatialIndex.getStats()}get stats(){const e=[];let t=0,i=0,n=0,r=0,o=0,a=0,l=0;const c={line:0,mesh:0,point:0,other:0};return this._layers.forEach(h=>{const p=h.stats;e.push(p),n+=p.line.indexed.geometrySize+p.line.nonIndexed.geometrySize,r+=p.mesh.indexed.geometrySize+p.mesh.nonIndexed.geometrySize,o+=p.point.indexed.geometrySize+p.point.nonIndexed.geometrySize,a+=p.unbatched.geometrySize,l+=p.unbatched.count,c.line+=p.unbatched.byType.line,c.mesh+=p.unbatched.byType.mesh,c.point+=p.unbatched.byType.point,c.other+=p.unbatched.byType.other,t+=p.summary.totalGeometrySize,i+=p.summary.totalMappingSize}),{layers:e,summary:{entityCount:this.entityCount,totalSize:{line:n,mesh:r,point:o,unbatched:a,geometry:t,mapping:i,unbatchedCount:l,unbatchedByType:c}}}}clear(){return this._layers.forEach(e=>{e.clear()}),this._layers.clear(),this._cachedBox.makeEmpty(),this._boxDirty=!0,this._extentExcludedObjectIds.clear(),this._insertLayerByObjectId.clear(),this._spatialIndex.clear(),this}rerenderPoints(e){this._layers.forEach(t=>{t.rerenderPoints(e)})}isIntersectWith(e,t){const i=this.getLayersByObjectId(e);for(let n=0;n<i.length;++n){const r=i[n];if(r&&r.isIntersectWith(e,t))return!0}return!1}hasVisibleEntity(e){return this.getLayersByObjectId(e).some(t=>t.visible)}addEntity(e,t=!0){if(!e.objectId)throw new Error("Object id is required to add one entity!");if(!e.layerName)throw new Error("Layer name is required to add one entity!");const i=this._layers.get(e.layerName);if(!i)throw new Error(`layer '${e.layerName}' doesn't exist!`);i.addEntity(e);const n=e.userData.insertLayerName;return n&&this._insertLayerByObjectId.set(e.objectId,n),t?this._extentExcludedObjectIds.delete(e.objectId):this._extentExcludedObjectIds.add(e.objectId),this.invalidateBox(),this.registerEntitySpatialIndex(e),this}addDirectEntity(e,t=!0){if(!e.objectId)throw new Error("Object id is required to add one entity!");if(!e.layerName)throw new Error("Layer name is required to add one entity!");const i=this._layers.get(e.layerName);if(!i)throw new Error(`layer '${e.layerName}' doesn't exist!`);return i.addDirectEntity(e)?(t?this._extentExcludedObjectIds.delete(e.objectId):this._extentExcludedObjectIds.add(e.objectId),this.invalidateBox(),this.registerSpatialIndexBox(e.objectId,e.wcsBbox),!0):!1}removeEntity(e){let t=!1;for(const[i,n]of this._layers)n.removeEntity(e)&&(t=!0);return t&&(this._spatialIndex.removeById(e),this._extentExcludedObjectIds.delete(e),this._insertLayerByObjectId.delete(e),this.invalidateBox()),t}updateEntity(e){for(const[t,i]of this._layers)if(i.updateEntity(e)){const n=e.userData.insertLayerName;return n&&this._insertLayerByObjectId.set(e.objectId,n),this._spatialIndex.removeById(e.objectId),this.registerEntitySpatialIndex(e),this.invalidateBox(),!0}return!1}hasEntity(e){for(const[t,i]of this._layers)if(i.hasEntity(e))return!0;return!1}setEntityVisible(e,t){let i=!1;for(const[n,r]of this._layers)r.setEntityVisible(e,t)&&(i=!0);return i&&this.invalidateBox(),i}getEntityVisible(e){for(const[t,i]of this._layers){const n=i.getEntityVisible(e);if(n!==void 0)return n}}canCreateEntityPreview(e,t){if(e.length===0)return!1;if((t==null?void 0:t.requireAllEntities)??!0){for(const n of e){if(!this.hasEntity(n))return!1;const r=new T.Box3;if(this.computeEntityPreviewBoundsBox([n],r),r.isEmpty())return!1}return!0}return!this.computeEntityPreviewBoundsBox(e).isEmpty()}findPreviewableEntityIds(e){const t=[];for(const i of e){if(!this.hasEntity(i))continue;const n=new T.Box3;this.computeEntityPreviewBoundsBox([i],n),n.isEmpty()||t.push(i)}return t}computeEntityPreviewBoundsBox(e,t=new T.Box3){if(t.makeEmpty(),e.length===0)return t;const i=new Set(e),n=new T.Box3;for(const r of this._layers.values())r.computeBatchBoundingBox(n,void 0,i),n.isEmpty()||t.union(n);return t}computeEntityPreviewBounds2d(e,t=1.1){const i=this.computeEntityPreviewBoundsBox(e);return M.AcTrEntityPreview.box3ToBounds2d(i,t)}createEntityPreviewRoot(e,t){const i=(t==null?void 0:t.missingEntity)??"fail",n=(t==null?void 0:t.requireAllEntities)??!1;if(n){for(const a of e)if(!this.hasEntity(a))return null}const r=new Map;for(const a of e){const l=this.getLayersByObjectId(a);if(l.length===0){if(n||i==="fail")return null;continue}for(const c of l){let h=r.get(c);h||(h=new Set,r.set(c,h)),h.add(a)}}if(r.size===0)return null;const o=new T.Group;o.name="EntityPreviewRoot";for(const[a,l]of r){const c=[...l],h=a.createPreviewSubset(c,{maxSlots:Math.max(1e4,c.length*8),missingEntity:i});if(!h||h.children.length===0){if(i==="fail")return M.disposePreviewSubset(o),null;continue}o.add(h)}return o.children.length===0?null:o}getLayer(e){return this._layers.get(e)}addLayer(e){const t=e.name;let i=this._layers.get(t);return i===void 0&&(i=new Kt(e),this._layers.set(t,i),this._group.add(i.internalObject)),i}updateLayer(e){const t=this._layers.get(e.name);if(t){const i=t.visible;t.update(e),i!==t.visible&&this.invalidateBox()}return t}applyInsertLayerFreeze(e,t){const i=[];for(const[n,r]of this._insertLayerByObjectId){if(r!==e)continue;let o=!1;for(const a of this.getLayersByObjectId(n))a.name!==e&&a.setEntityVisible(n,!t)&&(o=!0);o&&i.push(n)}return i.length>0&&this.invalidateBox(),i}hover(e){this.applyHighlightToLayers(e,(t,i)=>t.hover(i))}unhover(e){this.applyHighlightToLayers(e,(t,i)=>t.unhover(i))}select(e){this.applyHighlightToLayers(e,(t,i)=>t.select(i))}unselect(e){this.applyHighlightToLayers(e,(t,i)=>t.unselect(i))}applyHighlightToLayers(e,t){const i=new Map;for(const n of e){const r=this.getLayersByObjectId(n);for(const o of r){const a=i.get(o);a?a.push(n):i.set(o,[n])}}i.forEach((n,r)=>t(r,n))}search(e,t){return this._spatialIndex.search({minX:e.min.x,minY:e.min.y,maxX:e.max.x,maxY:e.max.y},t)}getLayersByObjectId(e){const t=[];for(const[i,n]of this._layers)n.hasEntity(e)&&t.push(n);return t}getSpatialIndexChildBoxes(e){const t=e.userData.spatialIndexChildBoxes;if(!(!t||t.length===0))return t}registerEntitySpatialIndex(e){const t=this.getSpatialIndexChildBoxes(e);let i;if(t&&t.length>0){const n=kn(t);i={minX:n.minX,minY:n.minY,maxX:n.maxX,maxY:n.maxY,id:e.objectId}}else if(e instanceof M.AcTrGroup&&e.wcsChildBoxes.length>0){const n=kn(e.wcsChildBoxes.map(r=>({minX:r.minX,minY:r.minY,maxX:r.maxX,maxY:r.maxY,id:r.id})));i={minX:n.minX,minY:n.minY,maxX:n.maxX,maxY:n.maxY,id:e.objectId}}else i={minX:e.wcsBbox.min.x,minY:e.wcsBbox.min.y,maxX:e.wcsBbox.max.x,maxY:e.wcsBbox.max.y,id:e.objectId};this._spatialIndex.insert({minX:i.minX,minY:i.minY,maxX:i.maxX,maxY:i.maxY,id:e.objectId}),t&&t.length>0&&(e.wcsBbox.min.set(i.minX,i.minY,e.wcsBbox.min.z),e.wcsBbox.max.set(i.maxX,i.maxY,e.wcsBbox.max.z)),t?this._spatialIndex.ensureChildIndex(e.objectId,t):e instanceof M.AcTrGroup&&this._spatialIndex.createChildIndex(e)}registerSpatialIndexBox(e,t){this._spatialIndex.insert({minX:t.min.x,minY:t.min.y,maxX:t.max.x,maxY:t.max.y,id:e})}}class ol{constructor(){this._scene=new T.Scene,this._transientManager=new M.AcTrTransientManager(this._scene),this._htmlTransientManager=new M.AcTrHtmlTransientManager(this._scene),this._previewOverlayManager=new M.AcTrPreviewOverlayManager(this._scene),this._layers=new Map,this._layouts=new Map,this._activeLayoutBtrId="",this._modelSpaceBtrId=""}get htmlTransientManager(){return this._htmlTransientManager}get layers(){return this._layers}get layouts(){return this._layouts}get box(){const e=this.activeLayout;if(!e)return;const t=e.box;return t.isEmpty()?void 0:t}get internalScene(){return this._scene}get modelSpaceBtrId(){return this._modelSpaceBtrId}set modelSpaceBtrId(e){if(this._modelSpaceBtrId=e,!this._layouts.has(e))throw new Error(`[AcTrScene] No layout assiciated with the specified block table record id '${e}'!`)}get activeLayoutBtrId(){return this._activeLayoutBtrId}set activeLayoutBtrId(e){this._activeLayoutBtrId=e,this._layouts.forEach((t,i)=>{t.visible=e==i})}get activeLayout(){if(this._activeLayoutBtrId&&this._layouts.has(this._activeLayoutBtrId))return this._layouts.get(this._activeLayoutBtrId)}get modelSpaceLayout(){if(this._modelSpaceBtrId&&this._layouts.has(this._modelSpaceBtrId))return this._layouts.get(this._modelSpaceBtrId)}get stats(){const e=[];let t=0,i=0,n=0,r=0,o=0,a=0,l=0,c=0;const h={line:0,mesh:0,point:0,other:0};return this._layouts.forEach(p=>e.push(p.stats)),e.forEach(p=>{t+=p.summary.entityCount,i+=p.summary.totalSize.line,n+=p.summary.totalSize.mesh,r+=p.summary.totalSize.point,o+=p.summary.totalSize.unbatched,a+=p.summary.totalSize.geometry,l+=p.summary.totalSize.mapping,c+=p.summary.totalSize.unbatchedCount,h.line+=p.summary.totalSize.unbatchedByType.line,h.mesh+=p.summary.totalSize.unbatchedByType.mesh,h.point+=p.summary.totalSize.unbatchedByType.point,h.other+=p.summary.totalSize.unbatchedByType.other}),{layouts:e,summary:{layoutCount:e.length,entityCount:t,totalSize:{line:i,mesh:n,point:r,unbatched:o,geometry:a,mapping:l,unbatchedCount:c,unbatchedByType:h}}}}addEmptyLayout(e){const t=this._layouts.get(e);if(t)return t;const i=new rl;return this._layouts.set(e,i),this._scene.add(i.internalObject),i.visible=e==this._activeLayoutBtrId,this._layers.forEach(n=>{i.addLayer(n)}),i}clear(){return this._layouts.forEach(e=>{this._scene.remove(e.internalObject),e.clear()}),this._layouts.clear(),this._layers.clear(),this._transientManager.clear(),this._htmlTransientManager.clear(),this._previewOverlayManager.clear(),this._scene.clear(),this._transientManager=new M.AcTrTransientManager(this._scene),this._htmlTransientManager=new M.AcTrHtmlTransientManager(this._scene),this._previewOverlayManager=new M.AcTrPreviewOverlayManager(this._scene),this}hover(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.hover(e)),!0)}unhover(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.unhover(e)),!0)}select(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.select(e)),!0)}unselect(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.unselect(e)),!0)}search(e,t){const i=this.activeLayout;return i?i.search(e,t):[]}addLayer(e){const t=[];return this._layers.set(e.name,e),this._layouts.forEach(i=>{const n=i.addLayer(e);n&&t.push(n)}),t}updateLayer(e){const t=this._layers.get(e.name),i=(t==null?void 0:t.isFrozen)??!1,n=[];this._layers.set(e.name,e);const r=new Set;return this._layouts.forEach(o=>{const a=o.updateLayer(e);if(a&&n.push(a),e.isFrozen&&!i)for(const l of o.applyInsertLayerFreeze(e.name,!0))r.add(l);else if(!e.isFrozen&&i)for(const l of o.applyInsertLayerFreeze(e.name,!1))r.add(l)}),{updatedLayers:n,touchedObjectIds:r}}forEachSceneLayer(e,t){this._layouts.forEach(i=>{const n=i.getLayer(e);n&&t(n,i)})}addTransientEntity(e){this._transientManager.update(e)}removeTransientEntity(e){this._transientManager.remove(e)}setTransientEntityVisible(e,t){const i=this._transientManager.get(e);return!i||i.visible===t?!1:(i.visible=t,!0)}updateTransientPreviewTransforms(e){const t=e.map(i=>({id:i.objectId,matrix:i.matrix}));return{webgl:this._transientManager.applyTransforms(t),html:this._htmlTransientManager.applyTransforms(t)}}canCreatePreview(e){const t=this.activeLayout;return t?t.canCreateEntityPreview(e,{requireAllEntities:!0}):!1}computeEntityPreviewBounds2d(e,t=1.1,i="active-first"){const n=this.computeEntityPreviewBoundsBox(e,i);return M.AcTrEntityPreview.box3ToBounds2d(n,t)}findPreviewableEntityIds(e,t="active-first"){if(e.length===0)return[];if(t==="all"){const i=[],n=new Set(e);for(const r of this.getOrderedLayouts("all")){if(n.size===0)break;const o=r.findPreviewableEntityIds([...n]);if(o.length!==0){i.push(...o);for(const a of o)n.delete(a)}}return i}for(const i of this.getOrderedLayouts("active-first")){const n=i.findPreviewableEntityIds(e);if(n.length>0)return n}return[]}createEntityPreviewRoot(e,t){if(e.length===0)return null;const i=(t==null?void 0:t.scope)??"active-first",n={missingEntity:"skip",...t==null?void 0:t.layoutOptions};if(i==="all")return this.mergeEntityPreviewRoots(e,this.getOrderedLayouts("all"),n);for(const r of this.getOrderedLayouts("active-first")){const o=r.createEntityPreviewRoot(e,n);if(o)return o}return null}mergeEntityPreviewRoots(e,t,i){const n=new Set(e),r=new T.Group;r.name="EntityPreviewRoot";for(const o of t){if(n.size===0)break;const a=o.findPreviewableEntityIds([...n]);if(a.length===0)continue;const l=o.createEntityPreviewRoot(a,i);if(l){r.add(l);for(const c of a)n.delete(c)}}return r.children.length>0?r:null}getOrderedLayouts(e){if(e==="all")return[...this._layouts.values()];const t=[],i=this.activeLayout,n=this.modelSpaceLayout;i&&t.push(i),n&&n!==i&&t.push(n);for(const r of this._layouts.values())r!==i&&r!==n&&t.push(r);return t}computeEntityPreviewBoundsBox(e,t="active-first"){const i=new T.Box3,n=new T.Box3;if(t==="all"){const r=new Set(e);for(const o of this.getOrderedLayouts("all")){if(r.size===0)break;const a=o.findPreviewableEntityIds([...r]);if(a.length!==0){o.computeEntityPreviewBoundsBox(a,n),n.isEmpty()||i.union(n);for(const l of a)r.delete(l)}}return i}for(const r of this.getOrderedLayouts("active-first"))if(r.computeEntityPreviewBoundsBox(e,n),!n.isEmpty())return i.copy(n),i;return i.makeEmpty(),i}createPreview(e){const t=this.activeLayout;if(!t)return null;const i=t.createEntityPreviewRoot(e,{missingEntity:"fail",requireAllEntities:!0});return i?this._previewOverlayManager.add(i).id:null}updatePreview(e,t){return this._previewOverlayManager.update(e,t)}removePreview(e){return this._previewOverlayManager.remove(e)}addEntity(e,t=!0){const i=e.ownerId;if(i){let n=this._layouts.get(i);n||(n=this.addEmptyLayout(i)),n.addEntity(e,t)}else u.log.warn("[AcTrSecene] The owner id of one entity cannot be empty!");return this}addDirectEntity(e,t=!0){const i=e.ownerId;if(!i)return u.log.warn("[AcTrSecene] The owner id of one entity cannot be empty!"),!1;let n=this._layouts.get(i);return n||(n=this.addEmptyLayout(i)),n.addDirectEntity(e,t)}removeEntity(e){for(const[t,i]of this._layouts)if(i.removeEntity(e))return!0;return!1}updateEntity(e){for(const[t,i]of this._layouts)if(i.updateEntity(e))return!0;return!1}hasEntity(e){for(const[t,i]of this._layouts)if(i.hasEntity(e))return!0;return!1}setEntityVisible(e,t){let i=!1;for(const[n,r]of this._layouts)r.setEntityVisible(e,t)&&(i=!0);return i}getEntityVisible(e){for(const[t,i]of this._layouts){const n=i.getEntityVisible(e);if(n!==void 0)return n}}}const al="ml-html-text-editing",ll="ml-markup-inline-text-edit-styles",im=400,cl=6,bi=new WeakSet;let An=0;function dl(){return An>0}function nm(){if(typeof document>"u"||document.getElementById(ll))return;const s=document.createElement("style");s.id=ll,s.textContent=`
127
- .ml-html-text-editing {
128
- outline: 1px solid var(--ml-ui-accent, #409eff);
129
- outline-offset: 1px;
121
+ `,document.head.appendChild(s)}function lr(s){return Math.max(0,Math.min(16777215,Math.round(s)))}function Za(s){return`#${(s===null?16777215:lr(s)).toString(16).padStart(6,"0")}`}function Wp(s){return/^#[0-9a-fA-F]{6}$/.test(s)?Number.parseInt(s.slice(1),16):16777215}function $p(s){return s.isRgb&&s.rgbValue!==null?Za(s.rgbValue):s.isAci&&s.aci!==null?Za(D.getColorByIndex(s.aci)):"#ffffff"}function Xa(s){const e=new D.MTextColor;return e.rgbValue=Wp(s),e}function qa(s){const e=new D.MTextColor;return s.aci!==null&&Number.isFinite(s.aci)?(e.aci=s.aci,e):s.rgb!==null?(e.rgbValue=lr(s.rgb),e):(e.rgbValue=16777215,e)}function Yp(s){const e=s.trim().toLowerCase();return/^#[0-9a-f]{6}$/.test(e)?e:/^[0-9a-f]{6}$/.test(e)?`#${e}`:null}function gt(s,e){const t=document.createElement("button");return t.type="button",t.className="ml-mtext-toolbar__btn",t.title=s,t.setAttribute("aria-label",s),t.setAttribute("aria-pressed","false"),t.innerHTML=Up[e],t}function Zp(s){const e=s&&s.length>0?s:Ya,t=[],i=new Set;for(const n of e){const r=n.trim();!r||i.has(r)||(i.add(r),t.push(r))}return t.length>0?t:[...Ya]}class Xp{constructor(e){E(this,"anchorElement");E(this,"root");E(this,"controls");E(this,"onFormatChange");E(this,"onToggleStack");E(this,"onToggleSuperscript");E(this,"onToggleSubscript");E(this,"theme");E(this,"colorPicker");Hp(),this.anchorElement=e.anchorElement,this.onFormatChange=e.onFormatChange,this.onToggleStack=e.onToggleStack??(()=>{}),this.onToggleSuperscript=e.onToggleSuperscript??(()=>!1),this.onToggleSubscript=e.onToggleSubscript??(()=>!1),this.theme=e.theme,this.root=document.createElement("div"),this.root.className="ml-mtext-toolbar";const t=document.createElement("div");t.className="ml-mtext-toolbar__group";const i=document.createElement("select");i.className="ml-mtext-toolbar__select";for(const w of Zp(e.fontFamilies)){const v=document.createElement("option");v.value=w,v.textContent=w,i.appendChild(v)}const n=document.createElement("input");n.className="ml-mtext-toolbar__input",n.type="number",n.min="1",n.max="1024",n.step="1",this.colorPicker=this.createColorPicker(e.colorPicker,e.initialFormat),t.append(i,n,this.colorPicker.host);const r=document.createElement("div");r.className="ml-mtext-toolbar__separator";const o=document.createElement("div");o.className="ml-mtext-toolbar__group";const a=gt("Bold","bold"),l=gt("Italic","italic"),c=gt("Underline","underline"),h=gt("Overline","overline"),p=gt("Strike Through","strike"),m=gt("Superscript","superscript"),g=gt("Subscript","subscript"),f=gt("Stack","stack");o.append(a,l,c,h,p,m,g,f),this.root.append(t,r,o),this.controls={fontFamily:i,fontSize:n,boldBtn:a,italicBtn:l,underlineBtn:c,overlineBtn:h,strikeBtn:p,superscriptBtn:m,subscriptBtn:g,stackBtn:f},this.setTheme(this.theme),this.bindEvents(),(e.container??document.body).appendChild(this.root)}setTheme(e){this.theme=e,this.root.dataset.theme=e,this.colorPicker.setTheme(e)}getTheme(){return this.theme}setVisible(e){this.root.style.display=e?"inline-flex":"none"}setSession(e){this.anchorElement=e.anchorElement,this.onFormatChange=e.onFormatChange,this.onToggleStack=e.onToggleStack,this.onToggleSuperscript=e.onToggleSuperscript??(()=>!1),this.onToggleSubscript=e.onToggleSubscript??(()=>!1)}setAnchor(e,t){const i=this.root.offsetWidth||0,n=this.root.offsetHeight||0,r=8,o=8,a=Math.max(r,window.innerWidth-i-8),l=Math.max(o,window.innerHeight-n-8),c=Math.max(r,Math.min(a,Math.round(e))),h=Math.max(o,Math.min(l,Math.round(t-n)));this.root.style.left=`${c}px`,this.root.style.top=`${h}px`}setFormat(e){this.ensureSelectValue(e.fontFamily),this.controls.fontSize.value=String(Math.max(1,Math.round(e.fontSize)));const t=qa(e);this.colorPicker.setValue(t),this.setToggleState(this.controls.boldBtn,e.bold),this.setToggleState(this.controls.italicBtn,e.italic),this.setToggleState(this.controls.underlineBtn,e.underline),this.setToggleState(this.controls.overlineBtn,e.overline),this.setToggleState(this.controls.strikeBtn,e.strike),this.setToggleState(this.controls.superscriptBtn,e.script==="superscript"),this.setToggleState(this.controls.subscriptBtn,e.script==="subscript")}dispose(){this.colorPicker.dispose(),this.root.remove()}setStackActive(e){this.setToggleState(this.controls.stackBtn,e)}setToggleState(e,t){e.classList.toggle("is-active",t),e.setAttribute("aria-pressed",t?"true":"false")}ensureSelectValue(e){if(!Array.from(this.controls.fontFamily.options).some(i=>i.value===e)){const i=document.createElement("option");i.value=e,i.textContent=e,this.controls.fontFamily.appendChild(i)}this.controls.fontFamily.value=e}bindEvents(){const e=()=>{const t=Math.max(1,Number(this.controls.fontSize.value)||1);this.controls.fontSize.value=String(Math.round(t)),this.onFormatChange({fontSize:t})};this.controls.fontFamily.addEventListener("change",()=>{this.onFormatChange({fontFamily:this.controls.fontFamily.value})}),this.controls.fontSize.addEventListener("input",e),this.controls.fontSize.addEventListener("change",e),this.controls.fontSize.addEventListener("blur",e),this.controls.fontSize.addEventListener("keydown",t=>{t.key==="Enter"&&(e(),this.anchorElement.focus({preventScroll:!0}))}),this.controls.boldBtn.addEventListener("click",()=>{this.onFormatChange({bold:!this.controls.boldBtn.classList.contains("is-active")})}),this.controls.italicBtn.addEventListener("click",()=>{this.onFormatChange({italic:!this.controls.italicBtn.classList.contains("is-active")})}),this.controls.underlineBtn.addEventListener("click",()=>{this.onFormatChange({underline:!this.controls.underlineBtn.classList.contains("is-active")})}),this.controls.overlineBtn.addEventListener("click",()=>{this.onFormatChange({overline:!this.controls.overlineBtn.classList.contains("is-active")})}),this.controls.strikeBtn.addEventListener("click",()=>{this.onFormatChange({strike:!this.controls.strikeBtn.classList.contains("is-active")})}),this.controls.superscriptBtn.addEventListener("click",()=>{if(this.onToggleSuperscript())return;const t=this.controls.superscriptBtn.classList.contains("is-active");this.onFormatChange({script:t?"normal":"superscript"})}),this.controls.subscriptBtn.addEventListener("click",()=>{if(this.onToggleSubscript())return;const t=this.controls.subscriptBtn.classList.contains("is-active");this.onFormatChange({script:t?"normal":"subscript"})}),this.controls.stackBtn.addEventListener("click",()=>{this.onToggleStack()}),this.root.addEventListener("mousedown",t=>{const i=t.target;i&&(i.closest('[data-ml-mtext-toolbar-interactive="true"]')||i.tagName==="INPUT"||i.tagName==="SELECT"||i.tagName==="OPTION"||(t.preventDefault(),this.anchorElement.focus({preventScroll:!0})))})}createColorPicker(e,t){if(!e){const a=document.createElement("input");return a.className="ml-mtext-toolbar__color",a.type="color",a.dataset.mlMtextToolbarInteractive="true",a.addEventListener("input",()=>{this.applyColorChange(Xa(a.value))}),{host:a,setValue:l=>{const c=Yp($p(l));c&&(a.value=c)},setTheme:()=>{},dispose:()=>{}}}const i=document.createElement("div");i.className="ml-mtext-toolbar__color",i.dataset.mlMtextToolbarInteractive="true";const n=t?qa(t):Xa("#ffffff"),o=e({container:i,theme:this.theme,initialColor:n,onChange:a=>{this.applyColorChange(a)}})??{};return{host:i,setValue:a=>{var l;(l=o.setValue)==null||l.call(o,a)},setTheme:a=>{var l;(l=o.setTheme)==null||l.call(o,a)},dispose:()=>{var a;(a=o.dispose)==null||a.call(o)}}}applyColorChange(e){if(e.isAci&&e.aci!==null){this.onFormatChange({aci:e.aci});return}if(e.isRgb&&e.rgbValue!==null){this.onFormatChange({aci:null,rgb:lr(e.rgbValue)});return}this.onFormatChange({aci:null,rgb:16777215})}}function Ja(s,e){const t=Math.max(1,s),i=e;return i===void 0||i===1||i===4||i===7||i===10?0:i===2||i===5||i===8||i===11?-t/2:i===3||i===6||i===9||i===12?-t:0}const fn="__mlightcadMTextInputBoxSceneRoot",V=class V{constructor(e){E(this,"scene");E(this,"camera");E(this,"mtextRenderer");E(this,"cursorRenderer");E(this,"width");E(this,"position");E(this,"mtextInsertionOffset",new L.Vector3(0,0,0));E(this,"enableWordWrap");E(this,"mtextString","");E(this,"editorLineSpaceFactor",null);E(this,"editorAttachmentPoint",D.MTextAttachmentPoint.TopLeft);E(this,"cursorIndex",0);E(this,"selectionStart",0);E(this,"selectionEnd",0);E(this,"baseFormat");E(this,"currentFormat");E(this,"defaultTextStyle");E(this,"cursorLogic");E(this,"layoutContainer",{x:0,y:0,width:1,height:1});E(this,"isDragging",!1);E(this,"pendingCursorLineHint",null);E(this,"latestCursorLayoutData",{containerBox:{x:0,y:0,width:1,height:1},charBoxes:[]});E(this,"renderedObject",null);E(this,"boundingBoxObject",null);E(this,"boundingBoxPadding",1);E(this,"boundingBoxZOffset",.01);E(this,"rendererReady",!1);E(this,"pendingFontLoad",null);E(this,"lastFontKey","");E(this,"toolbarTheme","dark");E(this,"toolbarOffsetY",10);E(this,"debugMode",!1);E(this,"colorSettings");E(this,"debugVisibility",{showCharBoxes:!0,showLineIndices:!0,showCharIndices:!0,showChars:!0});E(this,"maxHistorySize",100);E(this,"undoStack",[]);E(this,"redoStack",[]);E(this,"document");E(this,"uiAdapter");E(this,"imeInput",null);E(this,"imeTarget",null);E(this,"lastImeTarget",null);E(this,"reopenTarget",null);E(this,"pointerTarget",null);E(this,"imeComposing",!1);E(this,"imeFocusTimer",null);E(this,"closed",!1);E(this,"toolbarEnabled",!0);E(this,"toolbarContainer",null);E(this,"toolbarFontFamilies",null);E(this,"toolbarColorPicker");E(this,"onImeKeyDown",e=>{if(!this.isActiveEditor()||!(e.ctrlKey||e.metaKey)&&!e.altKey&&e.key.length===1||e.isComposing||e.key==="Process")return;this.handleKeyDown(e)&&e.preventDefault()});E(this,"onWindowKeyDown",e=>{if(!this.isActiveEditor()||e.defaultPrevented)return;const t=e.target,i=(t==null?void 0:t.tagName)??"";if((i==="INPUT"||i==="TEXTAREA"||i==="SELECT"||!!(t!=null&&t.isContentEditable))&&t!==this.imeInput)return;if(!(e.ctrlKey||e.metaKey)&&!e.altKey&&e.key.length===1||this.imeComposing||e.isComposing||e.key==="Process"){this.refocusImeInputSoon();return}this.handleKeyDown(e)&&(e.preventDefault(),this.refocusImeInputSoon())});E(this,"onImeBeforeInput",e=>{if(!this.isActiveEditor()||e.isComposing)return;const t=e.inputType;if(t==="insertText"||t==="insertCompositionText"){this.handleTextInput(e.data??"")&&e.preventDefault();return}t==="insertParagraph"&&this.handleTextInput(`
122
+ `)&&e.preventDefault()});E(this,"onImeCompositionStart",()=>{this.isActiveEditor()&&(this.imeComposing=!0,this.updateImeAnchorPosition(),this.refocusImeInputSoon())});E(this,"onImeCompositionEnd",e=>{if(!this.isActiveEditor())return;this.imeComposing=!1;const t=e.data??"";this.handleTextInput(t)&&this.imeInput&&(this.imeInput.value=""),this.refocusImeInputSoon()});E(this,"onImeTargetMouseDown",()=>{this.isActiveEditor()&&this.refocusImeInputSoon()});E(this,"onPointerMouseDown",e=>{if(this.closed||e.altKey||e.button===1)return;const t=this.pointerEventToEditorLocal(e);if(!t)return;if(!this.isPointInContainer(t.x,t.y)){this.isActiveEditor()&&this.closeEditor();return}this.activateEditor(),this.handleMouseDown(t.x,t.y,e.shiftKey),this.refocusImeInputSoon()});E(this,"onPointerMouseMove",e=>{if(!this.isActiveEditor()||e.buttons===0||!this.isDragging)return;const t=this.pointerEventToEditorLocal(e);t&&this.handleMouseMove(t.x,t.y)});E(this,"onPointerMouseUp",()=>{this.isActiveEditor()&&this.handleMouseUp()});E(this,"onPointerDoubleClick",e=>{if(!this.isActiveEditor())return;const t=this.pointerEventToEditorLocal(e);t&&(this.handleDoubleClick(t.x,t.y),this.refocusImeInputSoon())});E(this,"onReopenDoubleClick",e=>{this.closed&&this.shouldReopenFromDoubleClick(e)&&this.showEditor()});E(this,"handlers",{change:new Set,selectionChange:new Set,cursorMove:new Set,show:new Set,close:new Set});var o,a,l,c,h,p,m,g;V.instances.add(this),this.scene=e.scene,this.camera=e.camera,this.toolbarTheme=((o=e.toolbar)==null?void 0:o.theme)??"dark",this.toolbarOffsetY=Math.max(0,((a=e.toolbar)==null?void 0:a.offsetY)??10),this.toolbarEnabled=((l=e.toolbar)==null?void 0:l.enabled)??!0,this.toolbarContainer=((c=e.toolbar)==null?void 0:c.container)??null,this.toolbarFontFamilies=((h=e.toolbar)==null?void 0:h.fontFamilies)??null,this.toolbarColorPicker=(p=e.toolbar)==null?void 0:p.colorPicker,this.colorSettings=e.colorSettings,this.width=Math.max(1,e.width),this.position=((m=e.position)==null?void 0:m.clone())??new L.Vector3(0,0,0),e.initialAttachmentPoint!==void 0&&(this.editorAttachmentPoint=e.initialAttachmentPoint),this.enableWordWrap=e.enableWordWrap??!0;const t=e.textStyle??V.DEFAULT_TEXT_STYLE,i=Math.max(1,Number.isFinite(t.fixedTextHeight)?t.fixedTextHeight:V.DEFAULT_TEXT_STYLE.fixedTextHeight),n=Math.max(1,Number.isFinite(t.lastHeight)?t.lastHeight:i);this.defaultTextStyle={...t,fixedTextHeight:i,lastHeight:n,widthFactor:Number.isFinite(t.widthFactor)?t.widthFactor:1,obliqueAngle:Number.isFinite(t.obliqueAngle)?t.obliqueAngle:0,textGenerationFlag:Number.isFinite(t.textGenerationFlag)?t.textGenerationFlag:0,standardFlag:Number.isFinite(t.standardFlag)?t.standardFlag:0,font:t.font||V.DEFAULT_TEXT_STYLE.font,bigFont:t.bigFont??""},this.baseFormat=this.createBaseFormatFromTextStyle(this.defaultTextStyle,this.resolveRenderColorSettings()),this.currentFormat={...this.baseFormat},this.document=new me,this.uiAdapter=new ar(this.document),this.mtextRenderer=new D.UnifiedRenderer("main",{workerUrl:typeof e.workerUrl=="string"?e.workerUrl:((g=e.workerUrl)==null?void 0:g.toString())??"./assets/mtext-renderer-worker.js"}),e.fontUrl&&this.mtextRenderer.setFontUrl(e.fontUrl),this.cursorLogic=new _p({containerBox:{x:0,y:0,width:this.width,height:1},charBoxes:[],lineTolerance:4});const r={...e.cursorStyle??{}};r.height===void 0&&r.heightMode!=="fixed"&&(r.height=0),r.color??(r.color="#ffffff"),r.glowColor??(r.glowColor="#ffffff"),this.cursorRenderer=new Mp({renderer:new Dp({scene:this.scene,camera:this.camera}),cursorStyle:r,selectionStyle:e.selectionStyle,enableDebug:!1,enableSelection:!0,debugYAxisUp:this.camera instanceof L.OrthographicCamera?this.camera.top>=this.camera.bottom:!0,debugVisibility:this.debugVisibility}),this.cursorRenderer.setViewTransform({x:this.position.x,y:this.position.y,scaleX:1,scaleY:1}),this.createBoundingBox(e.showBoundingBox??!0,e.boundingBoxStyle),this.setText(e.initialText??""),this.attachIme(e.imeTarget),this.initializeRenderer()}setText(e){this.document=this.createNormalizedDocument(e),this.document.cursor=0,this.uiAdapter=new ar(this.document),this.clearHistory(),this.syncUiStateFromDocument(),this.relayout(),this.emit("change")}getText(){return this.syncUiStateFromDocument(),this.mtextString}getPlainText(){return this.getChars().join("")}insertText(e){if(e.length!==0){if(e===`
123
+ `){const t=this.cursorLogic.getCursorState().lineIndex;this.pendingCursorLineHint=t>=0?t+1:0}this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"insertText",text:e,style:this.toDocumentStyle(this.currentFormat)}),this.syncUiStateFromDocument(),this.relayout()})}}deleteBackward(){this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"backspace"}),this.syncUiStateFromDocument(),this.relayout()})}deleteForward(){this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"delete"}),this.syncUiStateFromDocument(),this.relayout()})}undo(){const e=this.undoStack.pop();return e?(this.redoStack.push(this.createHistorySnapshot()),this.restoreHistorySnapshot(e),!0):!1}redo(){const e=this.redoStack.pop();return e?(this.undoStack.push(this.createHistorySnapshot()),this.restoreHistorySnapshot(e),!0):!1}moveCursor(e){switch(e){case"left":this.cursorLogic.moveLeft();break;case"right":this.cursorLogic.moveRight();break;case"up":this.cursorLogic.moveUp();break;case"down":this.cursorLogic.moveDown();break;case"lineStart":this.cursorLogic.moveToLineStart();break;case"lineEnd":this.cursorLogic.moveToLineEnd();break;case"wordPrev":this.cursorLogic.moveTo(this.findPrevWordStart(this.cursorLogic.getCurrentIndex()));break;case"wordNext":this.cursorLogic.moveTo(this.findNextWordStart(this.cursorLogic.getCurrentIndex()));break}this.cursorLogic.clearSelection(),this.syncStateFromCursor(),this.emit("cursorMove"),this.emit("selectionChange")}extendSelection(e){const t=this.cursorLogic.getSelection(),i=t?t.anchor:this.cursorLogic.getCurrentIndex();switch(this.cursorLogic.clearSelection(),this.cursorLogic.moveTo(this.cursorIndex),e){case"left":this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex()-1);break;case"right":this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex()+1);break;case"up":this.cursorLogic.moveUp();break;case"down":this.cursorLogic.moveDown();break;case"lineStart":this.cursorLogic.moveToLineStart();break;case"lineEnd":this.cursorLogic.moveToLineEnd();break}this.cursorLogic.setSelectionWithDirection(i,this.cursorLogic.getCurrentIndex()),this.syncStateFromCursor(),this.emit("selectionChange")}selectAll(){this.cursorLogic.selectAll(),this.syncStateFromCursor(),this.emit("selectionChange")}clearSelection(){this.cursorLogic.clearSelection(),this.syncStateFromCursor(),this.emit("selectionChange")}setDebugMode(e){this.debugMode=e,this.cursorRenderer.setDebugMode(e)}isDebugMode(){return this.debugMode}setDebugVisibility(e){this.debugVisibility={...this.debugVisibility,...e},this.cursorRenderer.setDebugVisibility(e)}getDebugVisibility(){return{...this.debugVisibility}}setToolbarTheme(e){var t;this.toolbarTheme=e,this.isActiveEditor()&&((t=this.getActiveToolbar())==null||t.setTheme(e))}getToolbarTheme(){return this.toolbarTheme}attachIme(e){const t=this.closed;this.lastImeTarget=e,this.bindReopenDoubleClick(e),this.imeTarget=e,this.attachPointerInteractions(e),this.closed=!1,V.activeEditor?V.activeEditor===this?this.activateEditor():(this.cursorRenderer.hide(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!1)):this.activateEditor(),t&&this.emit("show")}detachIme(){this.imeInput&&(this.imeInput.removeEventListener("keydown",this.onImeKeyDown),this.imeInput.removeEventListener("beforeinput",this.onImeBeforeInput),this.imeInput.removeEventListener("compositionstart",this.onImeCompositionStart),this.imeInput.removeEventListener("compositionend",this.onImeCompositionEnd),window.removeEventListener("keydown",this.onWindowKeyDown),this.imeTarget&&this.imeTarget.removeEventListener("mousedown",this.onImeTargetMouseDown),this.imeInput.remove(),this.imeInput=null,this.imeComposing=!1,this.imeFocusTimer!==null&&(window.clearTimeout(this.imeFocusTimer),this.imeFocusTimer=null))}getCursorIndex(){return this.cursorIndex}getSelectionRange(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return{start:e,end:t,isCollapsed:e===t}}getCursorLayoutData(){const e={containerBox:{...this.latestCursorLayoutData.containerBox},charBoxes:this.latestCursorLayoutData.charBoxes.map(t=>({...t}))};return this.latestCursorLayoutData.lineBreakIndices&&(e.lineBreakIndices=[...this.latestCursorLayoutData.lineBreakIndices]),this.latestCursorLayoutData.lineLayouts&&(e.lineLayouts=this.latestCursorLayoutData.lineLayouts.map(t=>({...t}))),e}setCurrentFormat(e){var n;const t=this.mergeCharFormat(this.currentFormat,e);this.currentFormat=t;const i=this.getSelectionRange();i.isCollapsed||this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const r=this.getNodesByLogicalRange(i.start,i.end);for(const o of r){const a=this.toCharFormat(o.style),l=this.mergeCharFormat(a,e);o.style=this.toDocumentStyle(l,o.style)}this.syncUiStateFromDocument(),this.relayout()}),(n=this.getActiveToolbar())==null||n.setFormat(this.currentFormat)}getCurrentFormat(){return{...this.currentFormat}}setParagraphAlignment(e){const t=this.mapRibbonParagraphAlignment(e);t!==void 0&&this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const i=this.getSelectionRange(),n=this.toDocumentIndexFromLogicalIndex(Math.min(i.start,i.end),!0),r=this.toDocumentIndexFromLogicalIndex(Math.max(i.start,i.end),!1),o=this.document.ast.nodes;if(o.length===0)return;const a=m=>{var f;const g=Math.max(0,Math.min(m,o.length-1));return((f=o[g])==null?void 0:f.type)==="paragraphBreak"?Math.min(g+1,o.length):Math.min(m,o.length-1)},l=m=>{var f;const g=a(m);for(let w=g;w>=0;w--)if(((f=o[w])==null?void 0:f.type)==="paragraphBreak")return w+1;return 0},c=m=>{var f;const g=Math.min(Math.max(0,m),o.length-1);for(let w=g;w<o.length;w++)if(((f=o[w])==null?void 0:f.type)==="paragraphBreak")return w;return o.length},h=l(Math.min(n,r)),p=c(Math.max(n,r));if(!(h>=p)){for(let m=h;m<p;m++){const g=o[m];g&&pi(g)&&(g.style.paragraph.align=t)}this.syncUiStateFromDocument(),this.relayout()}})}setAttachmentPoint(e){const t=this.mapRibbonAttachmentCode(e);if(!(t===void 0||t===this.editorAttachmentPoint)){if(Number.isFinite(this.layoutContainer.width)&&Number.isFinite(this.layoutContainer.height)){const i=this.position.x+this.layoutContainer.x,n=i+this.layoutContainer.width,r=this.position.y+this.layoutContainer.y,o=r+this.layoutContainer.height;if(Number.isFinite(i)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(o)&&n>=i-1e-9&&o>=r-1e-9){const a=this.computeAttachmentAnchorOnBounds(i,n,r,o,this.editorAttachmentPoint),l=this.computeAttachmentAnchorOnBounds(i,n,r,o,t);this.position.x+=l.x-a.x,this.position.y+=l.y-a.y,this.cursorRenderer.setViewTransform({x:this.position.x,y:this.position.y,scaleX:1,scaleY:1})}}this.editorAttachmentPoint=t,this.relayout(),this.emit("change")}}getAttachmentPointCode(){return this.attachmentPointToRibbonCode(this.editorAttachmentPoint)}getMTextAttachmentPoint(){return this.editorAttachmentPoint}toggleCase(){const e=this.getSelectionRange();e.isCollapsed||this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const t=this.toDocumentIndexFromLogicalIndex(e.start,!0),i=this.toDocumentIndexFromLogicalIndex(e.end,!1);if(i<=t)return;const n=this.document.ast.nodes.slice(t,i),r=n.map(l=>l.type==="char"?l.value:l.type==="stack"?`${l.numerator}${l.denominator}`:"").join("");if(!/[a-zA-Z]/.test(r))return;const o=/[a-z]/.test(r),a=l=>o?l.toUpperCase():l.toLowerCase();this.document.transaction(()=>{for(const l of n)l.type==="char"?l.value=a(l.value):l.type==="stack"&&(l.numerator=a(l.numerator),l.denominator=a(l.denominator));this.document.setSelection(t,i)}),this.syncUiStateFromDocument(),this.relayout()})}getDefaultTextStyle(){return{...this.defaultTextStyle}}handleKeyDown(e){if(e.isComposing||e.key==="Process")return!1;if(e.key==="Escape")return this.closeEditor(),!0;const t=this.isMacPlatform(),i=t?e.metaKey:e.ctrlKey,n=t?e.altKey:e.ctrlKey;if(i&&e.key.toLowerCase()==="a")return this.selectAll(),!0;if(i&&e.key.toLowerCase()==="z")return e.shiftKey?this.redo():this.undo();if(!t&&i&&e.key.toLowerCase()==="y")return this.redo();if(e.shiftKey){if(e.key==="ArrowLeft")return this.consumeExtend("left");if(e.key==="ArrowRight")return this.consumeExtend("right");if(e.key==="ArrowUp")return this.consumeExtend("up");if(e.key==="ArrowDown")return this.consumeExtend("down");if(e.key==="Home")return this.consumeExtend("lineStart");if(e.key==="End")return this.consumeExtend("lineEnd")}return t&&e.metaKey&&e.key==="ArrowLeft"?this.consumeMove("lineStart"):t&&e.metaKey&&e.key==="ArrowRight"?this.consumeMove("lineEnd"):e.key==="ArrowLeft"?this.consumeMove(n?"wordPrev":"left"):e.key==="ArrowRight"?this.consumeMove(n?"wordNext":"right"):e.key==="ArrowUp"?this.consumeMove("up"):e.key==="ArrowDown"?this.consumeMove("down"):e.key==="Home"?this.consumeMove("lineStart"):e.key==="End"?this.consumeMove("lineEnd"):e.key==="Backspace"?(this.deleteBackward(),!0):e.key==="Delete"?(this.deleteForward(),!0):e.key==="Enter"?(this.insertText(`
124
+ `),!0):!i&&!e.altKey&&e.key.length===1?(this.insertText(e.key),!0):!1}handleTextInput(e){return e?(this.insertText(e),!0):!1}handleMouseDown(e,t,i){if(i){const n=this.cursorLogic.hitTest(e,t);if(n<0)return;this.cursorLogic.setSelectionWithDirection(this.selectionStart,n)}else if(!this.cursorLogic.moveToClick(e,t))return;this.isDragging=!0,this.syncStateFromCursor(),this.emit("cursorMove"),this.emit("selectionChange")}handleMouseMove(e,t){this.isDragging&&(this.cursorLogic.updateSelectionDrag(e,t),this.syncStateFromCursor(),this.emit("selectionChange"))}handleMouseUp(){this.isDragging=!1}handleDoubleClick(e,t){const i=this.cursorLogic.hitTest(e,t);if(i<0)return;const n=this.getChars();let r=i,o=i;for(;r>0&&!/\s/.test(n[r-1]??"");)r-=1;for(;o<n.length&&!/\s/.test(n[o]??"");)o+=1;this.cursorLogic.setSelection(r,o),this.cursorLogic.moveTo(o),this.syncStateFromCursor(),this.emit("selectionChange")}update(){const e=this.cursorLogic.getCursorState(),t=this.cursorLogic.getSelection(),i=this.getActiveCursorRenderState(e.position,e.lineInfo.height),n=this.cursorLogic.getSelectedCharBoxes();this.cursorRenderer.updateCursor(i.position,i.height),this.cursorRenderer.updateSelection(n),this.cursorRenderer.updateDebugInfo({containerBox:this.layoutContainer,charBoxes:this.cursorLogic.getCharBoxes(),chars:this.getChars(),lines:this.cursorLogic.getLines()}),this.cursorRenderer.setSelectionStyle({fillColor:t!=null&&t.isBackwards?"rgba(150,0,255,0.25)":"rgba(0,120,255,0.30)"}),this.cursorRenderer.render(),this.updateImeAnchorPosition(),this.updateToolbarPosition()}dispose(){var e;V.activeEditor===this?this.deactivateEditor():this.detachIme(),this.detachPointerInteractions(),this.unbindReopenDoubleClick(),this.disposeRenderedObject(this.renderedObject),this.renderedObject=null,this.disposeBoundingBox(),this.mtextRenderer.destroy(),this.cursorRenderer.dispose(),this.cursorLogic.destroy(),this.handlers.change.clear(),this.handlers.selectionChange.clear(),this.handlers.cursorMove.clear(),this.handlers.show.clear(),this.handlers.close.clear(),V.instances.delete(this),V.instances.size===0&&((e=V.sharedToolbar)==null||e.dispose(),V.sharedToolbar=null,V.sharedToolbarContainer=null,V.sharedToolbarFontFamiliesKey="",V.sharedToolbarColorPickerFactory=null,V.activeEditor=null)}closeEditor(){this.closed||(this.closed=!0,this.detachPointerInteractions(),this.deactivateEditor(),this.emit("close"))}showEditor(){const e=this.lastImeTarget;if(!e)return!1;const t=this.closed;return this.closed=!1,this.attachPointerInteractions(e),this.activateEditor(),t&&this.emit("show"),!0}attachPointerInteractions(e){this.detachPointerInteractions(),this.pointerTarget=e,e.addEventListener("mousedown",this.onPointerMouseDown),e.addEventListener("mousemove",this.onPointerMouseMove),e.addEventListener("dblclick",this.onPointerDoubleClick),window.addEventListener("mouseup",this.onPointerMouseUp)}detachPointerInteractions(){this.pointerTarget&&(this.pointerTarget.removeEventListener("mousedown",this.onPointerMouseDown),this.pointerTarget.removeEventListener("mousemove",this.onPointerMouseMove),this.pointerTarget.removeEventListener("dblclick",this.onPointerDoubleClick),window.removeEventListener("mouseup",this.onPointerMouseUp),this.pointerTarget=null)}on(e,t){this.handlers[e].add(t)}off(e,t){(e==="change"||e==="selectionChange"||e==="cursorMove"||e==="show"||e==="close")&&this.handlers[e].delete(t)}getCursorWorldPosition(){const e=this.cursorLogic.getCursorState(),t=this.getActiveCursorRenderState(e.position,e.lineInfo.height).position;return{x:this.position.x+t.x,y:this.position.y+t.y,z:this.position.z}}getMTextInsertionPoint(){return this.position.clone()}getState(){return{mtextString:this.getText(),cursorIndex:this.cursorIndex,selectionStart:this.selectionStart,selectionEnd:this.selectionEnd,currentFormat:this.getCurrentFormat()}}isActiveEditor(){return V.activeEditor===this}activateEditor(){var i;if(this.closed)return;const e=V.activeEditor;e&&e!==this&&e.deactivateEditor(),V.activeEditor=this;const t=this.imeTarget??this.lastImeTarget;t&&this.attachImeBridge(t),this.cursorRenderer.show(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!0),t&&this.toolbarEnabled?this.mountToolbar(t):(i=V.sharedToolbar)==null||i.setVisible(!1)}deactivateEditor(){var e;this.isDragging=!1,this.detachIme(),this.cursorRenderer.hide(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!1),V.activeEditor===this&&(V.activeEditor=null,(e=V.sharedToolbar)==null||e.setVisible(!1))}attachImeBridge(e){this.detachIme(),this.imeTarget=e;const t=document.createElement("textarea");t.setAttribute("aria-hidden","true"),t.autocapitalize="off",t.autocomplete="off",t.spellcheck=!1,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.style.width="2px",t.style.height="2px",t.style.opacity="0",t.style.pointerEvents="none",t.style.zIndex="2147483647",document.body.appendChild(t),this.imeInput=t,t.addEventListener("keydown",this.onImeKeyDown),t.addEventListener("beforeinput",this.onImeBeforeInput),t.addEventListener("compositionstart",this.onImeCompositionStart),t.addEventListener("compositionend",this.onImeCompositionEnd),window.addEventListener("keydown",this.onWindowKeyDown),e.addEventListener("mousedown",this.onImeTargetMouseDown),this.updateImeAnchorPosition(),this.focusImeInput()}getActiveToolbar(){if(!this.isActiveEditor())return null;const e=V.sharedToolbar;if(!e)throw new Error("[mtext-input-box] Failed to create shared toolbar");return e}createToolbarSessionOptions(e){return{anchorElement:e,onFormatChange:t=>{this.setCurrentFormat(t)},onToggleStack:()=>{this.toggleStackSelection()},onToggleSuperscript:()=>this.toggleScriptSelection("superscript"),onToggleSubscript:()=>this.toggleScriptSelection("subscript")}}ensureSharedToolbar(e){var o,a;const t=this.toolbarContainer??document.body,i=((o=this.toolbarFontFamilies)==null?void 0:o.join("\0"))??"";if(!V.sharedToolbar||V.sharedToolbarContainer!==t||V.sharedToolbarFontFamiliesKey!==i||V.sharedToolbarColorPickerFactory!==(this.toolbarColorPicker??null)){(a=V.sharedToolbar)==null||a.dispose();const l={...this.createToolbarSessionOptions(e),container:t,theme:this.toolbarTheme,initialFormat:this.currentFormat};this.toolbarFontFamilies&&(l.fontFamilies=this.toolbarFontFamilies),this.toolbarColorPicker&&(l.colorPicker=this.toolbarColorPicker),V.sharedToolbar=new Xp(l),V.sharedToolbarContainer=t,V.sharedToolbarFontFamiliesKey=i,V.sharedToolbarColorPickerFactory=this.toolbarColorPicker??null}const r=V.sharedToolbar;if(!r)throw new Error("[mtext-input-box] Failed to create shared toolbar");return r}mountToolbar(e){if(!this.toolbarEnabled||!this.isActiveEditor())return;const t=this.ensureSharedToolbar(e);t.setTheme(this.toolbarTheme),t.setSession(this.createToolbarSessionOptions(e)),t.setVisible(!0),t.setFormat(this.currentFormat),this.updateToolbarStackState(),this.updateToolbarPosition()}updateToolbarPosition(){if(!this.toolbarEnabled||!this.isActiveEditor()||!this.imeTarget)return;const e=this.getActiveToolbar();if(!e)return;const t=this.getEditorScreenBounds();t&&e.setAnchor(t.minX,t.minY-this.toolbarOffsetY)}getEditorScreenBounds(){if(!this.imeTarget)return null;const e=this.imeTarget.getBoundingClientRect(),t=this.position.x+this.layoutContainer.x,i=t+this.layoutContainer.width,n=this.position.y+this.layoutContainer.y,r=n+this.layoutContainer.height,o=[new L.Vector3(t,n,this.position.z),new L.Vector3(i,n,this.position.z),new L.Vector3(t,r,this.position.z),new L.Vector3(i,r,this.position.z)];let a=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY,c=Number.POSITIVE_INFINITY,h=Number.NEGATIVE_INFINITY;for(const p of o){const m=p.clone().project(this.camera),g=e.left+(m.x+1)*.5*e.width,f=e.top+(1-m.y)*.5*e.height;a=Math.min(a,g),l=Math.max(l,g),c=Math.min(c,f),h=Math.max(h,f)}return!Number.isFinite(a)||!Number.isFinite(c)?null:{minX:a,maxX:l,minY:c,maxY:h}}pointerEventToEditorLocal(e){const t=this.pointerTarget??this.imeTarget;return this.pointerEventToEditorLocalByTarget(e,t)}pointerEventToEditorLocalByTarget(e,t){if(!t)return null;const i=t.getBoundingClientRect();if(i.width<=0||i.height<=0)return null;const n=(e.clientX-i.left)/i.width*2-1,r=-((e.clientY-i.top)/i.height)*2+1,o=new L.Vector3(n,r,-1).unproject(this.camera),l=new L.Vector3(n,r,1).unproject(this.camera).sub(o);if(Math.abs(l.z)<1e-8)return null;const c=(this.position.z-o.z)/l.z,h=o.add(l.multiplyScalar(c));return{x:h.x-this.position.x,y:h.y-this.position.y}}shouldReopenFromDoubleClick(e){return this.hitTestRenderedObject(e)}hitTestRenderedObject(e){if(!this.renderedObject||!this.reopenTarget)return!1;const t=this.reopenTarget.getBoundingClientRect();if(t.width<=0||t.height<=0)return!1;const i=(e.clientX-t.left)/t.width*2-1,n=-((e.clientY-t.top)/t.height)*2+1,r=new L.Raycaster;return r.setFromCamera(new L.Vector2(i,n),this.camera),r.intersectObject(this.renderedObject,!0).length>0}bindReopenDoubleClick(e){this.reopenTarget!==e&&(this.unbindReopenDoubleClick(),this.reopenTarget=e,e.addEventListener("dblclick",this.onReopenDoubleClick))}unbindReopenDoubleClick(){this.reopenTarget&&(this.reopenTarget.removeEventListener("dblclick",this.onReopenDoubleClick),this.reopenTarget=null)}isPointInContainer(e,t){const i=this.layoutContainer,n=i.x+i.width,r=i.y+i.height;return e>=i.x&&e<=n&&t>=i.y&&t<=r}async initializeRenderer(){try{await this.mtextRenderer.loadFonts([pn]),this.rendererReady=!0,this.ensureFontsLoaded(),this.relayout()}catch(e){console.error("[mtext-input-box] Failed to initialize mtext renderer fonts",e)}}relayout(){if(!this.rendererReady){this.mtextInsertionOffset.set(0,0,0);const e=this.createFallbackCharBoxes();this.layoutContainer=e.containerBox,this.updateCursorData(e.charBoxes,e.lineBreakIndices,e.lineLayouts),this.updateBoundingBoxGeometry();return}this.ensureFontsLoaded();try{const e=this.createMTextData(),t=this.createTextStyle(),i=this.resolveRenderColorSettings(),n=this.mtextRenderer.syncRenderMText(e,t,i);this.pruneExtraMTextLayoutRoots(n),this.replaceRenderedObject(n);const r=this.extractBoxesFromRenderedObject(n);this.mtextInsertionOffset.set(0,0,0),this.normalizeRenderedTopAlignment(n,r),this.layoutContainer=r.containerBox,this.updateCursorData(r.charBoxes,r.lineBreakIndices,r.lineLayouts),this.updateBoundingBoxGeometry()}catch(e){console.error("[mtext-input-box] Failed to sync render MTEXT",e),this.mtextInsertionOffset.set(0,0,0);const t=this.createFallbackCharBoxes();this.layoutContainer=t.containerBox,this.updateCursorData(t.charBoxes,t.lineBreakIndices,t.lineLayouts),this.updateBoundingBoxGeometry()}}ensureFontsLoaded(){if(this.pendingFontLoad)return;const e=this.collectFontNamesForText(),t=e.map(i=>i.toLowerCase()).sort().join("|");!t||t===this.lastFontKey||(this.lastFontKey=t,this.pendingFontLoad=this.mtextRenderer.loadFonts(e).then(()=>{}).catch(i=>{console.warn("[mtext-input-box] Failed to load fonts for MTEXT",i)}).finally(()=>{this.pendingFontLoad=null,this.rendererReady&&this.relayout()}))}collectFontNamesForText(){const e=new Set,t=i=>{if(!i)return;const n=i.trim();n&&e.add(n)};t(this.defaultTextStyle.font),t(this.defaultTextStyle.bigFont);try{const i=D.MText.getFonts(this.mtextString||"",!0);for(const n of i)t(n)}catch(i){console.warn("[mtext-input-box] Failed to parse fonts from MTEXT",i)}return e.size===0&&e.add(pn),[...e]}updateCursorData(e,t,i){this.latestCursorLayoutData={containerBox:{...this.layoutContainer},charBoxes:e.map(l=>({...l})),...t?{lineBreakIndices:[...t]}:{},...i?{lineLayouts:i.map(l=>({...l}))}:{}},this.cursorLogic.updateData(this.layoutContainer,e,t,i);const n=Math.min(this.cursorIndex,this.charCount()),r=Math.max(0,this.cursorLogic.getLineCount()-1),o=this.pendingCursorLineHint===null?null:Math.max(0,Math.min(this.pendingCursorLineHint,r));this.pendingCursorLineHint=null,this.cursorLogic.moveTo(n,o),this.selectionStart!==this.selectionEnd?this.cursorLogic.setSelection(this.selectionStart,this.selectionEnd):this.cursorLogic.clearSelection(),this.syncStateFromCursor();const a=this.unionLayoutContainerWithCursorLines(this.layoutContainer);(Math.abs(a.y-this.layoutContainer.y)>1e-6||Math.abs(a.height-this.layoutContainer.height)>1e-6)&&(this.layoutContainer=a,this.latestCursorLayoutData.containerBox={...this.layoutContainer},this.cursorLogic.updateData(this.layoutContainer,e,t,i),this.cursorLogic.moveTo(n,o),this.selectionStart!==this.selectionEnd?this.cursorLogic.setSelection(this.selectionStart,this.selectionEnd):this.cursorLogic.clearSelection(),this.syncStateFromCursor())}unionLayoutContainerWithCursorLines(e){const t=this.cursorLogic.getLines();if(t.length===0)return e;let i=e.y,n=e.y+e.height;for(const r of t){if(r.charCount!==0)continue;const o=r.y-r.height/2,a=r.y+r.height/2;Number.isFinite(o)&&(i=Math.min(i,o)),Number.isFinite(a)&&(n=Math.max(n,a))}return!Number.isFinite(i)||!Number.isFinite(n)||n<i?e:{...e,y:i,height:n-i}}computeEditorVerticalBounds(e,t,i){const n=()=>({minY:i.y-i.height/2,maxY:i.y+i.height/2}),r=(l,c,h,p)=>l<p+1e-4&&c>h-1e-4;if(e.length===0&&t.length===0)return n();if(e.length===0){let l=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(const h of t)l=Math.min(l,h.y-h.height/2),c=Math.max(c,h.y+h.height/2);return Number.isFinite(l)&&Number.isFinite(c)&&c>=l?{minY:l,maxY:c}:n()}if(t.length===0){let l=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(const h of e){const p=h.y-h.height/2,m=h.y+h.height/2;l=Math.min(l,p),c=Math.max(c,m)}return Number.isFinite(l)&&Number.isFinite(c)&&c>=l?{minY:l,maxY:c}:n()}let o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const l of e){const c=l.y-l.height/2,h=l.y+l.height/2,p=t.filter(m=>{const g=m.y-m.height/2,f=m.y+m.height/2;return r(g,f,c,h)});if(p.length===0)o=Math.min(o,c),a=Math.max(a,h);else for(const m of p)o=Math.min(o,m.y-m.height/2),a=Math.max(a,m.y+m.height/2)}for(const l of t){const c=l.y-l.height/2,h=l.y+l.height/2;e.some(m=>{const g=m.y-m.height/2,f=m.y+m.height/2;return r(c,h,g,f)})||(o=Math.min(o,c),a=Math.max(a,h))}return!Number.isFinite(o)||!Number.isFinite(a)||a<o?n():{minY:o,maxY:a}}extractBoxesFromRenderedObject(e){const t=e.createLayoutData(),i=[],n=((t==null?void 0:t.lines)??[]).filter(p=>Number.isFinite(p.y)&&Number.isFinite(p.height)).map(p=>({y:p.y-this.position.y,height:Math.max(1,p.height)}));for(const p of(t==null?void 0:t.chars)??[]){const m=p.box?this.toLocalBox(p.box):void 0;!m||!(Number.isFinite(m.x)&&Number.isFinite(m.y)&&Number.isFinite(m.width)&&Number.isFinite(m.height))||i.push(m)}const r=(t.lines??[]).map(p=>p.breakIndex).filter(p=>Number.isInteger(p)).filter(p=>p>=0&&p<=i.length),o=this.toLocalBox(e.box),{minY:a,maxY:l}=this.computeEditorVerticalBounds(n,i,o),c={x:Ja(this.width,this.editorAttachmentPoint),y:a,width:Math.max(1,this.width),height:Math.max(0,l-a)},h=this.getFallbackLineAdvance();if(c.height<h){const p=h-c.height;c.y-=p,c.height=h}return{containerBox:c,charBoxes:i,...r.length>0?{lineBreakIndices:r}:{},...n.length>0?{lineLayouts:n}:{}}}normalizeRenderedTopAlignment(e,t){var r;const n=-(t.containerBox.y+t.containerBox.height);!Number.isFinite(n)||Math.abs(n)<1e-8||(this.mtextInsertionOffset.set(0,n,0),e.position.y+=n,e.updateMatrixWorld(!0),t.containerBox.y+=n,t.charBoxes.forEach(o=>{o.y+=n}),(r=t.lineLayouts)==null||r.forEach(o=>{o.y+=n}))}toLocalBox(e){const t=e.min.x-this.position.x,i=e.max.x-this.position.x,n=e.min.y-this.position.y,r=e.max.y-this.position.y,o=Math.max(0,i-t),a=Math.max(0,r-n);return{x:t,y:n+a/2,width:o,height:a}}createFallbackCharBoxes(){const e=this.getFallbackLineAdvance(),t=[],i=[],n=[];let r=0,o=0,a=-e;n.push({y:o-e/2,height:e});for(const l of this.getChars()){if(l===`
125
+ `){i.push(t.length),r=0,o-=e,a=Math.min(a,o-e),n.push({y:o-e/2,height:e});continue}const c=Math.max(1,this.currentFormat.fontSize*.6);this.enableWordWrap&&r>0&&r+c>this.width&&(i.push(t.length),r=0,o-=e,a=Math.min(a,o-e),n.push({y:o-e/2,height:e})),t.push({x:r,y:o-e/2,width:c,height:e}),r+=c}return{containerBox:{x:Ja(this.width,this.editorAttachmentPoint),y:a,width:this.width,height:Math.max(1,-a)},charBoxes:t,lineBreakIndices:i,lineLayouts:n}}createBoundingBox(e,t){if(!e)return;const i=typeof(t==null?void 0:t.color)=="number"?t.color:new L.Color((t==null?void 0:t.color)??"#58a6ff");this.boundingBoxPadding=Math.max(0,(t==null?void 0:t.padding)??1),this.boundingBoxZOffset=(t==null?void 0:t.zOffset)??.01;const n=new L.LineBasicMaterial({color:i,transparent:!0,opacity:(t==null?void 0:t.opacity)??.9,depthTest:!1,depthWrite:!1}),r=new L.BufferGeometry;this.boundingBoxObject=new L.LineLoop(r,n),this.boundingBoxObject.position.z=this.boundingBoxZOffset,this.scene.add(this.boundingBoxObject)}updateBoundingBoxGeometry(){if(!this.boundingBoxObject)return;this.boundingBoxObject.geometry.dispose();const t=this.boundingBoxPadding,i=this.position.x+this.layoutContainer.x-t,n=this.position.y+this.layoutContainer.y-t,r=this.position.x+this.layoutContainer.x+this.layoutContainer.width+t,o=this.position.y+this.layoutContainer.y+this.layoutContainer.height+t,a=this.position.z;this.boundingBoxObject.geometry=new L.BufferGeometry().setFromPoints([new L.Vector3(i,n,a),new L.Vector3(r,n,a),new L.Vector3(r,o,a),new L.Vector3(i,o,a)])}disposeBoundingBox(){if(!this.boundingBoxObject)return;this.boundingBoxObject.removeFromParent(),this.boundingBoxObject.geometry.dispose();const e=Array.isArray(this.boundingBoxObject.material)?this.boundingBoxObject.material:[this.boundingBoxObject.material];for(const t of e)t.dispose();this.boundingBoxObject=null}replaceRenderedObject(e){this.disposeRenderedObject(this.renderedObject),this.removeStrayInputBoxSceneRootsExcept(e),this.forceVisibleMaterialState(e),e.userData[fn]=this,this.renderedObject=e,this.scene.add(e)}removeStrayInputBoxSceneRootsExcept(e){const t=e;for(let i=this.scene.children.length-1;i>=0;i--){const n=this.scene.children[i];if(!n||n===t)continue;n.userData[fn]===this&&(this.scene.remove(n),this.disposeMTextRootResources(n),delete n.userData[fn])}}forceVisibleMaterialState(e){e.traverse(t=>{const i=t,n=i.material?Array.isArray(i.material)?i.material:[i.material]:[];for(const r of n){const o=r;typeof o.side<"u"&&(o.side=L.DoubleSide),typeof o.depthTest<"u"&&(o.depthTest=!1),typeof o.depthWrite<"u"&&(o.depthWrite=!1),typeof o.transparent<"u"&&typeof o.opacity<"u"&&(o.transparent=o.opacity<1),o.needsUpdate=!0}})}disposeDetachedThreeSubtree(e){e.traverse(t=>{const i=t;i.geometry&&i.geometry.dispose();const n=i.material?Array.isArray(i.material)?i.material:[i.material]:[];for(const r of n){const o=r;o.map&&o.map.dispose(),r.dispose()}})}pruneExtraMTextLayoutRoots(e){for(;e.children.length>1;){const t=e.children[0];if(!t)break;e.remove(t),this.disposeDetachedThreeSubtree(t)}}disposeMTextRootResources(e){const t=e;if(typeof t.dispose=="function"){t.dispose();return}this.disposeDetachedThreeSubtree(e)}disposeRenderedObject(e){e&&(e.removeFromParent(),delete e.userData[fn],this.disposeMTextRootResources(e))}isExplicitAci(e){return e!==null&&Number.isInteger(e)&&e>0&&e<256}normalizeColorNumber(e){return Math.max(0,Math.min(16777215,Math.round(e)))}resolveAciColor(e){const t=D.getColorByIndex(e);return this.normalizeColorNumber(Number.isFinite(t)?t:16777215)}resolveBaseColor(){return this.isExplicitAci(this.baseFormat.aci)?this.resolveAciColor(this.baseFormat.aci):this.baseFormat.rgb!==null?this.normalizeColorNumber(this.baseFormat.rgb):16777215}resolveBaseFormatColor(e){const t=e.color;if(t.isRgb&&t.rgbValue!==null)return{aci:null,rgb:this.normalizeColorNumber(t.rgbValue)};if(t.isAci&&t.aci!==null){const i=t.aci;return Number.isInteger(i)&&i>=1&&i<=255?{aci:i,rgb:null}:i===0?{aci:null,rgb:this.normalizeColorNumber(e.byBlockColor)}:{aci:null,rgb:this.normalizeColorNumber(e.byLayerColor)}}return{aci:null,rgb:this.normalizeColorNumber(e.byLayerColor)}}createBaseFormatFromTextStyle(e,t){const i=Ap();i.fontFamily=e.font||i.fontFamily,i.fontSize=Math.max(1,e.fixedTextHeight);const n=this.resolveBaseFormatColor(t);i.aci=n.aci,i.rgb=n.rgb;const r=e.widthFactor;i.widthFactor=typeof r=="number"&&Number.isFinite(r)?Math.max(.01,r):1;const o=e.obliqueAngle;return i.obliqueAngle=typeof o=="number"&&Number.isFinite(o)?o:0,i.tracking=1,i}createMTextData(){const e={text:this.mtextString,height:Math.max(1,this.defaultTextStyle.fixedTextHeight),width:this.width,position:{x:this.position.x,y:this.position.y,z:this.position.z},attachmentPoint:this.editorAttachmentPoint,drawingDirection:D.MTextFlowDirection.LEFT_TO_RIGHT,widthFactor:1,collectCharBoxes:!0};return this.editorLineSpaceFactor!=null&&Number.isFinite(this.editorLineSpaceFactor)&&(e.lineSpaceFactor=this.editorLineSpaceFactor),e}getLineSpacingFactor(){return this.editorLineSpaceFactor??V.DEFAULT_LINE_SPACE_FACTOR}setLineSpacingFactor(e){if(!Number.isFinite(e)||e<=0)return;const t=V.DEFAULT_LINE_SPACE_FACTOR,i=e>=1?Math.max(.01,t+(e-1)/D.LINE_SPACING_SCALE_FACTOR):e;this.editorLineSpaceFactor=i,this.relayout(),this.emit("change")}clearLineSpacing(){this.editorLineSpaceFactor=null,this.relayout(),this.emit("change")}getFallbackLineAdvance(){return Math.max(1,this.currentFormat.fontSize*V.FALLBACK_LINE_ADVANCE_RATIO)}createTextStyle(){return{...this.defaultTextStyle}}resolveRenderColorSettings(){if(this.colorSettings)return this.colorSettings;const e=this.toolbarTheme==="light"?0:16777215;return{byLayerColor:e,byBlockColor:e,color:new D.MTextColor(256)}}focusImeInput(){this.imeInput&&this.imeInput.focus({preventScroll:!0})}refocusImeInputSoon(){this.imeInput&&(this.imeFocusTimer!==null&&window.clearTimeout(this.imeFocusTimer),this.imeFocusTimer=window.setTimeout(()=>{this.focusImeInput(),this.imeFocusTimer=null},0))}updateImeAnchorPosition(){if(!this.imeInput||!this.imeTarget)return;const e=this.getCursorWorldPosition(),i=new L.Vector3(e.x,e.y,e.z).project(this.camera),n=this.imeTarget.getBoundingClientRect(),r=n.left+(i.x+1)*.5*n.width,o=n.top+(1-i.y)*.5*n.height;this.imeInput.style.left=`${Math.round(r)}px`,this.imeInput.style.top=`${Math.round(o)}px`}syncStateFromCursor(){this.cursorIndex=this.cursorLogic.getCurrentIndex();const e=this.cursorLogic.getSelection();e?(this.selectionStart=e.start,this.selectionEnd=e.end):(this.selectionStart=this.cursorIndex,this.selectionEnd=this.cursorIndex),this.syncDocumentFromUiState(),this.refreshCurrentFormatFromDocument()}consumeMove(e){return this.moveCursor(e),!0}consumeExtend(e){return this.extendSelection(e),!0}isMacPlatform(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}emit(e){for(const t of this.handlers[e])t()}findPrevWordStart(e){const t=this.getChars();let i=Math.max(0,e-1);for(;i>0&&/\s/.test(t[i]??"");)i-=1;for(;i>0&&!/\s/.test(t[i-1]??"");)i-=1;return i}findNextWordStart(e){const t=this.getChars();let i=Math.min(t.length,e);for(;i<t.length&&!/\s/.test(t[i]??"");)i+=1;for(;i<t.length&&/\s/.test(t[i]??"");)i+=1;return i}getChars(){const e=[];for(const t of this.document.ast.nodes){if(t.type==="char"){e.push(t.value);continue}if(t.type==="stack"){e.push("");continue}(t.type==="paragraphBreak"||t.type==="columnBreak"||t.type==="wrapAtDimLine")&&e.push(`
126
+ `)}return e}charCount(){return this.getChars().length}getActiveCursorRenderState(e,t){var a;const i=this.cursorLogic.getCharBoxes(),n=this.cursorLogic.getCurrentIndex(),r=this.cursorLogic.getCurrentLineInfo();if(i.length===0){const l=(a=this.latestCursorLayoutData.lineLayouts)==null?void 0:a[0];if(l&&Number.isFinite(l.y)&&Number.isFinite(l.height)){const h=Math.max(1,l.height);return{position:{x:e.x,y:l.y},height:h}}const c=Math.max(1,this.getFallbackLineAdvance());return{position:{x:e.x,y:this.layoutContainer.y+c/2},height:c}}if(n<=0||n===r.startIndex){if(!(r.charCount<=0||r.endIndex<r.startIndex)){const h=Math.max(0,Math.min(r.startIndex,i.length-1)),p=i[h];if(p)return{position:{x:e.x,y:p.y},height:Math.max(1,p.height)}}const c=r.height??t;return{position:{x:e.x,y:r.y??e.y},height:Math.max(1,c)}}const o=i[Math.min(n-1,i.length-1)];return o?{position:{x:o.x+o.width,y:o.y},height:Math.max(1,o.height)}:{position:e,height:Math.max(1,t)}}getNodeLogicalSpan(e){switch(e.type){case"char":return 1;case"stack":return 1;case"paragraphBreak":case"columnBreak":case"wrapAtDimLine":return 0;default:return 0}}toLogicalIndexFromDocumentIndex(e){const t=Math.max(0,Math.min(e,this.document.ast.nodes.length));let i=0;for(let n=0;n<t;n+=1){const r=this.document.ast.nodes[n];r&&(i+=this.getNodeLogicalSpan(r))}return i}toDocumentIndexFromLogicalIndex(e,t=!0,i){var h,p;const n=this.document.ast.nodes;if(n.length===0)return 0;const r=this.charCount(),o=Math.max(0,Math.min(e,r)),a=[];let l=0,c=0;for(let m=0;m<=n.length&&(l===o&&a.push({index:m,lineIndex:c}),m!==n.length);m+=1){const g=n[m];if(!g)continue;const f=this.getNodeLogicalSpan(g);f===0?c+=1:l+=f}if(a.length===0)return n.length;if(i!==void 0&&Number.isFinite(i)){const m=this,f=(typeof m.resolveCandidateByVisualLineHint=="function"?m.resolveCandidateByVisualLineHint:V.prototype.resolveCandidateByVisualLineHint).call(this,a,o,i);if(f!==void 0)return f;const w=((h=a[0])==null?void 0:h.lineIndex)??0,v=((p=a[a.length-1])==null?void 0:p.lineIndex)??0;if(i<w||i>v)return t?a[a.length-1].index:a[0].index;let x=a[0],S=Math.abs(x.lineIndex-i);for(let P=1;P<a.length;P+=1){const A=a[P],_=Math.abs(A.lineIndex-i);_<S&&(x=A,S=_)}return x.index}return t?a[a.length-1].index:a[0].index}resolveCandidateByVisualLineHint(e,t,i){if(e.length<=1||this.cursorLogic==null||typeof this.cursorLogic.getLines!="function")return;const n=this.cursorLogic.getLines();if(!Array.isArray(n)||n.length===0)return;const r=[];for(let l=0;l<n.length;l+=1){const c=n[l];c&&t>=c.startIndex&&t<=c.endIndex+1&&r.push(l)}if(r.length!==e.length)return;const o=r.indexOf(i);if(o<0)return;const a=e[o];return a==null?void 0:a.index}syncUiStateFromDocument(){this.mtextString=this.document.toMText();const e=this.charCount();this.cursorIndex=Math.min(this.toLogicalIndexFromDocumentIndex(this.document.cursor),e);const t=this.document.selection;t?(this.selectionStart=this.toLogicalIndexFromDocumentIndex(t.start),this.selectionEnd=this.toLogicalIndexFromDocumentIndex(t.end)):(this.selectionStart=this.cursorIndex,this.selectionEnd=this.cursorIndex),this.refreshCurrentFormatFromDocument()}syncDocumentFromUiState(){const e=this.getSelectionRange();if(!e.isCollapsed){const r=this.toDocumentIndexFromLogicalIndex(e.start,!0),o=this.toDocumentIndexFromLogicalIndex(e.end,!1);this.document.setSelection(r,o);return}this.document.clearSelection();const t=this.cursorLogic.getCursorState(),i=t.lineIndex,n=!(t.isAtLineEnd&&!t.isAtLineStart);this.document.cursor=this.toDocumentIndexFromLogicalIndex(this.cursorIndex,n,i>=0?i:void 0)}refreshCurrentFormatFromDocument(){var t,i;const e=this.inferCurrentFormatFromDocument();if(this.updateToolbarStackState(),!e){(t=this.getActiveToolbar())==null||t.setFormat(this.currentFormat);return}Na(this.currentFormat,e)||(this.currentFormat=e),(i=this.getActiveToolbar())==null||i.setFormat(this.currentFormat)}toggleStackSelection(){const e=this.getSelectionRange();e.isCollapsed||this.commitHistoryEdit(()=>{var c;this.syncDocumentFromUiState();const t=this.toDocumentIndexFromLogicalIndex(e.start,!0),i=this.toDocumentIndexFromLogicalIndex(e.end,!1);if(i<=t)return;const n=this.document.ast.nodes.slice(t,i);if(n.length===1&&((c=n[0])==null?void 0:c.type)==="stack"){const h=n[0],p=this.stackNodeToPlainText(h.numerator,h.denominator,h.divider),m=Array.from(p).map(g=>({type:"char",value:g,style:this.cloneDocumentStyle(h.style)}));if(m.length===0)return;this.document.transaction(g=>{g.ast.nodes.splice(t,1,...m),g.setSelection(t,t+m.length)}),this.syncUiStateFromDocument(),this.relayout();return}if(!n.every(h=>(h==null?void 0:h.type)==="char"))return;const r=n.map(h=>h.value).join(""),o=this.parseStackParts(r);if(!o)return;const a=n[0];if(!a)return;const l={type:"stack",numerator:o.numerator,denominator:o.denominator,divider:o.divider,style:this.cloneDocumentStyle(a.style)};this.document.transaction(h=>{h.ast.nodes.splice(t,i-t,l),h.setSelection(t,t+1)}),this.syncUiStateFromDocument(),this.relayout()})}toggleScriptSelection(e){const t=this.getSelectionRange();if(t.isCollapsed)return!1;let i=!1;return this.commitHistoryEdit(()=>{var p;this.syncDocumentFromUiState();const n=this.toDocumentIndexFromLogicalIndex(t.start,!0),r=this.toDocumentIndexFromLogicalIndex(t.end,!1);if(r<=n)return;const o=this.document.ast.nodes.slice(n,r);if(o.length===1&&((p=o[0])==null?void 0:p.type)==="stack"){const m=o[0],g=this.scriptStackToPlainText(m.numerator,m.denominator,m.divider);if(!g)return;const f=this.cloneDocumentStyle(m.style);f.script="normal",f.align=D.MTextLineAlignment.MIDDLE;const w=Array.from(g).map(v=>({type:"char",value:v,style:this.cloneDocumentStyle(f)}));if(w.length===0)return;this.document.transaction(v=>{v.ast.nodes.splice(n,1,...w),v.setSelection(n,n+w.length)}),this.syncUiStateFromDocument(),this.relayout(),i=!0;return}if(!o.every(m=>(m==null?void 0:m.type)==="char"))return;const a=o.map(m=>m.value).join("");if(a.length===0)return;const l=o[0];if(!l)return;const c=this.cloneDocumentStyle(l.style);c.script=e,c.align=e==="superscript"?D.MTextLineAlignment.TOP:D.MTextLineAlignment.BOTTOM;const h={type:"stack",numerator:e==="superscript"?a:"",denominator:e==="subscript"?a:"",divider:"^",style:this.cloneDocumentStyle(c)};this.document.transaction(m=>{m.ast.nodes.splice(n,r-n,h),m.setSelection(n,n+1)}),this.syncUiStateFromDocument(),this.relayout(),i=!0}),i}commitHistoryEdit(e){const t=this.createHistorySnapshot();e(),!this.isSameAsCurrent(t)&&(this.undoStack.push(t),this.undoStack.length>this.maxHistorySize&&this.undoStack.splice(0,this.undoStack.length-this.maxHistorySize),this.redoStack=[],this.emit("change"),this.emit("selectionChange"),this.emit("cursorMove"))}createHistorySnapshot(){return{ast:this.cloneAst(this.document.ast),cursor:this.document.cursor,selection:this.document.selection?{...this.document.selection}:null,currentFormat:{...this.currentFormat}}}restoreHistorySnapshot(e){this.document=new me(this.cloneAst(e.ast)),e.selection?this.document.setSelection(e.selection.start,e.selection.end):(this.document.cursor=e.cursor,this.document.clearSelection()),this.uiAdapter=new ar(this.document),this.currentFormat={...e.currentFormat},this.syncUiStateFromDocument(),this.relayout(),this.emit("change"),this.emit("selectionChange"),this.emit("cursorMove")}isSameAsCurrent(e){if(e.cursor!==this.document.cursor)return!1;const t=this.document.selection;return!!e.selection!=!!t||e.selection&&t&&(e.selection.start!==t.start||e.selection.end!==t.end)||!Na(e.currentFormat,this.currentFormat)?!1:this.document.toMText()===this.buildMTextFromAst(e.ast)}buildMTextFromAst(e){return new me(this.cloneAst(e)).toMText()}clearHistory(){this.undoStack=[],this.redoStack=[]}cloneAst(e){return{nodes:e.nodes.map(t=>t.type==="char"?{...t,style:this.cloneDocumentStyle(t.style)}:t.type==="stack"?{...t,style:this.cloneDocumentStyle(t.style)}:{...t,style:this.cloneDocumentStyle(t.style)})}}stackNodeToPlainText(e,t,i){if(i==="^"){if(e.length===0&&t.length>0)return`^${t.trimStart()}`;if(e.length>0&&t.length===0)return`${e.trimEnd()}^`}return`${e}${i}${t}`}scriptStackToPlainText(e,t,i){if(i!=="^")return null;const n=e.trim().length>0,r=t.trim().length>0;return n===r?null:n?e.trim():t.trim()}parseStackParts(e){const t=[];for(let l=0;l<e.length;l+=1){const c=e[l];(c==="/"||c==="#"||c==="^")&&t.push({index:l,divider:c})}if(t.length!==1)return null;const i=t[0];if(!i)return null;const{index:n,divider:r}=i,o=e.slice(0,n),a=e.slice(n+1);if(r==="^"){const l=o.trim().length>0,c=a.trim().length>0;return!l&&!c?null:{numerator:o,denominator:a,divider:r}}return o.trim().length===0||a.trim().length===0?null:{numerator:o,denominator:a,divider:r}}updateToolbarStackState(){var a;const e=this.getActiveToolbar();if(!e)return;const t=this.getSelectionRange();if(t.isCollapsed){e.setStackActive(!1);return}const i=this.toDocumentIndexFromLogicalIndex(t.start,!0),n=this.toDocumentIndexFromLogicalIndex(t.end,!1),r=this.document.ast.nodes.slice(i,n),o=r.length===1&&((a=r[0])==null?void 0:a.type)==="stack"&&!this.isScriptOnlyStack(r[0]);e.setStackActive(o)}isScriptOnlyStack(e){if(e.divider!=="^")return!1;const t=e.numerator.trim().length>0,i=e.denominator.trim().length>0;return t!==i}inferCurrentFormatFromDocument(){if(this.document.ast.nodes.length===0||this.getChars().length===0)return null;const n=this.selectionStart!==this.selectionEnd?Math.min(this.selectionStart,this.selectionEnd):this.cursorIndex>0?this.cursorIndex-1:0,r=this.getNodeByLogicalCharIndex(n);if(!r)return null;if(r.type==="stack"&&this.isScriptOnlyStack(r)){const o=r.numerator.trim().length>0?"superscript":"subscript";return{...this.toCharFormat(r.style),script:o}}return this.toCharFormat(r.style)}getNodeByLogicalCharIndex(e){const t=this.document.ast.nodes;if(t.length===0)return null;let i=0;const n=Math.max(0,e);for(const r of t){const o=this.getNodeLogicalSpan(r);if(n<i+o)return r;i+=o}return t[t.length-1]??null}getNodesByLogicalRange(e,t){const i=this.document.ast.nodes;if(i.length===0)return[];const n=Math.max(0,Math.min(e,t)),r=Math.max(n,Math.max(e,t));if(n===r)return[];const o=[];let a=0;for(const l of i){const c=this.getNodeLogicalSpan(l),h=a,p=a+c;c>0&&h<r&&p>n&&o.push(l),a=p}return o}toCharFormat(e){var v,x;const t=Math.max(1,this.defaultTextStyle.fixedTextHeight),i=e.capHeight.isRelative?t*Math.max(0,e.capHeight.value):e.capHeight.value,n=this.defaultTextStyle.font||this.baseFormat.fontFamily,r=e.rgb?this.rgbArrayToColorNumber(e.rgb):this.isExplicitAci(e.aci)?this.resolveAciColor(e.aci):this.resolveBaseColor(),o=this.isExplicitAci(e.aci)?e.aci:this.isExplicitAci(this.baseFormat.aci)?this.baseFormat.aci:null,a=this.toScriptFromStyle(e,t,i),l=Math.max(1,t)*.9,c=i<=l,h=a==="normal"?i:c?i/.7:i,p=(v=e.widthFactor)==null?void 0:v.value,m=typeof p=="number"&&Number.isFinite(p)?Math.max(.01,p):1,g=(x=e.charTrackingFactor)==null?void 0:x.value,f=typeof g=="number"&&Number.isFinite(g)?Math.max(.01,g):1,w=typeof e.oblique=="number"&&Number.isFinite(e.oblique)?e.oblique:0;return{fontFamily:e.fontFace.family||n,fontSize:Math.max(1,h||t),bold:e.fontFace.weight>=700,italic:e.fontFace.style==="Italic",underline:e.underline,overline:e.overline,strike:e.strikeThrough,script:a,aci:o,rgb:r,obliqueAngle:w,widthFactor:m,tracking:f,paragraphAlignment:e.paragraph.align}}toScriptFromStyle(e,t,i){const n=Math.max(1,t)*.9,r=i<=n;return e.script&&e.script!=="normal"?r?e.script:"normal":r&&e.align===D.MTextLineAlignment.TOP?"superscript":r&&e.align===D.MTextLineAlignment.BOTTOM?"subscript":"normal"}createDefaultParseContext(){const e=new D.MTextContext;if(e.fontFace.family=this.defaultTextStyle.font||this.baseFormat.fontFamily,e.fontFace.style=this.baseFormat.italic?"Italic":"Regular",e.fontFace.weight=this.baseFormat.bold?700:400,e.capHeight={value:this.defaultTextStyle.fixedTextHeight,isRelative:!1},e.align=D.MTextLineAlignment.BOTTOM,e.widthFactor={value:this.defaultTextStyle.widthFactor??1,isRelative:!1},this.isExplicitAci(this.baseFormat.aci))e.aci=this.baseFormat.aci,e.rgb=null;else{const t=this.resolveBaseColor();e.rgb=this.colorNumberToRgbArray(t),e.aci=256}return e}createNormalizedDocument(e){const t=me.fromMText(e,this.createDefaultParseContext()),i={nodes:[]};for(const n of t.ast.nodes)switch(n.type){case"char":i.nodes.push({type:"char",value:n.value,style:this.cloneDocumentStyle(n.style)});break;case"stack":i.nodes.push({type:"stack",numerator:n.numerator,denominator:n.denominator,divider:n.divider,style:this.cloneDocumentStyle(n.style)});break;case"paragraphBreak":i.nodes.push({type:"paragraphBreak",style:this.cloneDocumentStyle(n.style)});break;case"columnBreak":case"wrapAtDimLine":i.nodes.push({type:"paragraphBreak",style:this.cloneDocumentStyle(n.style)});break}return new me(i)}computeAttachmentAnchorOnBounds(e,t,i,n,r){const o=(e+t)*.5,a=(i+n)*.5,l=this.position.z;switch(r){case D.MTextAttachmentPoint.TopLeft:return new L.Vector3(e,n,l);case D.MTextAttachmentPoint.TopCenter:return new L.Vector3(o,n,l);case D.MTextAttachmentPoint.TopRight:return new L.Vector3(t,n,l);case D.MTextAttachmentPoint.MiddleLeft:return new L.Vector3(e,a,l);case D.MTextAttachmentPoint.MiddleCenter:return new L.Vector3(o,a,l);case D.MTextAttachmentPoint.MiddleRight:return new L.Vector3(t,a,l);case D.MTextAttachmentPoint.BottomLeft:case D.MTextAttachmentPoint.BaselineLeft:return new L.Vector3(e,i,l);case D.MTextAttachmentPoint.BottomCenter:case D.MTextAttachmentPoint.BaselineCenter:return new L.Vector3(o,i,l);case D.MTextAttachmentPoint.BottomRight:case D.MTextAttachmentPoint.BaselineRight:return new L.Vector3(t,i,l);default:return new L.Vector3(e,n,l)}}mapRibbonParagraphAlignment(e){switch(e){case"default":return D.MTextParagraphAlignment.DEFAULT;case"left":return D.MTextParagraphAlignment.LEFT;case"center":return D.MTextParagraphAlignment.CENTER;case"right":return D.MTextParagraphAlignment.RIGHT;case"justified":return D.MTextParagraphAlignment.JUSTIFIED;case"distributed":return D.MTextParagraphAlignment.DISTRIBUTED;default:return}}mapRibbonAttachmentCode(e){switch(e.trim().toUpperCase()){case"TL":return D.MTextAttachmentPoint.TopLeft;case"TC":return D.MTextAttachmentPoint.TopCenter;case"TR":return D.MTextAttachmentPoint.TopRight;case"ML":return D.MTextAttachmentPoint.MiddleLeft;case"MC":return D.MTextAttachmentPoint.MiddleCenter;case"MR":return D.MTextAttachmentPoint.MiddleRight;case"BL":return D.MTextAttachmentPoint.BottomLeft;case"BC":return D.MTextAttachmentPoint.BottomCenter;case"BR":return D.MTextAttachmentPoint.BottomRight;default:return}}attachmentPointToRibbonCode(e){switch(e){case D.MTextAttachmentPoint.TopLeft:return"TL";case D.MTextAttachmentPoint.TopCenter:return"TC";case D.MTextAttachmentPoint.TopRight:return"TR";case D.MTextAttachmentPoint.MiddleLeft:return"ML";case D.MTextAttachmentPoint.MiddleCenter:return"MC";case D.MTextAttachmentPoint.MiddleRight:return"MR";case D.MTextAttachmentPoint.BottomLeft:case D.MTextAttachmentPoint.BaselineLeft:return"BL";case D.MTextAttachmentPoint.BottomCenter:case D.MTextAttachmentPoint.BaselineCenter:return"BC";case D.MTextAttachmentPoint.BottomRight:case D.MTextAttachmentPoint.BaselineRight:return"BR";default:return"TL"}}mergeCharFormat(e,t){const i={...e,...t};if(t.aci!==void 0)if(!this.isExplicitAci(t.aci))i.aci=null;else{const n=this.resolveAciColor(t.aci);i.aci=t.aci,i.rgb=n}return t.rgb!==void 0&&(t.rgb===null?i.rgb=null:(i.rgb=this.normalizeColorNumber(t.rgb),t.aci===void 0&&(i.aci=null))),t.paragraphAlignment!==void 0&&(i.paragraphAlignment=t.paragraphAlignment),i}cloneDocumentStyle(e){return{underline:e.underline,overline:e.overline,strikeThrough:e.strikeThrough,script:e.script,aci:e.aci,rgb:e.rgb?[...e.rgb]:null,align:e.align,fontFace:{...e.fontFace},capHeight:{...e.capHeight},widthFactor:{...e.widthFactor},charTrackingFactor:{...e.charTrackingFactor},oblique:e.oblique,paragraph:{indent:e.paragraph.indent,left:e.paragraph.left,right:e.paragraph.right,align:e.paragraph.align,tabs:[...e.paragraph.tabs]}}}toDocumentStyle(e,t){const i=this.isExplicitAci(e.aci)?e.aci:null,n=i!==null?null:this.colorNumberToRgbArray(e.rgb!==null?e.rgb:this.resolveBaseColor()),r=e.script!=="normal",o=Math.max(1,e.fontSize*(r?.7:1)),a=e.script==="superscript"?D.MTextLineAlignment.TOP:e.script==="subscript"?D.MTextLineAlignment.BOTTOM:D.MTextLineAlignment.MIDDLE,l=e.paragraphAlignment;return{underline:e.underline,overline:e.overline,strikeThrough:e.strike,script:e.script,aci:i,rgb:n,align:a,fontFace:{family:e.fontFamily,style:e.italic?"Italic":"Regular",weight:e.bold?700:400},capHeight:{value:o,isRelative:!1},widthFactor:{value:Math.max(.01,e.widthFactor),isRelative:!1},charTrackingFactor:{value:Math.max(.01,e.tracking),isRelative:!1},oblique:e.obliqueAngle,paragraph:{indent:(t==null?void 0:t.paragraph.indent)??0,left:(t==null?void 0:t.paragraph.left)??0,right:(t==null?void 0:t.paragraph.right)??0,align:l,tabs:t!=null&&t.paragraph.tabs?[...t.paragraph.tabs]:[]}}}colorNumberToRgbArray(e){const t=this.normalizeColorNumber(e);return[t>>16&255,t>>8&255,t&255]}rgbArrayToColorNumber(e){const t=Math.max(0,Math.min(255,Math.round(e[0]))),i=Math.max(0,Math.min(255,Math.round(e[1]))),n=Math.max(0,Math.min(255,Math.round(e[2])));return t<<16|i<<8|n}};E(V,"activeEditor",null),E(V,"sharedToolbar",null),E(V,"sharedToolbarContainer",null),E(V,"sharedToolbarFontFamiliesKey",""),E(V,"sharedToolbarColorPickerFactory",null),E(V,"instances",new Set),E(V,"FALLBACK_LINE_ADVANCE_RATIO",1.5),E(V,"DEFAULT_TEXT_STYLE",{name:"MTextInputBoxStyle",standardFlag:0,fixedTextHeight:24,widthFactor:1,obliqueAngle:0,textGenerationFlag:0,lastHeight:24,font:pn,bigFont:""}),E(V,"DEFAULT_LINE_SPACE_FACTOR",.3);let cr=V;function qp(s){return d.acgiContrastingForegroundColor(s)}function Jp(s){if(typeof s=="number")return s===1;if(typeof s=="boolean")return s;const e=String(s).toLowerCase();return e==="light"||e==="1"||e==="true"}function Qa(s){return s.currentSpaceId===s.tables.blockTable.modelSpace.objectId}function dr(s){return s?d.AcDbSystemVariables.MODELBKCOLOR:d.AcDbSystemVariables.PAPERBKCOLOR}function el(s,e){const t=s==null?void 0:s.RGB;return t??(e?d.ACGI_MODEL_SPACE_BACKGROUND:d.ACGI_PAPER_SPACE_BACKGROUND)}function bn(s,e){const t=dr(e),i=d.AcDbSysVarManager.instance().getVar(t,s);return el(i,e)}function tl(s){const e=s.RGB??d.ACGI_MODEL_SPACE_BACKGROUND,t=new d.AcCmColor(d.AcCmColorMethod.ByColor);return d.acgiIsLightBackground(e)?t.setRGB(0,0,0):t.setRGB(255,255,255),t}function wn(s){return d.acgiIsLightBackground(s)?"black":"white"}function Qp(s){if(s===void 0)return;const e=s;return e>=1&&e<=12?e:D.MTextAttachmentPoint.TopLeft}function Zb(s){return s}const vn="__mlightcadMTextFormatBridge",q=class q{static setDefaultColorPicker(e){q.defaultColorPicker=e}static setDefaultToolbarEnabled(e){q.defaultToolbarEnabled=e}static getActiveInputBox(){return q.activeInputBox}static addActiveInputBoxChangeListener(e){q.activeInputBoxChangeListeners.add(e)}static removeActiveInputBoxChangeListener(e){q.activeInputBoxChangeListeners.delete(e)}static setActiveInputBox(e){q.activeInputBox!==e&&(q.activeInputBox=e,q.activeInputBoxChangeListeners.forEach(t=>{t(e)}))}static createHiddenToolbarContainer(e){const t=e.ownerDocument.createElement("div");return t.setAttribute("aria-hidden","true"),Object.assign(t.style,{display:"none",pointerEvents:"none"}),e.appendChild(t),t}static attachFormatBridge(e){const t=e;if(t[vn])return;const i=new Set,n=[],r=()=>{i.forEach(a=>{a()})},o=a=>{const l=t[a];typeof l=="function"&&(t[a]=(...c)=>{const h=l.apply(t,c);return r(),h},n.push(()=>{t[a]=l}))};["setCurrentFormat","refreshCurrentFormatFromDocument","toggleCase","toggleStackSelection","toggleScriptSelection","setParagraphAlignment","setAttachmentPoint","setLineSpacingFactor","clearLineSpacing"].forEach(o),t.addCurrentFormatChangeListener=a=>{i.add(a)},t.removeCurrentFormatChangeListener=a=>{i.delete(a)},t.focusEditor=()=>{const a=t,l=a.focusImeInput;if(typeof l=="function"){l.call(t);return}const c=a.refocusImeInputSoon;typeof c=="function"&&c.call(t)},t.isStackSelectionActive=()=>{var P,A;const a=t,l=a.getSelectionRange,c=a.toDocumentIndexFromLogicalIndex,h=a.isScriptOnlyStack,p=a.document;if(typeof l!="function"||typeof c!="function")return!1;const m=l.call(t);if(!m||m.isCollapsed)return!1;const g=c.call(t,m.start,!0),f=c.call(t,m.end,!1),w=((A=(P=p==null?void 0:p.ast)==null?void 0:P.nodes)==null?void 0:A.slice(g,f))??[],v=w[0];if(w.length!==1||(v==null?void 0:v.type)!=="stack")return!1;if(typeof h=="function")return!h.call(t,v);if(v.divider!=="^")return!0;const x=(v.numerator??"").trim().length>0,S=(v.denominator??"").trim().length>0;return x===S},t[vn]={addCurrentFormatChangeListener:t.addCurrentFormatChangeListener,removeCurrentFormatChangeListener:t.removeCurrentFormatChangeListener,dispose:()=>{n.forEach(a=>{a()}),i.clear(),delete t.addCurrentFormatChangeListener,delete t.removeCurrentFormatChangeListener,delete t.focusEditor,delete t.isStackSelectionActive,delete t[vn]}}}static detachFormatBridge(e){var i;(i=e[vn])==null||i.dispose()}open(e){const{view:t,location:i,width:n,textHeight:r,initialText:o="",toolbarFontFamilies:a=[],toolbarColorPicker:l,toolbarEnabled:c=q.defaultToolbarEnabled,initialAttachmentPoint:h}=e,p=new L.Vector3(i.x,i.y,i.z??0),g=d.acgiIsLightBackground(t.backgroundColor)?"#000000":"#ffffff",f=k.instance,w=f.curDocument.database,{layerColor:v}=f.resolveColors(),x=()=>{const N=d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.COLORTHEME,w);return N===0||N==="0"||N===!1||N==="dark"?"dark":"light"},S=Array.from(new Set(a.map(N=>N.trim()).filter(N=>N.length>0))),P=()=>{const N=w.tables.textStyleTable.getAt(w.textstyle);return N==null?void 0:N.textStyle},A=Math.max(1,r),_=P(),C=_?{..._,fixedTextHeight:A,lastHeight:A}:void 0,O=c?null:q.createHiddenToolbarContainer(t.container),B=Qp(h),I=new cr({scene:t.internalScene,camera:t.internalCamera,width:n,position:p.clone(),initialText:o,...B!==void 0?{initialAttachmentPoint:B}:{},textStyle:C,cursorStyle:{color:g,glowColor:g},boundingBoxStyle:{padding:0},imeTarget:t.canvas,colorSettings:{layer:w.clayer,color:new D.MTextColor,byLayerColor:v,byBlockColor:v},toolbar:{enabled:!0,theme:x(),fontFamilies:S,container:O??t.container,offsetY:10,colorPicker:l??q.defaultColorPicker??void 0}});return q.attachFormatBridge(I),q.setActiveInputBox(I),new Promise(N=>{let G=!1;const $=()=>{G||(I.update(),t.isHtmlDirty=!0)},X=re=>{re.name.toLowerCase()===d.AcDbSystemVariables.COLORTHEME.toLowerCase()&&(I.setToolbarTheme(x()),t.isHtmlDirty=!0)},Y=()=>{q.activeInputBox===I&&q.setActiveInputBox(null),q.detachFormatBridge(I),I.dispose(),O==null||O.remove(),t.events.renderFrame.removeEventListener($),I.off("close",se),d.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(X),t.isHtmlDirty=!0},Q=re=>{G||(G=!0,Y(),N(re))},se=()=>{var Ot;const re=I.getMTextInsertionPoint();Q({contents:I.getText(),location:{x:re.x,y:re.y,z:re.z},width:n,height:A,lineSpacingFactor:((Ot=I.getLineSpacingFactor)==null?void 0:Ot.call(I))??q.defaultLineSpacingFactor,attachmentPoint:I.getMTextAttachmentPoint()})};I.on("close",se),t.events.renderFrame.addEventListener($),d.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(X)})}};q.defaultLineSpacingFactor=.3,q.activeInputBox=null,q.activeInputBoxChangeListeners=new Set,q.defaultColorPicker=null,q.defaultToolbarEnabled=!0;let He=q;const Ds=class Ds{constructor(e){this.view=e}handleKeyDown(e){const t=this.resolveUndoRedoShortcut(e);if(this.shouldIgnoreEditableTargetShortcut(e)&&!t)return!1;if(t)return!this.shouldHandleUndoRedoShortcut(e)||He.getActiveInputBox()||this.view.editor.isActive?!1:(k.instance.sendStringToExecute(t),e.preventDefault(),!0);switch(e.code){case"Escape":return this.view.selectionSet.clear(),this.view.htmlTransientManager.deselectAll(),this.view.isHtmlDirty=!0,!1;case"Delete":case"Backspace":if(!this.view.editor.isActive){let n=!1;const r=this.view.htmlTransientManager;if(r.hasSelection()){const o=r.getSelectedGroups(),a=o.filter(c=>c.layer===W);a.length>0&&Ft(this.view,"Delete Measurement",()=>{for(const c of a)r.detach(c.id)&&(n=!0)}),(o.some(c=>c.layer!==W)||o.length===0&&r.hasSelection())&&ke(this.view,"Delete Markup",()=>{n=r.deleteSelected()||n})}if(n)return this.view.isHtmlDirty=!0,e.preventDefault(),!0;k.instance.sendStringToExecute("erase")}return!1}return!1}resolveUndoRedoShortcut(e){return!e.ctrlKey&&!e.metaKey?null:e.code==="KeyY"?"redo":e.code==="KeyZ"?e.shiftKey?"redo":"undo":null}shouldIgnoreEditableTargetShortcut(e){if(e.isComposing||e.keyCode===229)return!0;const t=e.target;return(t==null?void 0:t.tagName)==="TEXTAREA"||t!=null&&t.isContentEditable?!0:(t==null?void 0:t.tagName)==="INPUT"}shouldHandleUndoRedoShortcut(e){if(e.isComposing||e.keyCode===229)return!1;const t=e.target;if((t==null?void 0:t.tagName)==="TEXTAREA"||t!=null&&t.isContentEditable)return!1;if((t==null?void 0:t.tagName)==="INPUT"){const i=t;return i.classList.contains(Ds.COMMAND_LINE_INPUT_CLASS)?i.value.trim()===""&&!i.readOnly:!1}return!0}};Ds.COMMAND_LINE_INPUT_CLASS="ml-cli-text";let kn=Ds;function em(s){return s.directBatchPrimitive!=null}function il(s,e){if(s.directBatchPrimitive==null)return null;e.beginDirectCapture();let t;try{t=s.worldDraw(e);const i=e.takeDirectCapture();if(!i)return null;const n=tm(i,e);return n?n.wcsBbox.isEmpty()||e.batchDrawPolicy.resolveDrawMode({anchor:M.resolveAnchorFromBox(n.wcsBbox),position:n.position})==="unbatch"?(n.geometry.dispose(),null):{...n,objectId:s.objectId,ownerId:s.ownerId,layerName:s.layer,visible:s.visibility!==!1}:null}catch(i){throw e.cancelDirectCapture(),i}finally{t==null||t.dispose()}}function nl(s){return!(s instanceof d.AcDbRay||s instanceof d.AcDbXline)}function tm(s,e){const t=e.subEntityTraits;if(s.kind==="lineStrip"){const i=e.styleManager.getLineMaterial(t,!1);if(M.isDirectBatchRejectedMaterial(i))return null;const n=M.buildLineGeometry(s.points,i);return n?{kind:n.kind==="fat"?"lineFat":"lineBasic",geometry:n.geometry,worldOffset:n.worldOffset,wcsBbox:n.wcsBbox,material:n.material}:null}if(s.kind==="lineSegments"){const i=e.styleManager.getLineMaterial(t,!1);return M.buildLineSegmentsGeometry(s.array,s.itemSize,s.indices,i)}if(s.kind==="point"){const i=e.styleManager.getPointsMaterial(t);return M.isDirectBatchRejectedMaterial(i)?null:M.buildPointGeometry(s.point,i)}if(s.kind==="area"){const i=M.buildAreaGeometry(s.area,t,e.context);return i?M.isDirectBatchRejectedMaterial(i.material)?(i.geometry.dispose(),null):i:null}return null}class sl{constructor(e,t){this.getLayerTraits=e,this.renderer=t}remap(e,t,i){if(t===i)return;const n=this.getLayerTraits(i);for(const r of e)r.traverse(o=>{const a=o.userData.layerName===t;if(a&&(o.userData.layerName=i),!("material"in o)||!a)return;const l=o.material;if(Array.isArray(l)){const h=l;o.material=h.map(p=>this.shouldRemap(p,t)?this.renderer.getLayerBoundMaterial(this.promoteLayerZeroByLayerColor(p,t),i,n)??p:p),M.syncStyleMaterialIdFromMaterials(M.getSceneDrawableUserData(o),o.material);return}if(!this.shouldRemap(l,t))return;const c=this.renderer.getLayerBoundMaterial(this.promoteLayerZeroByLayerColor(l,t),i,n);c&&(o.material=c,M.syncStyleMaterialIdFromMaterials(M.getSceneDrawableUserData(o),c))})}shouldRemap(e,t){const i=M.getMaterialMetadata(e);return i.isForeground!==!0?!0:t!=="0"?!1:i.isByLayerColor===!0?!0:t==="0"&&(i.isByLayerLineType===!0||i.isByLayerLineWeight===!0||i.isByLayerTransparency===!0)}promoteLayerZeroByLayerColor(e,t){const i=M.getMaterialMetadata(e),n=M.hasByLayerBinding(i)&&i.isByLayerColor!==!0;return t==="0"&&n&&M.setMaterialMetadata(e,{isByLayerColor:!0}),e}}const ur=1,Rt=4;function hr(s){return{isOff:s.isOff,isFrozen:s.isFrozen,isLocked:((s.standardFlags??0)&Rt)!==0}}function rl(s,e){return s.isOff===e.isOff&&s.isFrozen===e.isFrozen&&s.isLocked===e.isLocked}const H="Layer",ol="Entity";function U(s,e,t){var n;if((n=s.transactionManager)!=null&&n.hasTransaction())return t();if(typeof s.runDatabaseEdit!="function")return process.env.NODE_ENV!=="production"&&console.warn(`[cad-simple-viewer] acapRunServiceEdit("${e}"): database.runDatabaseEdit is unavailable; mutation ran without undo support.`),t();let i;return pt(s,e,()=>{i=t()}),i}const j=class j{constructor(e){this.db=e}static openLayerForWrite(e,t){const i=typeof t=="string"?e.tables.layerTable.getAt(t):t;if(i)return j.registerLayerTableRecordForWrite(e,i),i}static registerLayerTableRecordForWrite(e,t){var o,a;const i=e.transactionManager;if(!((o=i==null?void 0:i.isRecording)!=null&&o.call(i)))return;const n=(a=i.currentTransaction)==null?void 0:a.call(i);if(!n)return;j.ensureLayerUndoHooks(e);const r=t.objectId;n.openedObjects.set(r,t),n.recorder.hasModify(r)||(n.originalStates.set(r,t.clonePreservingIdentity()),n.recorder.recordModify(t)),e.getObjectById(r)!==t&&j.ensureLayerFinalizeHook(n)}static resolveLayerForHandleCollision(e,t){var r;const i=(r=t.before)==null?void 0:r.name;if(typeof i!="string")return;const n=e.tables.layerTable.getAt(i);if(!(!n||e.getObjectById(t.objectId)===n))return n}static ensureLayerUndoHooks(e){const i=e.transactionManager.changeApplier;if(!i||j.patchedChangeAppliers.has(i))return;const n=i.applyModify.bind(i);i.applyModify=(r,o)=>{const a=j.resolveLayerForHandleCollision(e,r);if(a){const l=o?r.after:r.before;if(l){a.restoreFrom(l);return}}n(r,o)},j.patchedChangeAppliers.add(i)}static ensureLayerFinalizeHook(e){const t=e.recorder;if(t.__layerFinalizePatched||typeof t.finalize!="function")return;const i=t.finalize.bind(t);t.finalize=n=>{i(n);for(const r of t.getChanges()){if(r.kind!=="modify")continue;const o=e.openedObjects.get(r.objectId);if(!o||n.getObjectById(r.objectId)===o)continue;const a=j.resolveLayerForHandleCollision(n,r);a&&(r.after=a.clonePreservingIdentity())}},t.__layerFinalizePatched=!0}static syncLayerModifiedEvent(e,t,i){Object.keys(i).length!==0&&e.getObjectById(t.objectId)!==t&&e.events.layerModified.dispatch({database:e,layer:t,changes:i})}static setLayerFrozenState(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|ur:i&~ur}static setLayerLockedState(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|Rt:i&~Rt}static isLayerLocked(e){return((e.standardFlags??0)&Rt)!==0}static applyLayerPreviousSnapshot(e,t){t.states.forEach(n=>{const r=j.openLayerForWrite(e,n.name);r&&(r.isOff=!n.isOn,j.setLayerFrozenState(r,n.isFrozen),j.setLayerLockedState(r,n.isLocked))});const i=j.openLayerForWrite(e,t.clayer);return i?(i.isOff=!1,j.setLayerFrozenState(i,!1),e.clayer=i.name,!0):!1}parseLayerNameInput(e){const t=[...this.db.tables.layerTable.newIterator()].map(r=>r.name),i=e.trim();if(!i)return[];if(i==="*")return[...t];const n=i.split(",").map(r=>r.trim()).filter(Boolean);return[...new Set(n)]}resolveLayers(e){const t=this.db.tables.layerTable,i=[],n=[];return e.forEach(r=>{const o=t.getAt(r);o?i.push(o):n.push(r)}),{layers:i,missing:n}}getLayerSummaries(){return[...this.db.tables.layerTable.newIterator()].map(e=>({name:e.name,current:this.db.clayer===e.name?"*":"",on:e.isOff?"No":"Yes",frozen:e.isFrozen?"Yes":"No",locked:j.isLayerLocked(e)?"Yes":"No",color:e.color.toString()}))}createLayers(e){return U(this.db,H,()=>{const t=this.db.tables.layerTable;let i=0;const n=[];return e.forEach(r=>{if(t.has(r)){n.push(r);return}t.add(new d.AcDbLayerTableRecord({name:r,isOff:!1,isPlottable:!0,color:new d.AcCmColor(d.AcCmColorMethod.ByACI,7),linetype:"Continuous"})),i++}),{created:i,existed:n}})}setCurrentLayer(e){const t=this.db.tables.layerTable.getAt(e);return t?U(this.db,H,()=>{const i=j.openLayerForWrite(this.db,t);return i?(i.isOff=!1,j.setLayerFrozenState(i,!1),this.db.clayer=i.name,!0):!1}):!1}makeLayer(e){return U(this.db,H,()=>{const t=this.db.tables.layerTable;let i=t.getAt(e);i||(i=new d.AcDbLayerTableRecord({name:e,isOff:!1,isPlottable:!0,color:new d.AcCmColor(d.AcCmColorMethod.ByACI,7),linetype:"Continuous"}),t.add(i));const n=j.openLayerForWrite(this.db,i);return n?(n.isOff=!1,j.setLayerFrozenState(n,!1),this.db.clayer=n.name,!0):!1})}setLayerOn(e,t,i={}){if(!e||!this.db.tables.layerTable.getAt(e))return!1;const n=i.switchCurrentLayer??!1;return U(this.db,H,()=>{if(!t&&n&&!this.switchCurrentLayerIfNeeded(e))return!1;const r=j.openLayerForWrite(this.db,e);return r?(r.isOff=!t,j.syncLayerModifiedEvent(this.db,r,{isOff:r.isOff}),!0):!1})}setLayerFrozen(e,t,i={}){if(!e||!this.db.tables.layerTable.getAt(e))return!1;const n=i.switchCurrentLayer??!1;return U(this.db,H,()=>{if(t&&n&&!this.switchCurrentLayerIfNeeded(e))return!1;const r=j.openLayerForWrite(this.db,e);return r?(j.setLayerFrozenState(r,t),j.syncLayerModifiedEvent(this.db,r,{standardFlags:r.standardFlags}),!0):!1})}setLayerLocked(e,t){return!e||!this.db.tables.layerTable.getAt(e)?!1:U(this.db,H,()=>{const i=j.openLayerForWrite(this.db,e);return i?(j.setLayerLockedState(i,t),j.syncLayerModifiedEvent(this.db,i,{standardFlags:i.standardFlags}),!0):!1})}setLayerLineWeight(e,t){return this.db.tables.layerTable.getAt(e)?U(this.db,H,()=>{const i=j.openLayerForWrite(this.db,e);return i?(i.lineWeight=t,!0):!1}):!1}setLayerPlottable(e,t){return this.db.tables.layerTable.getAt(e)?U(this.db,H,()=>{const i=j.openLayerForWrite(this.db,e);return i?(i.isPlottable=t,!0):!1}):!1}setLayerLinetype(e,t){return!t||!this.db.tables.layerTable.getAt(e)?!1:U(this.db,H,()=>{const i=j.openLayerForWrite(this.db,e);return i?(i.linetype=t,!0):!1})}setLayerTransparency(e,t){return this.db.tables.layerTable.getAt(e)?U(this.db,H,()=>{const i=j.openLayerForWrite(this.db,e);return i?(i.transparency=t,!0):!1}):!1}isolateSingleLayer(e){return this.db.tables.layerTable.getAt(e)?U(this.db,H,()=>{for(const t of this.db.tables.layerTable.newIterator()){const i=j.openLayerForWrite(this.db,t);if(!i)continue;const n=i.name===e;i.isOff=!n,n&&j.setLayerFrozenState(i,!1)}return this.db.clayer=e,!0}):!1}setLayersVisibility(e,t,i={}){const n=i.skipCurrentLayer??!0,{layers:r}=this.resolveLayers(e),o=[];return U(this.db,H,()=>{r.forEach(a=>{if(t&&n&&a.name===this.db.clayer){o.push(a.name);return}const l=j.openLayerForWrite(this.db,a);l&&(l.isOff=t,j.syncLayerModifiedEvent(this.db,l,{isOff:l.isOff}))})}),{skippedCurrent:o}}setAllLayersOn(){return U(this.db,H,()=>{let e=0;for(const t of this.db.tables.layerTable.newIterator()){if(!t.isOff)continue;const i=j.openLayerForWrite(this.db,t);i&&(i.isOff=!1,e++)}return e})}setAllLayersOffExceptCurrent(){return U(this.db,H,()=>{const e=this.db.clayer;let t=0;for(const i of this.db.tables.layerTable.newIterator()){if(i.name===e||i.isOff)continue;const n=j.openLayerForWrite(this.db,i);n&&(n.isOff=!0,t++)}return t})}setLayersFrozen(e,t,i={}){const n=i.skipCurrentLayer??!0,{layers:r}=this.resolveLayers(e),o=[];return U(this.db,H,()=>{r.forEach(a=>{if(t&&n&&a.name===this.db.clayer){o.push(a.name);return}const l=j.openLayerForWrite(this.db,a);l&&(j.setLayerFrozenState(l,t),j.syncLayerModifiedEvent(this.db,l,{standardFlags:l.standardFlags}))})}),{skippedCurrent:o}}thawAllLayers(){return U(this.db,H,()=>{let e=0;for(const t of this.db.tables.layerTable.newIterator()){if(!t.isFrozen)continue;const i=j.openLayerForWrite(this.db,t);i&&(j.setLayerFrozenState(i,!1),j.syncLayerModifiedEvent(this.db,i,{standardFlags:i.standardFlags}),e++)}return e})}setLayersLocked(e,t){const{layers:i}=this.resolveLayers(e);U(this.db,H,()=>{i.forEach(n=>{const r=j.openLayerForWrite(this.db,n);r&&(j.setLayerLockedState(r,t),j.syncLayerModifiedEvent(this.db,r,{standardFlags:r.standardFlags}))})})}parseColorInput(e){const t=e.trim();if(!t)return;if(/^\d+$/.test(t)){const n=Number(t);return n>=1&&n<=255?new d.AcCmColor(d.AcCmColorMethod.ByACI,n):void 0}const i=d.AcCmColor.fromString(t);if(i){if(i.isByACI){const n=i.colorIndex;if(n==null||n<1||n>255)return}if(!(i.isByLayer||i.isByBlock))return i}}setLayerColor(e,t){return this.db.tables.layerTable.getAt(e)?U(this.db,H,()=>{const i=j.openLayerForWrite(this.db,e);return i?(i.color=t.clone(),!0):!1}):!1}setLayersColor(e,t){const{layers:i}=this.resolveLayers(e);U(this.db,H,()=>{i.forEach(n=>{const r=j.openLayerForWrite(this.db,n);r&&(r.color=t.clone())})})}setLayerDescription(e,t){const i=this.db.tables.layerTable.getAt(e);return i?U(this.db,H,()=>{const n=j.openLayerForWrite(this.db,i);return n?(n.description=t,!0):!1}):!1}switchCurrentLayerIfNeeded(e){if(this.db.clayer!==e)return!0;let t,i;for(const o of this.db.tables.layerTable.newIterator())if(o.name!==e&&(t??(t=o.name),!o.isOff&&!o.isFrozen)){i=o.name;break}const n=i??t;if(!n)return!1;const r=j.openLayerForWrite(this.db,n);return r?(r.isOff=!1,j.setLayerFrozenState(r,!1),this.db.clayer=r.name,!0):!1}getLayerNameFromEntity(e){var i;const t=this.db.tables.blockTable.getEntityById(e);return((i=t==null?void 0:t.layer)==null?void 0:i.trim())||void 0}collectLayerNamesFromEntities(e){const t=new Set,i=new Set;return e.forEach(n=>{const r=this.getLayerNameFromEntity(n);if(!r)return;const o=this.db.tables.layerTable.getAt(r);o?t.add(o.name):i.add(r)}),{layerNames:[...t],missingLayerNames:[...i]}}freezeLayerByEntity(e){const t=this.getLayerNameFromEntity(e);if(!t)return{ok:!1,reason:"invalid_selection"};const i=this.db.tables.layerTable.getAt(t);if(!i)return{ok:!1,reason:"layer_not_found",layerName:t};if(i.name===this.db.clayer)return{ok:!1,reason:"cannot_change_current",layerName:t};if(i.isFrozen)return{ok:!1,reason:"already_frozen",layerName:t};const n=i.isFrozen;return U(this.db,H,()=>{const r=j.openLayerForWrite(this.db,i);r&&j.setLayerFrozenState(r,!0)}),{ok:!0,layerName:t,previousFrozen:n}}setLayerFrozenByName(e,t){const i=this.db.tables.layerTable.getAt(e);return i?U(this.db,H,()=>{const n=j.openLayerForWrite(this.db,i);return n?(j.setLayerFrozenState(n,t),!0):!1}):!1}turnOffLayerByEntity(e){const t=this.getLayerNameFromEntity(e);if(!t)return{ok:!1,reason:"invalid_selection"};const i=this.db.tables.layerTable.getAt(t);if(!i)return{ok:!1,reason:"layer_not_found",layerName:t};if(i.name===this.db.clayer)return{ok:!1,reason:"cannot_change_current",layerName:t};if(i.isOff)return{ok:!1,reason:"already_off",layerName:t};const n=i.isOff;return U(this.db,H,()=>{const r=j.openLayerForWrite(this.db,i);r&&(r.isOff=!0)}),{ok:!0,layerName:t,previousOff:n}}setLayerOffByName(e,t){const i=this.db.tables.layerTable.getAt(e);return i?U(this.db,H,()=>{const n=j.openLayerForWrite(this.db,i);return n?(n.isOff=t,!0):!1}):!1}lockLayerByEntity(e){const t=this.getLayerNameFromEntity(e);if(!t)return{ok:!1,reason:"invalid_selection"};const i=this.db.tables.layerTable.getAt(t);return i?j.isLayerLocked(i)?{ok:!1,reason:"already_locked",layerName:t}:(U(this.db,H,()=>{const n=j.openLayerForWrite(this.db,i);n&&j.setLayerLockedState(n,!0)}),{ok:!0,layerName:t}):{ok:!1,reason:"layer_not_found",layerName:t}}unlockLayerByEntity(e){const t=this.getLayerNameFromEntity(e);if(!t)return{ok:!1,reason:"invalid_selection"};const i=this.db.tables.layerTable.getAt(t);return i?j.isLayerLocked(i)?(U(this.db,H,()=>{const n=j.openLayerForWrite(this.db,i);n&&j.setLayerLockedState(n,!1)}),{ok:!0,layerName:t}):{ok:!1,reason:"already_unlocked",layerName:t}:{ok:!1,reason:"layer_not_found",layerName:t}}isolateLayers(e,t){if(e.length!==0)return U(this.db,H,()=>{const i=this.db.tables.layerTable,n=new Set(e),r=i.getAt(e[0]),o=this.db.clayer,a=new Map;for(const p of i.newIterator())a.set(p.name,hr(p));r&&(this.db.clayer=r.name);const l=new Set;for(const p of i.newIterator()){const m=j.openLayerForWrite(this.db,p);if(m){if(n.has(m.name)){m.isOff&&(m.isOff=!1,l.add(m.name)),m.isFrozen&&(j.setLayerFrozenState(m,!1),l.add(m.name)),j.isLayerLocked(m)&&(j.setLayerLockedState(m,!1),l.add(m.name));continue}if(t==="Off"){m.isOff||(m.isOff=!0,l.add(m.name));continue}j.isLayerLocked(m)||(j.setLayerLockedState(m,!0),l.add(m.name))}}const c=[];for(const p of i.newIterator()){const m=a.get(p.name);if(!m)continue;const g=hr(p);rl(m,g)||c.push({name:p.name,before:m,isolated:g})}const h={currentLayerBefore:o,currentLayerAfter:this.db.clayer,layers:c};return{layerNames:e,affectedLayerCount:l.size,isoSnapshot:h}})}unisolateFromSnapshot(e){return U(this.db,H,()=>{const t=this.db.tables.layerTable;let i=0;for(const n of e.layers)t.getAt(n.name)&&this.restoreLayerIfUnchanged(n)&&i++;return this.db.clayer===e.currentLayerAfter&&e.currentLayerBefore!==e.currentLayerAfter&&t.getAt(e.currentLayerBefore)&&(this.db.clayer=e.currentLayerBefore),i})}collectLayerEntities(e){const t=[];for(const i of this.db.tables.blockTable.newIterator())for(const n of i.newIterator())n.layer===e&&t.push({ownerId:i.objectId,objectId:n.objectId,entity:n.clone()});return t}removeLayerEntities(e){const t=new Map;e.forEach(({ownerId:i,objectId:n})=>{const r=t.get(i)??[];r.push(n),t.set(i,r)}),t.forEach((i,n)=>{var r;(r=this.db.tables.blockTable.getIdAt(n))==null||r.removeEntity(i)})}deleteLayer(e){const t=this.db.tables.layerTable.getAt(e);return t?t.name==="0"?{ok:!1,reason:"layer_0",layerName:e}:t.name===this.db.clayer?{ok:!1,reason:"current_layer",layerName:e}:U(this.db,H,()=>{const i=this.collectLayerEntities(t.name);this.removeLayerEntities(i);const n=t.clone();return this.db.tables.layerTable.remove(t.name),this.db.events.layerErased.dispatch({database:this.db,layer:t}),{ok:!0,layerName:t.name,layer:n,entities:i}}):{ok:!1,reason:"not_found",layerName:e}}restoreDeletedLayer(e,t){U(this.db,H,()=>{this.db.tables.layerTable.has(e.name)||this.db.tables.layerTable.add(e.clone());const i=new Map;t.forEach(({ownerId:n,entity:r})=>{const o=i.get(n)??[];o.push(r.clone()),i.set(n,o)}),i.forEach((n,r)=>{(this.db.tables.blockTable.getIdAt(r)??this.db.tables.blockTable.modelSpace).appendEntity(n)})})}restoreLayerIfUnchanged(e){const t=this.db.tables.layerTable.getAt(e.name);if(!t)return!1;const i=j.openLayerForWrite(this.db,t);if(!i)return!1;let n=!1;return i.isOff===e.isolated.isOff&&i.isOff!==e.before.isOff&&(i.isOff=e.before.isOff,n=!0),i.isFrozen===e.isolated.isFrozen&&i.isFrozen!==e.before.isFrozen&&(j.setLayerFrozenState(i,e.before.isFrozen),n=!0),j.isLayerLocked(i)===e.isolated.isLocked&&j.isLayerLocked(i)!==e.before.isLocked&&(j.setLayerLockedState(i,e.before.isLocked),n=!0),n}getEffectiveLayerTraits(e){return j.resolveLayerTraits(this.db,e)}static resolveLayerTraits(e,t){const i=e.tables.layerTable.getAt(t);if(i)return{layer:i.name,color:i.color.clone(),lineType:i.lineStyle,lineWeight:i.lineWeight,transparency:i.transparency}}};j.patchedChangeAppliers=new WeakSet;let te=j;class al{constructor(e,t,i){this.scene=e,this.renderer=t,this.getLayerTraits=i}layerStyleMayHaveChanged(e){return e.color!=null||e.linetype!=null||e.lineWeight!==void 0||e.transparency!=null}syncFromLiveRecord(e){const t=this.getEffectiveLayerTraits(e.name);if(!t)return;const i=this.renderer.updateLayerMaterial(e.name,t);this.scene.forEachSceneLayer(e.name,n=>n.syncAppearanceFromRecord(e.name,t,i,this.renderer))}refreshTextMaterialsInObjectTree(e,t){e.traverse(i=>{const n=i.refreshTextMaterials;typeof n=="function"&&n.call(i,t)})}getEffectiveLayerTraits(e){if(this.getLayerTraits)return this.getLayerTraits(e);const t=this.renderer.context.database;if(t)return te.resolveLayerTraits(t,e)}}const Vt=1e-5;function yi(s){return Number.isFinite(s.minX)&&Number.isFinite(s.minY)&&Number.isFinite(s.maxX)&&Number.isFinite(s.maxY)}function pr(s){const e=new L.Box3;for(const t of s.wcsChildBoxes)yi(t)&&e.union(new L.Box3(new L.Vector3(t.minX,t.minY,0),new L.Vector3(t.maxX,t.maxY,0)));return e}function im(s){if(s.wcsChildBoxes.length===0)return;const e=pr(s),t=s.wcsBbox;if(!(Math.abs(t.min.x-e.min.x)<=Vt&&Math.abs(t.min.y-e.min.y)<=Vt&&Math.abs(t.min.z-e.min.z)<=Vt&&Math.abs(t.max.x-e.max.x)<=Vt&&Math.abs(t.max.y-e.max.y)<=Vt&&Math.abs(t.max.z-e.max.z)<=Vt))throw new Error(`[AcTrView2d] Group wcsBbox [${t.min.x}, ${t.min.y}]–[${t.max.x}, ${t.max.y}] does not match wcsChildBoxes union [${e.min.x}, ${e.min.y}]–[${e.max.x}, ${e.max.y}]. Ensure AcDbRenderingCache.draw applied the INSERT transform before handleGroup.`)}function nm(s){im(s)}function xn(s,e){var o;let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const a of s)yi(a)&&(t=Math.min(t,a.minX),i=Math.min(i,a.minY),n=Math.max(n,a.maxX),r=Math.max(r,a.maxY));return{minX:t,minY:i,maxX:n,maxY:r,id:e??((o=s[0])==null?void 0:o.id)??""}}function Sn(s){return!(s.children!==void 0&&s.children.length===0)}function ll(s){const e=new Map;return s.map(t=>{const i=t.id;if(typeof i!="string"||i.length===0)return t;const n=e.get(i)??0;return e.set(i,n+1),n===0?t:{...t,id:`${i}#${n}`}})}const sm=40;class rm{constructor(){this.items=new Map,this.anonKeySeq=0}storageKey(e){return typeof e.id=="string"&&e.id.length>0?e.id:`__anon_${this.anonKeySeq++}`}insert(e){if(typeof e.id=="string"&&e.id.length>0){this.items.set(e.id,e);return}this.items.set(this.storageKey(e),e)}load(e){for(const t of e)this.insert(t)}remove(e){if(typeof e.id=="string"&&e.id.length>0){this.items.delete(e.id);return}for(const[t,i]of this.items)if(i===e||i.id===e.id&&i.minX===e.minX&&i.minY===e.minY&&i.maxX===e.maxX&&i.maxY===e.maxY){this.items.delete(t);return}}removeById(e){typeof e=="string"&&e.length>0&&this.items.delete(e)}clear(){this.items.clear()}search(e,t){const i=[];for(const n of this.items.values())cl(n,e)&&((t==null?void 0:t.selectionMode)==="window"&&!Nt(n,e)||i.push(n));return i}collides(e){for(const t of this.items.values())if(cl(t,e))return!0;return!1}all(){return Array.from(this.items.values())}getStats(){const e=this.all(),t=e.length;return{kind:"linear",itemCount:t,estimatedBytes:Ma(e)+t*sm}}}function cl(s,e){return!(s.maxX<e.minX||s.minX>e.maxX||s.maxY<e.minY||s.minY>e.maxY)}function dl(s,e,t=0,i=s.length-1,n=om){for(;i>t;){if(i-t>600){const l=i-t+1,c=e-t+1,h=Math.log(l),p=.5*Math.exp(2*h/3),m=.5*Math.sqrt(h*p*(l-p)/l)*(c-l/2<0?-1:1),g=Math.max(t,Math.floor(e-c*p/l+m)),f=Math.min(i,Math.floor(e+(l-c)*p/l+m));dl(s,e,g,f,n)}const r=s[e];let o=t,a=i;for(gi(s,t,e),n(s[i],r)>0&&gi(s,t,i);o<a;){for(gi(s,o,a),o++,a--;n(s[o],r)<0;)o++;for(;n(s[a],r)>0;)a--}n(s[t],r)===0?gi(s,t,a):(a++,gi(s,a,i)),a<=e&&(t=a+1),e<=a&&(i=a-1)}}function gi(s,e,t){const i=s[e];s[e]=s[t],s[t]=i}function om(s,e){return s<e?-1:s>e?1:0}class am{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const i=[];if(!An(e,t))return i;const n=this.toBBox,r=[];for(;t;){for(let o=0;o<t.children.length;o++){const a=t.children[o],l=t.leaf?n(a):a;An(e,l)&&(t.leaf?i.push(a):yr(e,l)?this._all(a,i):r.push(a))}t=r.pop()}return i}collides(e){let t=this.data;if(!An(e,t))return!1;const i=[];for(;t;){for(let n=0;n<t.children.length;n++){const r=t.children[n],o=t.leaf?this.toBBox(r):r;if(An(e,o)){if(t.leaf||yr(e,o))return!0;i.push(r)}}t=i.pop()}return!1}load(e){if(!(e&&e.length))return this;if(e.length<this._minEntries){for(let i=0;i<e.length;i++)this.insert(e[i]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(!this.data.children.length)this.data=t;else if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const i=this.data;this.data=t,t=i}this._insert(t,this.data.height-t.height-1,!0)}return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Kt([]),this}remove(e,t){if(!e)return this;let i=this.data;const n=this.toBBox(e),r=[],o=[];let a,l,c;for(;i||r.length;){if(i||(i=r.pop(),l=r[r.length-1],a=o.pop(),c=!0),i.leaf){const h=lm(e,i.children,t);if(h!==-1)return i.children.splice(h,1),r.push(i),this._condense(r),this}!c&&!i.leaf&&yr(i,n)?(r.push(i),o.push(a),a=0,l=i,i=i.children[0]):l?(a++,i=l.children[a],c=!1):i=null}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const i=[];for(;e;)e.leaf?t.push(...e.children):i.push(...e.children),e=i.pop();return t}_build(e,t,i,n){const r=i-t+1;let o=this._maxEntries,a;if(r<=o)return a=Kt(e.slice(t,i+1)),Gt(a,this.toBBox),a;n||(n=Math.ceil(Math.log(r)/Math.log(o)),o=Math.ceil(r/Math.pow(o,n-1))),a=Kt([]),a.leaf=!1,a.height=n;const l=Math.ceil(r/o),c=l*Math.ceil(Math.sqrt(o));ul(e,t,i,c,this.compareMinX);for(let h=t;h<=i;h+=c){const p=Math.min(h+c-1,i);ul(e,h,p,l,this.compareMinY);for(let m=h;m<=p;m+=l){const g=Math.min(m+l-1,p);a.children.push(this._build(e,m,g,n-1))}}return Gt(a,this.toBBox),a}_chooseSubtree(e,t,i,n){for(;n.push(t),!(t.leaf||n.length-1===i);){let r=1/0,o=1/0,a;for(let l=0;l<t.children.length;l++){const c=t.children[l],h=mr(c),p=um(e,c)-h;p<o?(o=p,r=h<r?h:r,a=c):p===o&&h<r&&(r=h,a=c)}t=a||t.children[0]}return t}_insert(e,t,i){const n=i?e:this.toBBox(e),r=[],o=this._chooseSubtree(n,this.data,t,r);for(o.children.push(e),bi(o,n);t>=0&&r[t].children.length>this._maxEntries;)this._split(r,t),t--;this._adjustParentBBoxes(n,r,t)}_split(e,t){const i=e[t],n=i.children.length,r=this._minEntries;this._chooseSplitAxis(i,r,n);const o=this._chooseSplitIndex(i,r,n),a=Kt(i.children.splice(o,i.children.length-o));a.height=i.height,a.leaf=i.leaf,Gt(i,this.toBBox),Gt(a,this.toBBox),t?e[t-1].children.push(a):this._splitRoot(i,a)}_splitRoot(e,t){this.data=Kt([e,t]),this.data.height=e.height+1,this.data.leaf=!1,Gt(this.data,this.toBBox)}_chooseSplitIndex(e,t,i){let n,r=1/0,o=1/0;for(let a=t;a<=i-t;a++){const l=fi(e,0,a,this.toBBox),c=fi(e,a,i,this.toBBox),h=hm(l,c),p=mr(l)+mr(c);h<r?(r=h,n=a,o=p<o?p:o):h===r&&p<o&&(o=p,n=a)}return n||i-t}_chooseSplitAxis(e,t,i){const n=e.leaf?this.compareMinX:cm,r=e.leaf?this.compareMinY:dm,o=this._allDistMargin(e,t,i,n),a=this._allDistMargin(e,t,i,r);o<a&&e.children.sort(n)}_allDistMargin(e,t,i,n){e.children.sort(n);const r=this.toBBox,o=fi(e,0,t,r),a=fi(e,i-t,i,r);let l=Pn(o)+Pn(a);for(let c=t;c<i-t;c++){const h=e.children[c];bi(o,e.leaf?r(h):h),l+=Pn(o)}for(let c=i-t-1;c>=t;c--){const h=e.children[c];bi(a,e.leaf?r(h):h),l+=Pn(a)}return l}_adjustParentBBoxes(e,t,i){for(let n=i;n>=0;n--)bi(t[n],e)}_condense(e){for(let t=e.length-1,i;t>=0;t--)e[t].children.length===0?t>0?(i=e[t-1].children,i.splice(i.indexOf(e[t]),1)):this.clear():Gt(e[t],this.toBBox)}}function lm(s,e,t){if(!t)return e.indexOf(s);for(let i=0;i<e.length;i++)if(t(s,e[i]))return i;return-1}function Gt(s,e){fi(s,0,s.children.length,e,s)}function fi(s,e,t,i,n){n||(n=Kt(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(let r=e;r<t;r++){const o=s.children[r];bi(n,s.leaf?i(o):o)}return n}function bi(s,e){return s.minX=Math.min(s.minX,e.minX),s.minY=Math.min(s.minY,e.minY),s.maxX=Math.max(s.maxX,e.maxX),s.maxY=Math.max(s.maxY,e.maxY),s}function cm(s,e){return s.minX-e.minX}function dm(s,e){return s.minY-e.minY}function mr(s){return(s.maxX-s.minX)*(s.maxY-s.minY)}function Pn(s){return s.maxX-s.minX+(s.maxY-s.minY)}function um(s,e){return(Math.max(e.maxX,s.maxX)-Math.min(e.minX,s.minX))*(Math.max(e.maxY,s.maxY)-Math.min(e.minY,s.minY))}function hm(s,e){const t=Math.max(s.minX,e.minX),i=Math.max(s.minY,e.minY),n=Math.min(s.maxX,e.maxX),r=Math.min(s.maxY,e.maxY);return Math.max(0,n-t)*Math.max(0,r-i)}function yr(s,e){return s.minX<=e.minX&&s.minY<=e.minY&&e.maxX<=s.maxX&&e.maxY<=s.maxY}function An(s,e){return e.minX<=s.maxX&&e.minY<=s.maxY&&e.maxX>=s.minX&&e.maxY>=s.minY}function Kt(s){return{children:s,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function ul(s,e,t,i,n){const r=[e,t];for(;r.length;){if(t=r.pop(),e=r.pop(),t-e<=i)continue;const o=e+Math.ceil((t-e)/i/2)*i;dl(s,o,e,t,n),r.push(e,o,o,t)}}const pm=40,mm=1.4;class hl{constructor(e){this.tree=new am(e),this.idMap=new Map}insert(e){const t=typeof e.id=="string"&&e.id.length>0;if(t){const i=this.idMap.get(e.id);if(i){if(i.minX===e.minX&&i.minY===e.minY&&i.maxX===e.maxX&&i.maxY===e.maxY)return;this.remove(i,(n,r)=>n.id===r.id),this.idMap.delete(e.id)}}this.tree.insert(e),t&&this.idMap.set(e.id,e)}load(e){this.tree.load(e);for(const t of e)typeof t.id=="string"&&t.id.length>0&&this.idMap.set(t.id,t)}remove(e,t){this.tree.remove(e,t??((i,n)=>i===n||i.id===n.id&&i.minX===n.minX&&i.minY===n.minY&&i.maxX===n.maxX&&i.maxY===n.maxY)),typeof e.id=="string"&&e.id.length>0&&this.idMap.delete(e.id)}removeById(e){typeof e=="string"&&e.length>0&&(this.tree.remove({minX:0,minY:0,maxX:0,maxY:0,id:e},(t,i)=>t.id===i.id),this.idMap.delete(e))}clear(){this.tree.clear(),this.idMap.clear()}search(e,t){const i=this.tree.search(e);return(t==null?void 0:t.selectionMode)!=="window"?i:i.filter(n=>Nt(n,e))}collides(e){return this.tree.collides(e)}all(){return this.tree.all()}getStats(){const e=this.tree.all(),t=e.length,i=Ma(e),n=this.idMap.size*pm;return{kind:"rbush",itemCount:t,estimatedBytes:Math.round(i*mm+n)}}}const Os=class Os{constructor(e){this.childIndexes=new Map,this.rootIndex=e??new hl}setChildIndex(e,t){this.childIndexes.set(e,t)}removeChildIndex(e){this.childIndexes.delete(e)}insert(e){this.rootIndex.insert(e)}load(e){this.rootIndex.load(e)}remove(e,t){this.rootIndex.remove(e,t),this.childIndexes.delete(e.id)}removeById(e){this.rootIndex.removeById(e),this.childIndexes.delete(e)}clear(){this.rootIndex.clear(),this.childIndexes.forEach(e=>e.clear()),this.childIndexes.clear()}search(e,t){const i=this.rootIndex.search(e),n=[];for(const r of i){const o=this.childIndexes.get(r.id);if(!o){((t==null?void 0:t.selectionMode)!=="window"||Nt(r,e))&&n.push(r);continue}const a=o.search(e),l={...r,children:a};((t==null?void 0:t.selectionMode)!=="window"||this.isWindowSelectionHit(l,e))&&n.push(l)}return n}isWindowSelectionHit(e,t){const i=this.childIndexes.get(e.id);if(!i)return Nt(e,t);const n=i.all().filter(yi);return n.length===0?!1:n.every(r=>Nt(r,t))}collides(e){return this.rootIndex.collides(e)?this.rootIndex.search(e).some(i=>{const n=this.childIndexes.get(i.id);return n?n.collides(e):!0}):!1}all(){const e=[];for(const t of this.rootIndex.all()){const i=this.childIndexes.get(t.id);i?e.push(...i.all()):e.push(t)}return e}hasChildIndex(e){return this.childIndexes.has(e)}getStats(){const e=this.rootIndex.getStats();let t=0,i=0,n=0,r=0;for(const a of this.childIndexes.values()){const l=a.getStats();t+=l.itemCount,i+=l.estimatedBytes,l.kind==="rbush"?n++:l.kind==="linear"&&r++}const o=this.childIndexes.size*64;return{kind:"hierarchical",itemCount:e.itemCount,estimatedBytes:e.estimatedBytes+i+o,rootItemCount:e.itemCount,childIndexCount:this.childIndexes.size,childItemCount:t,rbushChildCount:n,linearChildCount:r}}ensureChildIndex(e,t){const i=ll(t.filter(yi));if(i.length===0)return;const n=xn(i,e);yi(n)&&this.insert(n);const r=this.childIndexes.get(e);if(r)return r.clear(),i.forEach(a=>r.insert({...a})),r;const o=this.createIndexBySize(i.length);if(o)return i.forEach(a=>o.insert({...a})),this.setChildIndex(e,o),o}createChildIndex(e){return this.ensureChildIndex(e.objectId,e.wcsChildBoxes)}createIndexBySize(e){if(e>Os.THRESHOLD)return new hl;if(e>0)return new rm}};Os.THRESHOLD=100;let gr=Os;class Ut{static isLayerVisible(e){return!(e.isFrozen||e.isOff)}constructor(e){this._group=new M.AcTrBatchedGroup,this._name=e.name,this._cachedBox=new L.Box3,this._boxDirty=!0,this._group.visible=Ut.isLayerVisible(e)}get name(){return this._name}set name(e){this._name=e}get box(){return this._boxDirty&&(this.computeBatchBoundingBox(this._cachedBox),this._boxDirty=!1),this._cachedBox}computeBatchBoundingBox(e=new L.Box3,t,i){return this.visible?this._group.computeBoundingBox(e,{excludeObjectIds:t,includeObjectIds:i}):(e.makeEmpty(),e)}get visible(){return this._group.visible}set visible(e){this._group.visible=e}get internalObject(){return this._group}get stats(){const e=this._group.stats;return{name:this._name,...e}}get entityCount(){return this._group.entityCount}update(e){const t=this.visible;this._name=e.name,this._group.visible=Ut.isLayerVisible(e),t!==this.visible&&(this._boxDirty=!0)}updateMaterial(e,t){this._group.updateMaterial(e,t)}syncAppearanceFromRecord(e,t,i,n){const r=Object.entries(i).some(([o,a])=>a.id!==Number(o));if(r)for(const o in i){const a=Number(o),l=i[o];l.id!==a&&this.updateMaterial(a,l)}this._group.syncAppearanceFromRecord(e,t,i,r,(o,a,l)=>n.getLayerBoundMaterial(o,a,l),n.styleManager)}rebindMaterialsForLayer(e,t,i,n){this._group.rebindMaterialsForLayer(e,t,i,n)}rematerializeLayerTextDrawables(e,t,i){this._group.rematerializeLayerTextDrawables(e,t,i)}rerenderPoints(e){this._group.rerenderPoints(e)}hasEntity(e){return this._group.hasEntity(e)}setEntityVisible(e,t){return this._group.setEntityVisible(e,t)}getEntityVisible(e){return this._group.getEntityVisible(e)}createPreviewSubset(e,t){return this._group.createPreviewSubset(e,t)}addEntity(e,t=!0){this._group.addEntity(e),this._boxDirty=!0}addDirectEntity(e){const t={objectId:e.objectId,visible:e.visible,position:e.position};let i=!1;return e.kind==="lineFat"?i=this._group.appendLine2Geometry(e.geometry,e.material,e.worldOffset,t):e.kind==="lineBasic"?i=this._group.appendLineGeometry(e.geometry,e.material,e.worldOffset,t):e.kind==="point"?i=this._group.appendPointGeometry(e.geometry,e.material,e.worldOffset,t):e.kind==="mesh"&&(i=this._group.appendMeshGeometry(e.geometry,e.material,e.worldOffset,t)),i&&(this._boxDirty=!0),i}isIntersectWith(e,t){return this._group.isIntersectWith(e,t)}removeEntity(e){const t=this._group.removeEntity(e);return t&&(this._boxDirty=!0),t}updateEntity(e){return e.objectId?this._group.removeEntity(e.objectId)?(this._group.addEntity(e),this._boxDirty=!0,!0):e.visible?(this._group.addEntity(e),this._boxDirty=!0,!0):!1:!1}clear(){this._group.clear(),this._cachedBox.makeEmpty(),this._boxDirty=!0,this._group.removeFromParent()}hover(e){if(e.length!==0){if(e.length===1){this._group.hover(e[0]);return}this._group.hoverMany(e)}}unhover(e){if(e.length!==0){if(e.length===1){this._group.unhover(e[0]);return}this._group.unhoverMany(e)}}select(e){if(e.length!==0){if(e.length===1){this._group.select(e[0]);return}this._group.selectMany(e)}}unselect(e){if(e.length!==0){if(e.length===1){this._group.unselect(e[0]);return}this._group.unselectMany(e)}}}class pl{constructor(){this.isReference=!1,this._group=new L.Group,this._spatialIndex=new gr,this._cachedBox=new L.Box3,this._boxDirty=!0,this._extentExcludedObjectIds=new Set,this._layers=new Map,this._insertLayerByObjectId=new Map,this._isLoaded=!1}get internalObject(){return this._group}get layers(){return this._layers}get box(){return this._boxDirty&&this.recomputeBox(),this._cachedBox}computeBatchBoundingBox(e=new L.Box3){return this._boxDirty&&this.recomputeBox(),e.copy(this._cachedBox)}recomputeBox(){this._cachedBox.makeEmpty();const e=new L.Box3;this._layers.forEach(t=>{t.computeBatchBoundingBox(e,this._extentExcludedObjectIds),e.isEmpty()||this._cachedBox.union(e)}),this._boxDirty=!1}invalidateBox(){this._boxDirty=!0}get isLoaded(){return this._isLoaded}set isLoaded(e){this._isLoaded=e}get visible(){return this._group.visible}set visible(e){this._group.visible=e}get entityCount(){let e=0;return this._layers.forEach(t=>e+=t.entityCount),e}get spatialIndexStats(){return this._spatialIndex.getStats()}get stats(){const e=[];let t=0,i=0,n=0,r=0,o=0,a=0,l=0;const c={line:0,mesh:0,point:0,other:0};return this._layers.forEach(h=>{const p=h.stats;e.push(p),n+=p.line.indexed.geometrySize+p.line.nonIndexed.geometrySize,r+=p.mesh.indexed.geometrySize+p.mesh.nonIndexed.geometrySize,o+=p.point.indexed.geometrySize+p.point.nonIndexed.geometrySize,a+=p.unbatched.geometrySize,l+=p.unbatched.count,c.line+=p.unbatched.byType.line,c.mesh+=p.unbatched.byType.mesh,c.point+=p.unbatched.byType.point,c.other+=p.unbatched.byType.other,t+=p.summary.totalGeometrySize,i+=p.summary.totalMappingSize}),{layers:e,summary:{entityCount:this.entityCount,totalSize:{line:n,mesh:r,point:o,unbatched:a,geometry:t,mapping:i,unbatchedCount:l,unbatchedByType:c}}}}clear(){return this._layers.forEach(e=>{e.clear()}),this._layers.clear(),this._cachedBox.makeEmpty(),this._boxDirty=!0,this._extentExcludedObjectIds.clear(),this._insertLayerByObjectId.clear(),this._spatialIndex.clear(),this}rerenderPoints(e){this._layers.forEach(t=>{t.rerenderPoints(e)})}isIntersectWith(e,t){const i=this.getLayersByObjectId(e);for(let n=0;n<i.length;++n){const r=i[n];if(r&&r.isIntersectWith(e,t))return!0}return!1}hasVisibleEntity(e){return this.getLayersByObjectId(e).some(t=>t.visible)}addEntity(e,t=!0){if(!e.objectId)throw new Error("Object id is required to add one entity!");if(!e.layerName)throw new Error("Layer name is required to add one entity!");const i=this._layers.get(e.layerName);if(!i)throw new Error(`layer '${e.layerName}' doesn't exist!`);i.addEntity(e);const n=e.userData.insertLayerName;return n&&this._insertLayerByObjectId.set(e.objectId,n),t?this._extentExcludedObjectIds.delete(e.objectId):this._extentExcludedObjectIds.add(e.objectId),this.invalidateBox(),this.registerEntitySpatialIndex(e),this}addDirectEntity(e,t=!0){if(!e.objectId)throw new Error("Object id is required to add one entity!");if(!e.layerName)throw new Error("Layer name is required to add one entity!");const i=this._layers.get(e.layerName);if(!i)throw new Error(`layer '${e.layerName}' doesn't exist!`);return i.addDirectEntity(e)?(t?this._extentExcludedObjectIds.delete(e.objectId):this._extentExcludedObjectIds.add(e.objectId),this.invalidateBox(),this.registerSpatialIndexBox(e.objectId,e.wcsBbox),!0):!1}removeEntity(e){let t=!1;for(const[i,n]of this._layers)n.removeEntity(e)&&(t=!0);return t&&(this._spatialIndex.removeById(e),this._extentExcludedObjectIds.delete(e),this._insertLayerByObjectId.delete(e),this.invalidateBox()),t}updateEntity(e){for(const[t,i]of this._layers)if(i.updateEntity(e)){const n=e.userData.insertLayerName;return n&&this._insertLayerByObjectId.set(e.objectId,n),this._spatialIndex.removeById(e.objectId),this.registerEntitySpatialIndex(e),this.invalidateBox(),!0}return!1}hasEntity(e){for(const[t,i]of this._layers)if(i.hasEntity(e))return!0;return!1}setEntityVisible(e,t){let i=!1;for(const[n,r]of this._layers)r.setEntityVisible(e,t)&&(i=!0);return i&&this.invalidateBox(),i}getEntityVisible(e){for(const[t,i]of this._layers){const n=i.getEntityVisible(e);if(n!==void 0)return n}}canCreateEntityPreview(e,t){if(e.length===0)return!1;if((t==null?void 0:t.requireAllEntities)??!0){for(const n of e){if(!this.hasEntity(n))return!1;const r=new L.Box3;if(this.computeEntityPreviewBoundsBox([n],r),r.isEmpty())return!1}return!0}return!this.computeEntityPreviewBoundsBox(e).isEmpty()}findPreviewableEntityIds(e){const t=[];for(const i of e){if(!this.hasEntity(i))continue;const n=new L.Box3;this.computeEntityPreviewBoundsBox([i],n),n.isEmpty()||t.push(i)}return t}computeEntityPreviewBoundsBox(e,t=new L.Box3){if(t.makeEmpty(),e.length===0)return t;const i=new Set(e),n=new L.Box3;for(const r of this._layers.values())r.computeBatchBoundingBox(n,void 0,i),n.isEmpty()||t.union(n);return t}computeEntityPreviewBounds2d(e,t=1.1){const i=this.computeEntityPreviewBoundsBox(e);return M.AcTrEntityPreview.box3ToBounds2d(i,t)}createEntityPreviewRoot(e,t){const i=(t==null?void 0:t.missingEntity)??"fail",n=(t==null?void 0:t.requireAllEntities)??!1;if(n){for(const a of e)if(!this.hasEntity(a))return null}const r=new Map;for(const a of e){const l=this.getLayersByObjectId(a);if(l.length===0){if(n||i==="fail")return null;continue}for(const c of l){let h=r.get(c);h||(h=new Set,r.set(c,h)),h.add(a)}}if(r.size===0)return null;const o=new L.Group;o.name="EntityPreviewRoot";for(const[a,l]of r){const c=[...l],h=a.createPreviewSubset(c,{maxSlots:Math.max(1e4,c.length*8),missingEntity:i});if(!h||h.children.length===0){if(i==="fail")return M.disposePreviewSubset(o),null;continue}o.add(h)}return o.children.length===0?null:o}getLayer(e){return this._layers.get(e)}addLayer(e){const t=e.name;let i=this._layers.get(t);return i===void 0&&(i=new Ut(e),this._layers.set(t,i),this._group.add(i.internalObject)),i}updateLayer(e){const t=this._layers.get(e.name);if(t){const i=t.visible;t.update(e),i!==t.visible&&this.invalidateBox()}return t}applyInsertLayerFreeze(e,t){const i=[];for(const[n,r]of this._insertLayerByObjectId){if(r!==e)continue;let o=!1;for(const a of this.getLayersByObjectId(n))a.name!==e&&a.setEntityVisible(n,!t)&&(o=!0);o&&i.push(n)}return i.length>0&&this.invalidateBox(),i}hover(e){this.applyHighlightToLayers(e,(t,i)=>t.hover(i))}unhover(e){this.applyHighlightToLayers(e,(t,i)=>t.unhover(i))}select(e){this.applyHighlightToLayers(e,(t,i)=>t.select(i))}unselect(e){this.applyHighlightToLayers(e,(t,i)=>t.unselect(i))}applyHighlightToLayers(e,t){const i=new Map;for(const n of e){const r=this.getLayersByObjectId(n);for(const o of r){const a=i.get(o);a?a.push(n):i.set(o,[n])}}i.forEach((n,r)=>t(r,n))}search(e,t){return this._spatialIndex.search({minX:e.min.x,minY:e.min.y,maxX:e.max.x,maxY:e.max.y},t)}getLayersByObjectId(e){const t=[];for(const[i,n]of this._layers)n.hasEntity(e)&&t.push(n);return t}getSpatialIndexChildBoxes(e){const t=e.userData.spatialIndexChildBoxes;if(!(!t||t.length===0))return t}registerEntitySpatialIndex(e){const t=this.getSpatialIndexChildBoxes(e);let i;if(t&&t.length>0){const n=xn(t);i={minX:n.minX,minY:n.minY,maxX:n.maxX,maxY:n.maxY,id:e.objectId}}else if(e instanceof M.AcTrGroup&&e.wcsChildBoxes.length>0){const n=xn(e.wcsChildBoxes.map(r=>({minX:r.minX,minY:r.minY,maxX:r.maxX,maxY:r.maxY,id:r.id})));i={minX:n.minX,minY:n.minY,maxX:n.maxX,maxY:n.maxY,id:e.objectId}}else i={minX:e.wcsBbox.min.x,minY:e.wcsBbox.min.y,maxX:e.wcsBbox.max.x,maxY:e.wcsBbox.max.y,id:e.objectId};this._spatialIndex.insert({minX:i.minX,minY:i.minY,maxX:i.maxX,maxY:i.maxY,id:e.objectId}),t&&t.length>0&&(e.wcsBbox.min.set(i.minX,i.minY,e.wcsBbox.min.z),e.wcsBbox.max.set(i.maxX,i.maxY,e.wcsBbox.max.z)),t?this._spatialIndex.ensureChildIndex(e.objectId,t):e instanceof M.AcTrGroup&&this._spatialIndex.createChildIndex(e)}registerSpatialIndexBox(e,t){this._spatialIndex.insert({minX:t.min.x,minY:t.min.y,maxX:t.max.x,maxY:t.max.y,id:e})}}class ml{constructor(){this._scene=new L.Scene,this._transientManager=new M.AcTrTransientManager(this._scene),this._htmlTransientManager=new M.AcTrHtmlTransientManager(this._scene),this._previewOverlayManager=new M.AcTrPreviewOverlayManager(this._scene),this._layers=new Map,this._layouts=new Map,this._activeLayoutBtrId="",this._modelSpaceBtrId=""}get htmlTransientManager(){return this._htmlTransientManager}get layers(){return this._layers}get layouts(){return this._layouts}get box(){const e=this.activeLayout;if(!e)return;const t=e.box;return t.isEmpty()?void 0:t}get internalScene(){return this._scene}get modelSpaceBtrId(){return this._modelSpaceBtrId}set modelSpaceBtrId(e){if(this._modelSpaceBtrId=e,!this._layouts.has(e))throw new Error(`[AcTrScene] No layout assiciated with the specified block table record id '${e}'!`)}get activeLayoutBtrId(){return this._activeLayoutBtrId}set activeLayoutBtrId(e){this._activeLayoutBtrId=e,this._layouts.forEach((t,i)=>{t.visible=e==i})}get activeLayout(){if(this._activeLayoutBtrId&&this._layouts.has(this._activeLayoutBtrId))return this._layouts.get(this._activeLayoutBtrId)}get modelSpaceLayout(){if(this._modelSpaceBtrId&&this._layouts.has(this._modelSpaceBtrId))return this._layouts.get(this._modelSpaceBtrId)}get stats(){const e=[];let t=0,i=0,n=0,r=0,o=0,a=0,l=0,c=0;const h={line:0,mesh:0,point:0,other:0};return this._layouts.forEach(p=>e.push(p.stats)),e.forEach(p=>{t+=p.summary.entityCount,i+=p.summary.totalSize.line,n+=p.summary.totalSize.mesh,r+=p.summary.totalSize.point,o+=p.summary.totalSize.unbatched,a+=p.summary.totalSize.geometry,l+=p.summary.totalSize.mapping,c+=p.summary.totalSize.unbatchedCount,h.line+=p.summary.totalSize.unbatchedByType.line,h.mesh+=p.summary.totalSize.unbatchedByType.mesh,h.point+=p.summary.totalSize.unbatchedByType.point,h.other+=p.summary.totalSize.unbatchedByType.other}),{layouts:e,summary:{layoutCount:e.length,entityCount:t,totalSize:{line:i,mesh:n,point:r,unbatched:o,geometry:a,mapping:l,unbatchedCount:c,unbatchedByType:h}}}}addEmptyLayout(e){const t=this._layouts.get(e);if(t)return t;const i=new pl;return this._layouts.set(e,i),this._scene.add(i.internalObject),i.visible=e==this._activeLayoutBtrId,this._layers.forEach(n=>{i.addLayer(n)}),i}clear(){return this._layouts.forEach(e=>{this._scene.remove(e.internalObject),e.clear()}),this._layouts.clear(),this._layers.clear(),this._transientManager.clear(),this._htmlTransientManager.clear(),this._previewOverlayManager.clear(),this._scene.clear(),this._transientManager=new M.AcTrTransientManager(this._scene),this._htmlTransientManager=new M.AcTrHtmlTransientManager(this._scene),this._previewOverlayManager=new M.AcTrPreviewOverlayManager(this._scene),this}hover(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.hover(e)),!0)}unhover(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.unhover(e)),!0)}select(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.select(e)),!0)}unselect(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.unselect(e)),!0)}search(e,t){const i=this.activeLayout;return i?i.search(e,t):[]}addLayer(e){const t=[];return this._layers.set(e.name,e),this._layouts.forEach(i=>{const n=i.addLayer(e);n&&t.push(n)}),t}updateLayer(e){const t=this._layers.get(e.name),i=(t==null?void 0:t.isFrozen)??!1,n=[];this._layers.set(e.name,e);const r=new Set;return this._layouts.forEach(o=>{const a=o.updateLayer(e);if(a&&n.push(a),e.isFrozen&&!i)for(const l of o.applyInsertLayerFreeze(e.name,!0))r.add(l);else if(!e.isFrozen&&i)for(const l of o.applyInsertLayerFreeze(e.name,!1))r.add(l)}),{updatedLayers:n,touchedObjectIds:r}}forEachSceneLayer(e,t){this._layouts.forEach(i=>{const n=i.getLayer(e);n&&t(n,i)})}addTransientEntity(e){this._transientManager.update(e)}removeTransientEntity(e){this._transientManager.remove(e)}setTransientEntityVisible(e,t){const i=this._transientManager.get(e);return!i||i.visible===t?!1:(i.visible=t,!0)}updateTransientPreviewTransforms(e){const t=e.map(i=>({id:i.objectId,matrix:i.matrix}));return{webgl:this._transientManager.applyTransforms(t),html:this._htmlTransientManager.applyTransforms(t)}}canCreatePreview(e){const t=this.activeLayout;return t?t.canCreateEntityPreview(e,{requireAllEntities:!0}):!1}computeEntityPreviewBounds2d(e,t=1.1,i="active-first"){const n=this.computeEntityPreviewBoundsBox(e,i);return M.AcTrEntityPreview.box3ToBounds2d(n,t)}findPreviewableEntityIds(e,t="active-first"){if(e.length===0)return[];if(t==="all"){const i=[],n=new Set(e);for(const r of this.getOrderedLayouts("all")){if(n.size===0)break;const o=r.findPreviewableEntityIds([...n]);if(o.length!==0){i.push(...o);for(const a of o)n.delete(a)}}return i}for(const i of this.getOrderedLayouts("active-first")){const n=i.findPreviewableEntityIds(e);if(n.length>0)return n}return[]}createEntityPreviewRoot(e,t){if(e.length===0)return null;const i=(t==null?void 0:t.scope)??"active-first",n={missingEntity:"skip",...t==null?void 0:t.layoutOptions};if(i==="all")return this.mergeEntityPreviewRoots(e,this.getOrderedLayouts("all"),n);for(const r of this.getOrderedLayouts("active-first")){const o=r.createEntityPreviewRoot(e,n);if(o)return o}return null}mergeEntityPreviewRoots(e,t,i){const n=new Set(e),r=new L.Group;r.name="EntityPreviewRoot";for(const o of t){if(n.size===0)break;const a=o.findPreviewableEntityIds([...n]);if(a.length===0)continue;const l=o.createEntityPreviewRoot(a,i);if(l){r.add(l);for(const c of a)n.delete(c)}}return r.children.length>0?r:null}getOrderedLayouts(e){if(e==="all")return[...this._layouts.values()];const t=[],i=this.activeLayout,n=this.modelSpaceLayout;i&&t.push(i),n&&n!==i&&t.push(n);for(const r of this._layouts.values())r!==i&&r!==n&&t.push(r);return t}computeEntityPreviewBoundsBox(e,t="active-first"){const i=new L.Box3,n=new L.Box3;if(t==="all"){const r=new Set(e);for(const o of this.getOrderedLayouts("all")){if(r.size===0)break;const a=o.findPreviewableEntityIds([...r]);if(a.length!==0){o.computeEntityPreviewBoundsBox(a,n),n.isEmpty()||i.union(n);for(const l of a)r.delete(l)}}return i}for(const r of this.getOrderedLayouts("active-first"))if(r.computeEntityPreviewBoundsBox(e,n),!n.isEmpty())return i.copy(n),i;return i.makeEmpty(),i}createPreview(e){const t=this.activeLayout;if(!t)return null;const i=t.createEntityPreviewRoot(e,{missingEntity:"fail",requireAllEntities:!0});return i?this._previewOverlayManager.add(i).id:null}updatePreview(e,t){return this._previewOverlayManager.update(e,t)}removePreview(e){return this._previewOverlayManager.remove(e)}addEntity(e,t=!0){const i=e.ownerId;if(i){let n=this._layouts.get(i);n||(n=this.addEmptyLayout(i)),n.addEntity(e,t)}else d.log.warn("[AcTrSecene] The owner id of one entity cannot be empty!");return this}addDirectEntity(e,t=!0){const i=e.ownerId;if(!i)return d.log.warn("[AcTrSecene] The owner id of one entity cannot be empty!"),!1;let n=this._layouts.get(i);return n||(n=this.addEmptyLayout(i)),n.addDirectEntity(e,t)}removeEntity(e){for(const[t,i]of this._layouts)if(i.removeEntity(e))return!0;return!1}updateEntity(e){for(const[t,i]of this._layouts)if(i.updateEntity(e))return!0;return!1}hasEntity(e){for(const[t,i]of this._layouts)if(i.hasEntity(e))return!0;return!1}setEntityVisible(e,t){let i=!1;for(const[n,r]of this._layouts)r.setEntityVisible(e,t)&&(i=!0);return i}getEntityVisible(e){for(const[t,i]of this._layouts){const n=i.getEntityVisible(e);if(n!==void 0)return n}}}const Cn="ml-html-text-editing",yl="ml-markup-inline-text-edit-styles",ym=400,gl=6,wi=new WeakSet;let _n=0;function fl(){return _n>0}function gm(){if(typeof document>"u"||document.getElementById(yl))return;const s=document.createElement("style");s.id=yl,s.textContent=`
127
+ .ml-html-text-editing,
128
+ .ml-html-text-editing:focus,
129
+ .ml-html-selected.ml-html-text-editing {
130
+ outline: none !important;
131
+ outline-offset: 0;
132
+ box-shadow: var(--ml-ui-shadow, 0 1px 4px rgba(0, 0, 0, 0.2));
130
133
  cursor: text !important;
131
134
  user-select: text;
132
135
  pointer-events: auto;
133
136
  min-height: 1.2em;
134
137
  }
135
- `,document.head.appendChild(s)}function sm(s){const e=window.getSelection();if(!e)return;const t=document.createRange();t.selectNodeContents(s),e.removeAllRanges(),e.addRange(t)}function rm(s){s.setAttribute("contenteditable","plaintext-only"),s.contentEditable!=="plaintext-only"&&(s.contentEditable="true")}function ul(s,e){if(!s)return!1;const t=e.t-s.t;if(t<0||t>im)return!1;const i=e.x-s.x,n=e.y-s.y;return i*i+n*n<=cl*cl}function pr(s){var r;nm();const{el:e,multiline:t=!1}=s,i=s.listenOn??e;if(bi.has(e)||(r=s.signal)!=null&&r.aborted)return Promise.resolve(void 0);const n=s.initialText!==void 0?s.initialText:(e.textContent??"").trim();return new Promise(o=>{var w;bi.add(e),An+=1,i.style.pointerEvents="auto",e.style.pointerEvents="auto",e.textContent=n,e.classList.add(al),e.tabIndex=0,rm(e);let a=!1,l=performance.now()+300;const c=()=>{var v;(v=s.signal)==null||v.removeEventListener("abort",f),e.classList.remove(al),e.removeAttribute("contenteditable"),e.removeAttribute("tabindex"),i.removeEventListener("pointerdown",p,!0),e.removeEventListener("keydown",m),e.removeEventListener("blur",g),bi.delete(e),An=Math.max(0,An-1)},h=v=>{if(a)return;a=!0;const x=(e.textContent??"").trim();if(!v){e.textContent=n,c(),o(void 0);return}e.textContent=x,c(),o(x)},p=v=>{v.stopPropagation()},m=v=>{if(!(v.isComposing||v.keyCode===229)){if(v.stopPropagation(),v.key==="Escape"){v.preventDefault(),h(!1);return}v.key==="Enter"&&(!t||!v.shiftKey)&&(v.preventDefault(),h(!0))}},g=()=>{if(performance.now()<l){e.focus();return}h(!0)},f=()=>h(!1);i.addEventListener("pointerdown",p,!0),e.addEventListener("keydown",m),e.addEventListener("blur",g),(w=s.signal)==null||w.addEventListener("abort",f),requestAnimationFrame(()=>{a||(l=performance.now()+300,e.focus(),sm(e))})})}function Cn(s){const{view:e,el:t,recordId:i,multiline:n=!1}=s,r=s.listenOn??t;r.style.pointerEvents="auto",t.style.pointerEvents="auto";let o,a=!1,l;const c=()=>{if(a||bi.has(t))return;const m=U().get(i),g=((m==null?void 0:m.text)??t.textContent??"").trim();U().setSelectedId(i),e.htmlTransientManager.selectGroup(i),l=new AbortController,pr({el:t,listenOn:r,multiline:n,initialText:g,signal:l.signal}).then(f=>{l=void 0,!(a||f===void 0||f===g)&&ve(e,"Edit Markup Text",()=>{U().updateMeta(i,{text:f})})})},h=m=>{if(m.button!==0||bi.has(t))return;const g={t:performance.now(),x:m.clientX,y:m.clientY},f=m.detail>=2||ul(o,g);o=g,f&&(m.stopPropagation(),c())},p=m=>{m.preventDefault(),m.stopPropagation(),c()};return r.addEventListener("pointerdown",h,!0),r.addEventListener("dblclick",p),()=>{a=!0,l==null||l.abort(),r.removeEventListener("pointerdown",h,!0),r.removeEventListener("dblclick",p)}}let mr=null;function hl(s){mr=s}function wi(){if(!mr)throw new Error("[AcApCommandServices] Not bound. Create AcApDocManager before running commands.");return mr}var F=(s=>(s[s.Read=0]="Read",s[s.Review=4]="Review",s[s.Write=8]="Write",s))(F||{});class z{constructor(){this._mode=F.Read,this.recordsUndoStack=!0,this._globalName="",this._localName="",this._userData={}}get userData(){return this._userData}get globalName(){return this._globalName}set globalName(e){this._globalName=e}get localName(){return this._localName}set localName(e){this._localName=e}get mode(){return this._mode}set mode(e){this._mode=e}onCommandWillStart(e){}onCommandEnded(e){}async trigger(e){const i=e.doc.database.transactionManager,n=this.shouldRecordUndoStack(e);let r=!1;n&&(i.startUndoMark(this.globalName||this.localName),i.startTransaction(),r=!0);try{this.onCommandWillStart(e),e.view.editor.events.commandWillStart.dispatch({command:this}),await this.execute(e)}catch(o){throw r&&i.hasTransaction()&&i.abortTransaction(),r&&(i.cancelUndoMark(),r=!1),o}finally{r&&i.hasTransaction()&&(i.commitTransaction(),i.endUndoMark(),r=!1,Q.emit("session-db-edit-committed",{}),lt()),e.view.editor.events.commandEnded.dispatch({command:this}),this.onCommandEnded(e)}}shouldRecordUndoStack(e){return this.recordsUndoStack?e.doc.openMode>=F.Review&&this.mode>=F.Review:!1}async execute(e){}showMessage(e,t="info",i){wi().showMessage(e,t,i)}notify(e,t="info"){Q.emit("message",{message:e,type:t})}showBusyIndicator(e){wi().showBusyIndicator(e)}hideBusyIndicator(){wi().hideBusyIndicator()}async withBusyIndicator(e,t){return wi().withBusyIndicator(e,t)}}class om{constructor(e){this._index=0,this._commands=[],e.forEach(t=>{const i=t.groupName;t.commandsByGlobalName.forEach(n=>{this._commands.push({command:n,commandGroup:i})})})}[Symbol.iterator](){return this}get command(){return this._index<this._commands.length?this._commands[this._index].command:null}get commandGroup(){return this._index<this._commands.length?this._commands[this._index].commandGroup:null}next(){for(;this._index<this._commands.length;){const e=this._commands[this._index];return this._index+=1,{value:e,done:!1}}return{value:null,done:!0}}}const ri=class ri{constructor(){this._activeCommand=null,this._activeView=null,this._activePromise=null,this._commandsByGroup=[],this._systemCommandGroup={groupName:ri.SYSTEMT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._defaultCommandGroup={groupName:ri.DEFAUT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._commandsByGroup.push(this._systemCommandGroup),this._commandsByGroup.push(this._defaultCommandGroup)}addCommand(e,t,i,n,r){if(e=e.toUpperCase(),t=t.toUpperCase(),i=i.toUpperCase(),!t)throw new Error("[AcEdCommandStack] The global name of the command is required!");i||(i=t);let o=this._defaultCommandGroup;if(e){const l=this._commandsByGroup.find(c=>c.groupName==e);l?o=l:(o={groupName:e,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._commandsByGroup.push(o))}if(o.commandsByGlobalName.has(t))throw new Error(`[AcEdCommandStack] The command with global name '${t}' already exists!`);if(o.commandsByLocalName.has(i))throw new Error(`[AcEdCommandStack] The command with local name '${i}' already exists!`);const a=this.normalizeAliases(r,t,i);for(const l of a){if(o.commandsByAlias.has(l))throw new Error(`[AcEdCommandStack] The command alias '${l}' already exists!`);if(o.commandsByGlobalName.has(l)||o.commandsByLocalName.has(l))throw new Error(`[AcEdCommandStack] The command alias '${l}' conflicts with existing command name!`)}o.commandsByGlobalName.set(t,n),o.commandsByLocalName.set(i,n),a.forEach(l=>{o.commandsByAlias.set(l,n)}),o.aliasesByCommand.set(n,new Set(a)),n.globalName=t,n.localName=i}iterator(){return new om(this._commandsByGroup)}searchCommandsByPrefix(e,t){e=e.toUpperCase();const i=[],n=this.iterator();let r=n.next();for(;!r.done;){const{command:o}=r.value;(o.globalName.startsWith(e)||o.localName.startsWith(e)||this.commandAliasStartsWith(r.value.commandGroup,o,e))&&(t===void 0||this.isModeCompatible(t,o.mode))&&i.push(r.value),r=n.next()}return i}lookupGlobalCmd(e,t){e=e.toUpperCase();let i;for(const n of this._commandsByGroup)if(i=n.commandsByGlobalName.get(e),i||(i=n.commandsByAlias.get(e)),i){if(t===void 0||this.isModeCompatible(t,i.mode))break;i=void 0}return i}lookupLocalCmd(e,t){e=e.toUpperCase();let i;for(const n of this._commandsByGroup)if(i=n.commandsByLocalName.get(e),i||(i=n.commandsByAlias.get(e)),i){if(t===void 0||this.isModeCompatible(t,i.mode))break;i=void 0}return i}removeCmd(e,t){e=e.toUpperCase(),t=t.toUpperCase();for(const i of this._commandsByGroup)if(i.groupName==e){const n=i.commandsByGlobalName.get(t);if(!n)return!1;i.commandsByGlobalName.delete(t),i.commandsByLocalName.delete(n.localName);const r=i.aliasesByCommand.get(n);return r==null||r.forEach(o=>{i.commandsByAlias.delete(o)}),i.aliasesByCommand.delete(n),!0}return!1}removeGroup(e){e=e.toUpperCase();const t=this._commandsByGroup.findIndex(i=>i.groupName===e);return t>=0?(this._commandsByGroup.splice(t,1),!0):!1}get activeCommand(){return this._activeCommand}markActive(e,t,i){this._activeCommand=e,this._activeView=t,this._activePromise=i}clearActive(e){this._activeCommand===e&&(this._activeCommand=null,this._activeView=null,this._activePromise=null)}async cancelActive(){const e=this._activeView,t=this._activePromise;if(this._activeCommand&&(e==null||e.editor.cancelActiveInput(),t))try{await t}catch{}}removeAll(){this._defaultCommandGroup.commandsByGlobalName.clear(),this._defaultCommandGroup.commandsByLocalName.clear(),this._defaultCommandGroup.commandsByAlias.clear(),this._defaultCommandGroup.aliasesByCommand.clear(),this._systemCommandGroup.commandsByGlobalName.clear(),this._systemCommandGroup.commandsByLocalName.clear(),this._systemCommandGroup.commandsByAlias.clear(),this._systemCommandGroup.aliasesByCommand.clear(),this._commandsByGroup=[this._systemCommandGroup,this._defaultCommandGroup]}getCommandAliases(e,t){const i=t==null?void 0:t.trim().toUpperCase(),n=i?this._commandsByGroup.filter(r=>r.groupName===i):this._commandsByGroup;for(const r of n){const o=r.aliasesByCommand.get(e);if(o)return[...o]}return[]}commandAliasStartsWith(e,t,i){const n=this._commandsByGroup.find(o=>o.groupName===e);if(!n)return!1;const r=n.aliasesByCommand.get(t);if(!r)return!1;for(const o of r)if(o.startsWith(i))return!0;return!1}normalizeAliases(e,t,i){const n=Array.isArray(e)?e:e?[e]:[],r=new Set;return n.forEach(o=>{const a=o.trim().toUpperCase();a&&a!==t&&a!==i&&r.add(a)}),[...r]}isModeCompatible(e,t){return e>=t}};ri.SYSTEMT_COMMAND_GROUP_NAME="ACAD",ri.DEFAUT_COMMAND_GROUP_NAME="USER";let ce=ri;function am(s){Q.emit("message",{message:s,type:"warning"})}class yr{constructor(e,t,i=1e3,n=0){this.condition=e,this.action=t,this.checkInterval=i,this.timeout=n,this.timerId=null,this.timeoutId=null}start(){this.timerId===null&&(this.timerId=window.setInterval(()=>{this.condition()&&this.executeAndStop()},this.checkInterval),this.timeout>0&&(this.timeoutId=window.setTimeout(()=>{u.log.warn("AcEdConditionWaiter: Timeout reached."),this.executeAndStop()},this.timeout)))}stop(){this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}executeAndStop(){this.stop(),this.action()}isRunning(){return this.timerId!==null}}const lm={light:{"--ml-ui-text":"var(--el-text-color-primary, #303133)","--ml-ui-text-muted":"var(--el-text-color-regular, #606266)","--ml-ui-bg":"var(--el-bg-color-overlay, #ffffff)","--ml-ui-border":"var(--el-border-color, #dcdfe6)","--ml-ui-shadow":"var(--el-box-shadow, 0 2px 6px rgba(0, 0, 0, 0.12))","--ml-ui-overlay":"var(--el-overlay-color-lighter, rgba(0, 0, 0, 0.18))","--ml-ui-accent":"var(--el-color-primary, #409eff)","--ml-ui-accent-alt":"var(--el-color-info, #909399)","--ml-ui-danger":"var(--el-color-danger, #f56c6c)","--ml-ui-canvas-line":"var(--el-color-primary, #409eff)","--ml-ui-canvas-fill":"rgba(64, 158, 255, 0.2)","--ml-ui-canvas-fill-mix":"color-mix(in srgb, var(--el-color-primary, #409eff) 20%, transparent)"},dark:{"--ml-ui-text":"var(--el-text-color-primary, #e5eaf3)","--ml-ui-text-muted":"var(--el-text-color-regular, #cfd3dc)","--ml-ui-bg":"var(--el-bg-color-overlay, #1d1e1f)","--ml-ui-border":"var(--el-border-color, #4c4d4f)","--ml-ui-shadow":"var(--el-box-shadow, 0 6px 18px rgba(0, 0, 0, 0.35))","--ml-ui-overlay":"var(--el-overlay-color-lighter, rgba(0, 0, 0, 0.5))","--ml-ui-accent":"var(--el-color-primary, #409eff)","--ml-ui-accent-alt":"var(--el-color-info, #909399)","--ml-ui-danger":"var(--el-color-danger, #f56c6c)","--ml-ui-canvas-line":"var(--el-color-primary, #409eff)","--ml-ui-canvas-fill":"rgba(64, 158, 255, 0.2)","--ml-ui-canvas-fill-mix":"color-mix(in srgb, var(--el-color-primary, #409eff) 20%, transparent)"}};function gr(s,e=document.documentElement){const t=lm[s];Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])}),e.setAttribute("data-ml-ui-theme",s)}function fr(s){let e=s;for(;e;){const i=e.getAttribute("data-ml-ui-theme");if(i==="light"||i==="dark")return i;e=e.parentElement}const t=document.documentElement.getAttribute("data-ml-ui-theme");return t==="light"||t==="dark"?t:document.documentElement.classList.contains("dark")?"dark":"light"}const pl=600,ml=`(max-width: ${pl}px)`;function cm(){var s;return((s=window.matchMedia)==null?void 0:s.call(window,ml).matches)??!1}const yl=960,gl=`(max-width: ${yl}px)`;function dm(){var s;return((s=window.matchMedia)==null?void 0:s.call(window,gl).matches)??!1}const um=20;class Ut{constructor(e){this._view=e}resolve(e){const t=e.hitRadiusPx??um,i=e.lastPoint??e.cursorWcs,n=this.collectOsnapPoints(e.cursorWcs,i,t);if(n.length===0)return;const r=this._view.screenToWorld({x:0,y:0}),a=this._view.screenToWorld({x:t,y:0}).x-r.x;let l=Number.MAX_VALUE,c=Number.MAX_VALUE,h=-1;for(let p=0;p<n.length;p++){const m=n[p],g=e.cursorWcs.x-m.x,f=e.cursorWcs.y-m.y,w=Math.hypot(g,f);if(w>=a)continue;const v=Ut.osnapModePriority(m.type);(v<l||v===l&&w<c)&&(l=v,c=w,h=p)}return h!==-1?n[h]:void 0}static osnapModeToMarkerType(e){switch(e){case u.AcDbOsnapMode.EndPoint:return"rect";case u.AcDbOsnapMode.MidPoint:return"triangle";case u.AcDbOsnapMode.Center:return"circle";case u.AcDbOsnapMode.Quadrant:return"diamond";case u.AcDbOsnapMode.Nearest:return"x";default:return"rect"}}static osnapModePriority(e){switch(e){case u.AcDbOsnapMode.EndPoint:case u.AcDbOsnapMode.MidPoint:case u.AcDbOsnapMode.Center:return 0;case u.AcDbOsnapMode.Quadrant:return 1;case u.AcDbOsnapMode.Nearest:return 2;default:return 1}}collectOsnapPointsByMode(e,t,i,n,r,o){const a=i.length;e.subGetOsnapPoints(t,n,r,i,o);for(let l=a;l<i.length;l++)i[l].type=t}collectOsnapPointsInAvailableModes(e,t,i,n,r){u.acdbMaskToOsnapModes(we.instance.osnapModes).forEach(a=>this.collectOsnapPointsByMode(e,a,t,i,n,r))}collectOsnapPoints(e,t,i){const n=this._view.pick(e,i),o=u.acdbHostApplicationServices().workingDatabase.tables.blockTable.modelSpace,a=[],l=u.AcGeGeometryUtil.point2dToPoint3d(e),c=u.AcGeGeometryUtil.point2dToPoint3d(t);return n.forEach(h=>{const p=o.getIdAt(h.id);p&&(h.children&&h.children.length>0?h.children.forEach(m=>this.collectOsnapPointsInAvailableModes(p,a,l,c,m.id)):this.collectOsnapPointsInAvailableModes(p,a,l,c))}),a}}class _n{constructor(e="rect",t=12,i="var(--ml-ui-canvas-line, green)",n){this._type=e,this._size=t,this._color=i,this._host=n,_n.injectCSS(),getComputedStyle(this._host).position==="static"&&(this._host.style.position="relative"),this._el=document.createElement("div"),this._el.classList.add("ml-marker"),this._el.style.color=i,this.applyShape(),this._host.appendChild(this._el)}get color(){return this._color}set color(e){this._color=e,this._el.style.color=e}get type(){return this._type}set type(e){this._type=e,this.applyShape()}static injectCSS(){if(document.getElementById("ml-marker-style"))return;const e=document.createElement("style");e.id="ml-marker-style",e.textContent=`
138
+ `,document.head.appendChild(s)}function fm(s){const e=window.getSelection();if(!e)return;const t=document.createRange();t.selectNodeContents(s),e.removeAllRanges(),e.addRange(t)}function bm(s){s.setAttribute("contenteditable","plaintext-only"),s.contentEditable!=="plaintext-only"&&(s.contentEditable="true")}function bl(s,e){if(!s)return!1;const t=e.t-s.t;if(t<0||t>ym)return!1;const i=e.x-s.x,n=e.y-s.y;return i*i+n*n<=gl*gl}function fr(s){var r;gm();const{el:e,multiline:t=!1}=s,i=s.listenOn??e;if(wi.has(e)||(r=s.signal)!=null&&r.aborted)return Promise.resolve(void 0);const n=s.initialText!==void 0?s.initialText:(e.textContent??"").trim();return new Promise(o=>{var w;wi.add(e),_n+=1,i.style.pointerEvents="auto",e.style.pointerEvents="auto",e.textContent=n,e.classList.add(Cn),i.classList.add(Cn),e.tabIndex=0,bm(e);let a=!1,l=performance.now()+300;const c=()=>{var v;(v=s.signal)==null||v.removeEventListener("abort",f),e.classList.remove(Cn),i.classList.remove(Cn),e.removeAttribute("contenteditable"),e.removeAttribute("tabindex"),i.removeEventListener("pointerdown",p,!0),e.removeEventListener("keydown",m),e.removeEventListener("blur",g),wi.delete(e),_n=Math.max(0,_n-1)},h=v=>{if(a)return;a=!0;const x=(e.textContent??"").trim();if(!v){e.textContent=n,c(),o(void 0);return}e.textContent=x,c(),o(x)},p=v=>{v.stopPropagation()},m=v=>{if(!(v.isComposing||v.keyCode===229)){if(v.stopPropagation(),v.key==="Escape"){v.preventDefault(),h(!1);return}v.key==="Enter"&&(!t||!v.shiftKey)&&(v.preventDefault(),h(!0))}},g=()=>{if(performance.now()<l){e.focus();return}h(!0)},f=()=>h(!1);i.addEventListener("pointerdown",p,!0),e.addEventListener("keydown",m),e.addEventListener("blur",g),(w=s.signal)==null||w.addEventListener("abort",f),requestAnimationFrame(()=>{a||(l=performance.now()+300,e.focus(),fm(e))})})}function En(s){const{view:e,el:t,recordId:i,multiline:n=!1}=s,r=s.listenOn??t;r.style.pointerEvents="auto",t.style.pointerEvents="auto";let o,a=!1,l;const c=()=>{if(a||wi.has(t))return;const m=K().get(i),g=((m==null?void 0:m.text)??t.textContent??"").trim();K().setSelectedId(i),e.htmlTransientManager.selectGroup(i),l=new AbortController,fr({el:t,listenOn:r,multiline:n,initialText:g,signal:l.signal}).then(f=>{l=void 0,!(a||f===void 0||f===g)&&ke(e,"Edit Markup Text",()=>{K().updateMeta(i,{text:f})})})},h=m=>{if(m.button!==0||wi.has(t))return;const g={t:performance.now(),x:m.clientX,y:m.clientY},f=m.detail>=2||bl(o,g);o=g,f&&(m.stopPropagation(),c())},p=m=>{m.preventDefault(),m.stopPropagation(),c()};return r.addEventListener("pointerdown",h,!0),r.addEventListener("dblclick",p),()=>{a=!0,l==null||l.abort(),r.removeEventListener("pointerdown",h,!0),r.removeEventListener("dblclick",p)}}let br=null;function wl(s){br=s}function vi(){if(!br)throw new Error("[AcApCommandServices] Not bound. Create AcApDocManager before running commands.");return br}var F=(s=>(s[s.Read=0]="Read",s[s.Review=4]="Review",s[s.Write=8]="Write",s))(F||{});class z{constructor(){this._mode=F.Read,this.recordsUndoStack=!0,this._globalName="",this._localName="",this._userData={}}get userData(){return this._userData}get globalName(){return this._globalName}set globalName(e){this._globalName=e}get localName(){return this._localName}set localName(e){this._localName=e}get mode(){return this._mode}set mode(e){this._mode=e}onCommandWillStart(e){}onCommandEnded(e){}async trigger(e){const i=e.doc.database.transactionManager,n=this.shouldRecordUndoStack(e);let r=!1;n&&(i.startUndoMark(this.globalName||this.localName),i.startTransaction(),r=!0);try{this.onCommandWillStart(e),e.view.editor.events.commandWillStart.dispatch({command:this}),await this.execute(e)}catch(o){throw r&&i.hasTransaction()&&i.abortTransaction(),r&&(i.cancelUndoMark(),r=!1),o}finally{r&&i.hasTransaction()&&(i.commitTransaction(),i.endUndoMark(),r=!1,ee.emit("session-db-edit-committed",{}),ht()),e.view.editor.events.commandEnded.dispatch({command:this}),this.onCommandEnded(e)}}shouldRecordUndoStack(e){return this.recordsUndoStack?e.doc.openMode>=F.Review&&this.mode>=F.Review:!1}async execute(e){}showMessage(e,t="info",i){vi().showMessage(e,t,i)}notify(e,t="info"){ee.emit("message",{message:e,type:t})}showBusyIndicator(e){vi().showBusyIndicator(e)}hideBusyIndicator(){vi().hideBusyIndicator()}async withBusyIndicator(e,t){return vi().withBusyIndicator(e,t)}}class wm{constructor(e){this._index=0,this._commands=[],e.forEach(t=>{const i=t.groupName;t.commandsByGlobalName.forEach(n=>{this._commands.push({command:n,commandGroup:i})})})}[Symbol.iterator](){return this}get command(){return this._index<this._commands.length?this._commands[this._index].command:null}get commandGroup(){return this._index<this._commands.length?this._commands[this._index].commandGroup:null}next(){for(;this._index<this._commands.length;){const e=this._commands[this._index];return this._index+=1,{value:e,done:!1}}return{value:null,done:!0}}}const ri=class ri{constructor(){this._activeCommand=null,this._activeView=null,this._activePromise=null,this._commandsByGroup=[],this._systemCommandGroup={groupName:ri.SYSTEMT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._defaultCommandGroup={groupName:ri.DEFAUT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._commandsByGroup.push(this._systemCommandGroup),this._commandsByGroup.push(this._defaultCommandGroup)}addCommand(e,t,i,n,r){if(e=e.toUpperCase(),t=t.toUpperCase(),i=i.toUpperCase(),!t)throw new Error("[AcEdCommandStack] The global name of the command is required!");i||(i=t);let o=this._defaultCommandGroup;if(e){const l=this._commandsByGroup.find(c=>c.groupName==e);l?o=l:(o={groupName:e,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._commandsByGroup.push(o))}if(o.commandsByGlobalName.has(t))throw new Error(`[AcEdCommandStack] The command with global name '${t}' already exists!`);if(o.commandsByLocalName.has(i))throw new Error(`[AcEdCommandStack] The command with local name '${i}' already exists!`);const a=this.normalizeAliases(r,t,i);for(const l of a){if(o.commandsByAlias.has(l))throw new Error(`[AcEdCommandStack] The command alias '${l}' already exists!`);if(o.commandsByGlobalName.has(l)||o.commandsByLocalName.has(l))throw new Error(`[AcEdCommandStack] The command alias '${l}' conflicts with existing command name!`)}o.commandsByGlobalName.set(t,n),o.commandsByLocalName.set(i,n),a.forEach(l=>{o.commandsByAlias.set(l,n)}),o.aliasesByCommand.set(n,new Set(a)),n.globalName=t,n.localName=i}iterator(){return new wm(this._commandsByGroup)}searchCommandsByPrefix(e,t){e=e.toUpperCase();const i=[],n=this.iterator();let r=n.next();for(;!r.done;){const{command:o}=r.value;(o.globalName.startsWith(e)||o.localName.startsWith(e)||this.commandAliasStartsWith(r.value.commandGroup,o,e))&&(t===void 0||this.isModeCompatible(t,o.mode))&&i.push(r.value),r=n.next()}return i}lookupGlobalCmd(e,t){e=e.toUpperCase();let i;for(const n of this._commandsByGroup)if(i=n.commandsByGlobalName.get(e),i||(i=n.commandsByAlias.get(e)),i){if(t===void 0||this.isModeCompatible(t,i.mode))break;i=void 0}return i}lookupLocalCmd(e,t){e=e.toUpperCase();let i;for(const n of this._commandsByGroup)if(i=n.commandsByLocalName.get(e),i||(i=n.commandsByAlias.get(e)),i){if(t===void 0||this.isModeCompatible(t,i.mode))break;i=void 0}return i}removeCmd(e,t){e=e.toUpperCase(),t=t.toUpperCase();for(const i of this._commandsByGroup)if(i.groupName==e){const n=i.commandsByGlobalName.get(t);if(!n)return!1;i.commandsByGlobalName.delete(t),i.commandsByLocalName.delete(n.localName);const r=i.aliasesByCommand.get(n);return r==null||r.forEach(o=>{i.commandsByAlias.delete(o)}),i.aliasesByCommand.delete(n),!0}return!1}removeGroup(e){e=e.toUpperCase();const t=this._commandsByGroup.findIndex(i=>i.groupName===e);return t>=0?(this._commandsByGroup.splice(t,1),!0):!1}get activeCommand(){return this._activeCommand}markActive(e,t,i){this._activeCommand=e,this._activeView=t,this._activePromise=i}clearActive(e){this._activeCommand===e&&(this._activeCommand=null,this._activeView=null,this._activePromise=null)}async cancelActive(){const e=this._activeView,t=this._activePromise;if(this._activeCommand&&(e==null||e.editor.cancelActiveInput(),t))try{await t}catch{}}removeAll(){this._defaultCommandGroup.commandsByGlobalName.clear(),this._defaultCommandGroup.commandsByLocalName.clear(),this._defaultCommandGroup.commandsByAlias.clear(),this._defaultCommandGroup.aliasesByCommand.clear(),this._systemCommandGroup.commandsByGlobalName.clear(),this._systemCommandGroup.commandsByLocalName.clear(),this._systemCommandGroup.commandsByAlias.clear(),this._systemCommandGroup.aliasesByCommand.clear(),this._commandsByGroup=[this._systemCommandGroup,this._defaultCommandGroup]}getCommandAliases(e,t){const i=t==null?void 0:t.trim().toUpperCase(),n=i?this._commandsByGroup.filter(r=>r.groupName===i):this._commandsByGroup;for(const r of n){const o=r.aliasesByCommand.get(e);if(o)return[...o]}return[]}commandAliasStartsWith(e,t,i){const n=this._commandsByGroup.find(o=>o.groupName===e);if(!n)return!1;const r=n.aliasesByCommand.get(t);if(!r)return!1;for(const o of r)if(o.startsWith(i))return!0;return!1}normalizeAliases(e,t,i){const n=Array.isArray(e)?e:e?[e]:[],r=new Set;return n.forEach(o=>{const a=o.trim().toUpperCase();a&&a!==t&&a!==i&&r.add(a)}),[...r]}isModeCompatible(e,t){return e>=t}};ri.SYSTEMT_COMMAND_GROUP_NAME="ACAD",ri.DEFAUT_COMMAND_GROUP_NAME="USER";let de=ri;function vm(s){ee.emit("message",{message:s,type:"warning"})}class wr{constructor(e,t,i=1e3,n=0){this.condition=e,this.action=t,this.checkInterval=i,this.timeout=n,this.timerId=null,this.timeoutId=null}start(){this.timerId===null&&(this.timerId=window.setInterval(()=>{this.condition()&&this.executeAndStop()},this.checkInterval),this.timeout>0&&(this.timeoutId=window.setTimeout(()=>{d.log.warn("AcEdConditionWaiter: Timeout reached."),this.executeAndStop()},this.timeout)))}stop(){this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}executeAndStop(){this.stop(),this.action()}isRunning(){return this.timerId!==null}}const km={light:{"--ml-ui-text":"var(--el-text-color-primary, #303133)","--ml-ui-text-muted":"var(--el-text-color-regular, #606266)","--ml-ui-bg":"var(--el-bg-color-overlay, #ffffff)","--ml-ui-border":"var(--el-border-color, #dcdfe6)","--ml-ui-shadow":"var(--el-box-shadow, 0 2px 6px rgba(0, 0, 0, 0.12))","--ml-ui-overlay":"var(--el-overlay-color-lighter, rgba(0, 0, 0, 0.18))","--ml-ui-accent":"var(--el-color-primary, #409eff)","--ml-ui-accent-alt":"var(--el-color-info, #909399)","--ml-ui-danger":"var(--el-color-danger, #f56c6c)","--ml-ui-canvas-line":"var(--el-color-primary, #409eff)","--ml-ui-canvas-fill":"rgba(64, 158, 255, 0.2)","--ml-ui-canvas-fill-mix":"color-mix(in srgb, var(--el-color-primary, #409eff) 20%, transparent)"},dark:{"--ml-ui-text":"var(--el-text-color-primary, #e5eaf3)","--ml-ui-text-muted":"var(--el-text-color-regular, #cfd3dc)","--ml-ui-bg":"var(--el-bg-color-overlay, #1d1e1f)","--ml-ui-border":"var(--el-border-color, #4c4d4f)","--ml-ui-shadow":"var(--el-box-shadow, 0 6px 18px rgba(0, 0, 0, 0.35))","--ml-ui-overlay":"var(--el-overlay-color-lighter, rgba(0, 0, 0, 0.5))","--ml-ui-accent":"var(--el-color-primary, #409eff)","--ml-ui-accent-alt":"var(--el-color-info, #909399)","--ml-ui-danger":"var(--el-color-danger, #f56c6c)","--ml-ui-canvas-line":"var(--el-color-primary, #409eff)","--ml-ui-canvas-fill":"rgba(64, 158, 255, 0.2)","--ml-ui-canvas-fill-mix":"color-mix(in srgb, var(--el-color-primary, #409eff) 20%, transparent)"}};function vr(s,e=document.documentElement){const t=km[s];Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])}),e.setAttribute("data-ml-ui-theme",s)}function kr(s){let e=s;for(;e;){const i=e.getAttribute("data-ml-ui-theme");if(i==="light"||i==="dark")return i;e=e.parentElement}const t=document.documentElement.getAttribute("data-ml-ui-theme");return t==="light"||t==="dark"?t:document.documentElement.classList.contains("dark")?"dark":"light"}const vl=600,kl=`(max-width: ${vl}px)`;function xm(){var s;return((s=window.matchMedia)==null?void 0:s.call(window,kl).matches)??!1}const xl=960,Sl=`(max-width: ${xl}px)`;function Sm(){var s;return((s=window.matchMedia)==null?void 0:s.call(window,Sl).matches)??!1}const Pm={isDebug:!1,isShowCommandLine:!0,isShowCoordinate:!0,isShowEntityInfo:!1,isShowFileName:!0,isShowLanguageSelector:!0,isShowRibbon:!0,isShowToolbar:!0,isShowStats:!1,fontMapping:{},osnapModes:d.acdbOsnapModesToMask([d.AcDbOsnapMode.EndPoint,d.AcDbOsnapMode.MidPoint,d.AcDbOsnapMode.Center,d.AcDbOsnapMode.Quadrant,d.AcDbOsnapMode.Intersection,d.AcDbOsnapMode.Nearest])},xr="settings";function Pl(s){const e={...s};let t=!1;return!("isShowRibbon"in e)&&typeof e.isShowMainMenu=="boolean"&&(e.isShowRibbon=e.isShowMainMenu,t=!0),"isShowMainMenu"in e&&(delete e.isShowMainMenu,t=!0),{settings:e,migrated:t}}class ue{constructor(){this.events={modified:new d.AcCmEventManager}}static get instance(){return this._instance||(this._instance=new ue),this._instance}set(e,t){const i=this.settings;i[e]=t,localStorage.setItem(xr,JSON.stringify(i)),this.events.modified.dispatch({key:e,value:t})}get(e){return this.settings[e]}toggle(e){const t=this.get(e);this.set(e,!t)}get isDebug(){return this.get("isDebug")}set isDebug(e){this.set("isDebug",e)}get isShowCommandLine(){return this.get("isShowCommandLine")}set isShowCommandLine(e){this.set("isShowCommandLine",e)}get isShowCoordinate(){return this.get("isShowCoordinate")}set isShowCoordinate(e){this.set("isShowCoordinate",e)}get isShowEntityInfo(){return this.get("isShowEntityInfo")}set isShowEntityInfo(e){this.set("isShowEntityInfo",e)}get isShowFileName(){return this.get("isShowFileName")}set isShowFileName(e){this.set("isShowFileName",e)}get isShowLanguageSelector(){return this.get("isShowLanguageSelector")}set isShowLanguageSelector(e){this.set("isShowLanguageSelector",e)}get isShowRibbon(){return this.get("isShowRibbon")}set isShowRibbon(e){this.set("isShowRibbon",e)}get isShowToolbar(){return this.get("isShowToolbar")}set isShowToolbar(e){this.set("isShowToolbar",e)}get isShowStats(){return this.get("isShowStats")}set isShowStats(e){this.set("isShowStats",e)}get fontMapping(){return this.get("fontMapping")}set fontMapping(e){this.set("fontMapping",e)}setFontMapping(e,t){const i=this.get("fontMapping");i[e]=t,this.set("fontMapping",i)}get osnapModes(){return this.get("osnapModes")}set osnapModes(e){this.set("osnapModes",e)}get settings(){const e=localStorage.getItem(xr),t=e==null?{}:JSON.parse(e),{settings:i,migrated:n}=Pl(t),r=Ko.defaults(i,Pm);return n&&localStorage.setItem(xr,JSON.stringify(r)),r}}const Am=1e-10;function Ln(s,e,t,i){return Math.hypot(s-t,e-i)}function Cm(s,e,t,i,n,r){const o=n-t,a=r-i,l=o*o+a*a;if(l<1e-18)return Ln(s,e,t,i);let c=((s-t)*o+(e-i)*a)/l;return c=Math.max(0,Math.min(1,c)),Ln(s,e,t+c*o,i+c*a)}function _m(s,e,t){if(Math.abs(t)>Am)try{const i=new d.AcGeCircArc2d(s,e,t);return!(i.radius>0)||!Number.isFinite(i.radius)?void 0:i}catch{return}}function Ht(s){return{x:s.x,y:s.y,z:s.z??0}}function Em(s,e){const t=new d.AcGePoint3d(s.x,s.y,s.z).applyMatrix4(e);return Ht(t)}function Tn(s){return typeof s!="string"?s:s.replace(/#\d+$/,"")}function Lm(s){var i;if(s instanceof d.AcDb2dPolyline){const n=s.numberOfVertices;return Array.from({length:n},(r,o)=>{const a=s.getPointAt(o);return{x:a.x,y:a.y,bulge:s.getBulgeAt(o)}})}const e=(i=s._geo)==null?void 0:i.vertices;if(e&&e.length>0)return e.map(n=>({x:n.x,y:n.y,bulge:n.bulge??0}));const t=s.numberOfVertices;return Array.from({length:t},(n,r)=>{const o=s.getPoint2dAt(r);return{x:o.x,y:o.y,bulge:0}})}function Tm(s,e){const t=Lm(s);if(t.length<2)return;const i=s.closed?t.length:t.length-1;let n=Number.POSITIVE_INFINITY,r;for(let o=0;o<i;o++){const a=t[o],l=t[(o+1)%t.length],c=_m(a,l,a.bulge),h=c?Ln(e.x,e.y,c.nearestPoint(e).x,c.nearestPoint(e).y):Cm(e.x,e.y,a.x,a.y,l.x,l.y);h<n&&(n=h,r=c)}if(r)return Ht({x:r.center.x,y:r.center.y,z:s.elevation})}function Sr(s,e,t){const i=[];return s.subGetOsnapPoints(d.AcDbOsnapMode.Center,e,e,i,t),i.map(n=>Ht(n))}function Al(s,e,t){const i=s.blockTableRecord;if(!i)return;const n=new d.AcGeMatrix3d().multiplyMatrices(t,s.blockTransform),r=Tn(e);for(const o of i.newIterator()){if(o.objectId===e||o.objectId===r)return{entity:o,transform:n};if(o instanceof d.AcDbBlockReference){const a=Al(o,e,n);if(a)return a}}}function Im(s,e,t){if(!t)return Sr(s,e);const i=Al(s,t,new d.AcGeMatrix3d);if(!i)return Sr(s,e,Tn(t));const n=i.transform.clone().invert(),r=new d.AcGePoint3d(e).applyMatrix4(n);return Pr(i.entity,r).map(o=>Em(o,i.transform))}function Pr(s,e,t){if(s instanceof d.AcDbBlockReference)return Im(s,e,t);if(s instanceof d.AcDbCircle)return[Ht(s.center)];if(s instanceof d.AcDbArc)return[Ht(s.center)];if(s instanceof d.AcDbEllipse)return[Ht(s.center)];if(s instanceof d.AcDbPolyline||s instanceof d.AcDb2dPolyline){const i=Tm(s,e);return i?[i]:[]}return Sr(s,e,t)}function Mm(s,e){const t=[...s];for(const i of e)t.some(n=>Cl(n,i))||t.push(i);return t}function Cl(s,e,t=1e-8){return Ln(s.x,s.y,e.x,e.y)<=t}const Dm=20,Om=48;class ft{constructor(e){this._acquiredCenters=[],this._view=e}get acquiredCenterMarks(){return this._acquiredCenters}clearAcquiredCenters(){this._acquiredCenters=[]}static displayCenterMarks(e,t){return!t||t.type!==d.AcDbOsnapMode.Center?[...e]:e.filter(i=>!Cl(i,t))}resolve(e){const t=e.hitRadiusPx??Dm,i=e.lastPoint??e.cursorWcs,n=this._view.screenToWorld({x:0,y:0}),o=this._view.screenToWorld({x:t,y:0}).x-n.x,a=this.collectOsnapPoints(e.cursorWcs,i,t);for(const p of this._acquiredCenters)a.push({x:p.x,y:p.y,z:p.z,type:d.AcDbOsnapMode.Center});if(a.length===0)return;let l=Number.MAX_VALUE,c=Number.MAX_VALUE,h=-1;for(let p=0;p<a.length;p++){const m=a[p],g=e.cursorWcs.x-m.x,f=e.cursorWcs.y-m.y,w=Math.hypot(g,f);if(w>=o)continue;const v=ft.osnapModePriority(m.type);(v<l||v===l&&w<c)&&(l=v,c=w,h=p)}return h!==-1?a[h]:void 0}static osnapModeToMarkerType(e){switch(e){case d.AcDbOsnapMode.EndPoint:return"rect";case d.AcDbOsnapMode.MidPoint:return"triangle";case d.AcDbOsnapMode.Center:return"circle";case d.AcDbOsnapMode.Quadrant:return"diamond";case d.AcDbOsnapMode.Nearest:return"x";case d.AcDbOsnapMode.Intersection:return"intersection";default:return"rect"}}static osnapModePriority(e){switch(e){case d.AcDbOsnapMode.EndPoint:case d.AcDbOsnapMode.MidPoint:case d.AcDbOsnapMode.Center:case d.AcDbOsnapMode.Intersection:return 0;case d.AcDbOsnapMode.Quadrant:return 1;case d.AcDbOsnapMode.Nearest:return 2;default:return 1}}collectOsnapPointsByMode(e,t,i,n,r,o){const a=i.length;e.subGetOsnapPoints(t,n,r,i,o);for(let l=a;l<i.length;l++)i[l].type=t}collectOsnapPointsInAvailableModes(e,t,i,n,r){d.acdbMaskToOsnapModes(ue.instance.osnapModes).forEach(a=>{a!==d.AcDbOsnapMode.Intersection&&this.collectOsnapPointsByMode(e,a,t,i,n,r)})}collectIntersectionOsnapPoints(e,t){const i=e.slice(0,Om);for(let n=0;n<i.length;n++)for(let r=n;r<i.length;r++){const o=i[n].intersectWith(i[r]);for(const a of o)t.push({x:a.x,y:a.y,z:a.z,type:d.AcDbOsnapMode.Intersection})}}collectOsnapPoints(e,t,i){const n=this._view.pick(e,i),o=d.acdbHostApplicationServices().workingDatabase.tables.blockTable.modelSpace,a=[],l=d.AcGeGeometryUtil.point2dToPoint3d(e),c=d.AcGeGeometryUtil.point2dToPoint3d(t),h=[],p=new Set;return n.forEach(m=>{const g=o.getIdAt(m.id);g&&(p.has(m.id)||(p.add(m.id),h.push(g)),m.children&&m.children.length>0?m.children.forEach(f=>this.collectOsnapPointsInAvailableModes(g,a,l,c,Tn(f.id))):this.collectOsnapPointsInAvailableModes(g,a,l,c))}),d.acdbHasOsnapMode(ue.instance.osnapModes,d.AcDbOsnapMode.Intersection)&&this.collectIntersectionOsnapPoints(h,a),this.updateAcquiredCenters(n,o,l),a}updateAcquiredCenters(e,t,i){if(!d.acdbHasOsnapMode(ue.instance.osnapModes,d.AcDbOsnapMode.Center)){this._acquiredCenters=[];return}const n=[];e.forEach(r=>{const o=t.getIdAt(r.id);o&&(r.children&&r.children.length>0?r.children.forEach(a=>{n.push(...Pr(o,i,Tn(a.id)))}):n.push(...Pr(o,i)))}),this._acquiredCenters=Mm(this._acquiredCenters,n)}}class In{constructor(e="rect",t=12,i="var(--ml-ui-canvas-line, green)",n){this._type=e,this._size=t,this._color=i,this._host=n,In.injectCSS(),getComputedStyle(this._host).position==="static"&&(this._host.style.position="relative"),this._el=document.createElement("div"),this._el.classList.add("ml-marker"),this._el.style.color=i,this.applyShape(),this._host.appendChild(this._el)}get color(){return this._color}set color(e){this._color=e,this._el.style.color=e}get type(){return this._type}set type(e){this._type=e,this.applyShape()}static injectCSS(){if(document.getElementById("ml-marker-style"))return;const e=document.createElement("style");e.id="ml-marker-style",e.textContent=`
136
139
  .ml-marker {
137
140
  position: absolute;
138
141
  pointer-events: none;
@@ -184,7 +187,54 @@
184
187
  .ml-marker-x::after {
185
188
  transform: translate(-50%, -50%) rotate(-45deg);
186
189
  }
187
- `,document.head.appendChild(e)}applyShape(){switch(this._el.className="ml-marker",this._el.style.width="",this._el.style.height="",this._el.style.fontSize="",this._el.style.transform="translate(-50%, -50%)",this._type){case"circle":this._el.classList.add("ml-marker-circle"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"rect":this._el.classList.add("ml-marker-rect"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"triangle":this._el.classList.add("ml-marker-triangle"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"diamond":this._el.classList.add("ml-marker-diamond"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"x":this._el.classList.add("ml-marker-x"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break}}setPosition(e){this._el.style.left=`${e.x}px`,this._el.style.top=`${e.y}px`}destroy(){this._el.remove()}}class br{constructor(e){this.stack=[],this.view=e}showMarker(e,t,i,n){const r=this.view.worldToScreen(e),o=this.view.canvasToContainer(r),a=new _n(t,i,n,this.view.container);return a.setPosition(o),this.stack.push(a),a}repositionTop(e){const t=this.top();if(!t)return;const i=this.view.worldToScreen(e),n=this.view.canvasToContainer(i);t.setPosition(n)}hideMarker(){const e=this.stack.pop();e&&e.destroy()}clear(){for(const e of this.stack)e.destroy();this.stack=[]}top(){return this.stack[this.stack.length-1]}}class G{constructor(e){this.view=e}get entity(){return null}render(){this.entity&&this.view.addTransientEntity(this.entity)}end(){this.entity&&this.view.removeTransientEntity(this.entity.objectId)}}class fl extends G{constructor(e,t,i,n){super(e),this._previewEntity=null,this._view=e;const r=t.clone();if(!r)throw new Error("Failed to clone entity for grip preview.");this._sourceClone=r,this._gripIndex=i,this._gripBaseWcs=new u.AcGePoint3d(n)}get entity(){return this._previewEntity}update(e){this._previewEntity&&(this._view.removeTransientEntity(this._previewEntity.objectId),this._previewEntity=null);const t=this._sourceClone.clone();t&&(t.subMoveGripPointsAt([this._gripIndex],this.computeOffset(e)),this._previewEntity=t)}computeOffset(e){return new u.AcGeVector3d(e.x-this._gripBaseWcs.x,e.y-this._gripBaseWcs.y,(e.z??0)-(this._gripBaseWcs.z??0))}render(){this._previewEntity&&this._view.addTransientEntity(this._previewEntity)}end(){this._previewEntity&&(this._view.removeTransientEntity(this._previewEntity.objectId),this._previewEntity=null)}}class bl{constructor(e,t,i,n){this._boundMouseMove=r=>this.onMouseMove(r),this._boundMouseUp=r=>this.onMouseUp(r),this._boundKeyDown=r=>this.onKeyDown(r),this._view=e,this._entity=t,this._target=i,this._onEnd=n,this._osnapMarkerManager=new br(e),this._jig=new fl(e,t,i.gripIndex,i.gripBaseWcs),document.addEventListener("mousemove",this._boundMouseMove),document.addEventListener("mouseup",this._boundMouseUp),document.addEventListener("keydown",this._boundKeyDown)}onMouseMove(e){const t=this.resolveWcs(e);this._jig.update(t),this._jig.render()}onMouseUp(e){if(e.button!==0)return;const t=this.resolveWcs(e),i=this._jig.computeOffset(t),n=this._entity.database;ct(n,"Grip Edit",()=>{const r=n.openEntityForWrite(this._entity);r&&r.subMoveGripPointsAt([this._target.gripIndex],i)}),this.finish()}onKeyDown(e){e.key==="Escape"&&(e.preventDefault(),this.cancel())}cancel(){this.finish()}finish(){this._jig.end(),this._osnapMarkerManager.clear(),document.removeEventListener("mousemove",this._boundMouseMove),document.removeEventListener("mouseup",this._boundMouseUp),document.removeEventListener("keydown",this._boundKeyDown),this._onEnd()}resolveWcs(e){const t=this._view.viewportToCanvas({x:e.clientX,y:e.clientY}),i=this._view.screenToWorld(t),n={x:i.x,y:i.y,z:0};this._osnapMarkerManager.hideMarker();const r=this._view.osnapResolver.resolve({cursorWcs:n,lastPoint:this._target.gripBaseWcs});return r?(this._osnapMarkerManager.showMarker(r,Ut.osnapModeToMarkerType(r.type)),{x:r.x,y:r.y,z:r.z??0}):n}}class En{constructor(e,t){this._host=e,this._state="normal",En.injectCSS(),getComputedStyle(this._host).position==="static"&&(this._host.style.position="relative"),this._el=document.createElement("div"),this._el.className="ml-grip-handle ml-grip-handle-normal",this.applyAppearance(t),this._host.appendChild(this._el)}get element(){return this._el}get state(){return this._state}setState(e){this._state!==e&&(this._state=e,this._el.className=`ml-grip-handle ml-grip-handle-${e}`)}setPosition(e){this._el.style.left=`${e.x}px`,this._el.style.top=`${e.y}px`}applyAppearance(e){this._el.style.width=`${e.size}px`,this._el.style.height=`${e.size}px`,this._el.style.setProperty("--ml-ui-grip-normal",e.colorCss),this._el.style.setProperty("--ml-ui-grip-hot",e.hotColorCss)}destroy(){this._el.remove()}static injectCSS(){if(document.getElementById("ml-grip-handle-style"))return;const e=document.createElement("style");e.id="ml-grip-handle-style",e.textContent=`
190
+
191
+ .ml-marker-plus::before,
192
+ .ml-marker-plus::after {
193
+ content: '';
194
+ position: absolute;
195
+ top: 50%;
196
+ left: 50%;
197
+ background: currentColor;
198
+ transform-origin: center;
199
+ }
200
+
201
+ .ml-marker-plus::before {
202
+ width: 100%;
203
+ height: 2px;
204
+ transform: translate(-50%, -50%);
205
+ }
206
+
207
+ .ml-marker-plus::after {
208
+ width: 2px;
209
+ height: 100%;
210
+ transform: translate(-50%, -50%);
211
+ }
212
+
213
+ .ml-marker-intersection {
214
+ border: 2px solid currentColor;
215
+ background: transparent;
216
+ }
217
+
218
+ .ml-marker-intersection::before,
219
+ .ml-marker-intersection::after {
220
+ content: '';
221
+ position: absolute;
222
+ top: 50%;
223
+ left: 50%;
224
+ width: 70%;
225
+ height: 2px;
226
+ background: currentColor;
227
+ transform-origin: center;
228
+ }
229
+
230
+ .ml-marker-intersection::before {
231
+ transform: translate(-50%, -50%) rotate(45deg);
232
+ }
233
+
234
+ .ml-marker-intersection::after {
235
+ transform: translate(-50%, -50%) rotate(-45deg);
236
+ }
237
+ `,document.head.appendChild(e)}applyShape(){switch(this._el.className="ml-marker",this._el.style.width="",this._el.style.height="",this._el.style.fontSize="",this._el.style.transform="translate(-50%, -50%)",this._type){case"circle":this._el.classList.add("ml-marker-circle"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"rect":this._el.classList.add("ml-marker-rect"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"triangle":this._el.classList.add("ml-marker-triangle"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"diamond":this._el.classList.add("ml-marker-diamond"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"x":this._el.classList.add("ml-marker-x"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"plus":this._el.classList.add("ml-marker-plus"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"intersection":this._el.classList.add("ml-marker-intersection"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break}}setPosition(e){this._el.style.left=`${e.x}px`,this._el.style.top=`${e.y}px`}destroy(){this._el.remove()}}class Ar{constructor(e){this.stack=[],this.hintMarkers=[],this.hintPositions=[],this.view=e}showMarker(e,t,i,n){const r=this.createMarker(e,t,i,n);return this.stack.push(r),r}setHintMarkers(e,t="plus",i,n){this.clearHintMarkers(),this.hintPositions=e.map(r=>({x:r.x,y:r.y}));for(const r of this.hintPositions)this.hintMarkers.push(this.createMarker(r,t,i,n))}repositionHints(){for(let e=0;e<this.hintMarkers.length;e++){const t=this.hintPositions[e];t&&this.hintMarkers[e].setPosition(this.toContainerPos(t))}}repositionTop(e){const t=this.top();if(!t)return;const i=this.view.worldToScreen(e),n=this.view.canvasToContainer(i);t.setPosition(n)}hideMarker(){const e=this.stack.pop();e&&e.destroy()}clear(){this.clearHintMarkers();for(const e of this.stack)e.destroy();this.stack=[]}top(){return this.stack[this.stack.length-1]}createMarker(e,t,i,n){const r=new In(t,i,n,this.view.container);return r.setPosition(this.toContainerPos(e)),r}toContainerPos(e){const t=this.view.worldToScreen(e);return this.view.canvasToContainer(t)}clearHintMarkers(){for(const e of this.hintMarkers)e.destroy();this.hintMarkers=[],this.hintPositions=[]}}class R{constructor(e){this.view=e}get entity(){return null}render(){this.entity&&this.view.addTransientEntity(this.entity)}end(){this.entity&&this.view.removeTransientEntity(this.entity.objectId)}}class _l extends R{constructor(e,t,i,n){super(e),this._previewEntity=null,this._view=e;const r=t.clone();if(!r)throw new Error("Failed to clone entity for grip preview.");this._sourceClone=r,this._gripIndex=i,this._gripBaseWcs=new d.AcGePoint3d(n)}get entity(){return this._previewEntity}update(e){this._previewEntity&&(this._view.removeTransientEntity(this._previewEntity.objectId),this._previewEntity=null);const t=this._sourceClone.clone();t&&(t.subMoveGripPointsAt([this._gripIndex],this.computeOffset(e)),this._previewEntity=t)}computeOffset(e){return new d.AcGeVector3d(e.x-this._gripBaseWcs.x,e.y-this._gripBaseWcs.y,(e.z??0)-(this._gripBaseWcs.z??0))}render(){this._previewEntity&&this._view.addTransientEntity(this._previewEntity)}end(){this._previewEntity&&(this._view.removeTransientEntity(this._previewEntity.objectId),this._previewEntity=null)}}class El{constructor(e,t,i,n){this._boundMouseMove=r=>this.onMouseMove(r),this._boundMouseUp=r=>this.onMouseUp(r),this._boundKeyDown=r=>this.onKeyDown(r),this._view=e,this._entity=t,this._target=i,this._onEnd=n,this._osnapMarkerManager=new Ar(e),this._jig=new _l(e,t,i.gripIndex,i.gripBaseWcs),document.addEventListener("mousemove",this._boundMouseMove),document.addEventListener("mouseup",this._boundMouseUp),document.addEventListener("keydown",this._boundKeyDown)}onMouseMove(e){const t=this.resolveWcs(e);this._jig.update(t),this._jig.render()}onMouseUp(e){if(e.button!==0)return;const t=this.resolveWcs(e),i=this._jig.computeOffset(t),n=this._entity.database;pt(n,"Grip Edit",()=>{const r=n.openEntityForWrite(this._entity);r&&r.subMoveGripPointsAt([this._target.gripIndex],i)}),this.finish()}onKeyDown(e){e.key==="Escape"&&(e.preventDefault(),this.cancel())}cancel(){this.finish()}finish(){this._jig.end(),this._osnapMarkerManager.clear(),this._view.osnapResolver.clearAcquiredCenters(),document.removeEventListener("mousemove",this._boundMouseMove),document.removeEventListener("mouseup",this._boundMouseUp),document.removeEventListener("keydown",this._boundKeyDown),this._onEnd()}resolveWcs(e){const t=this._view.viewportToCanvas({x:e.clientX,y:e.clientY}),i=this._view.screenToWorld(t),n={x:i.x,y:i.y,z:0};this._osnapMarkerManager.hideMarker();const r=this._view.osnapResolver.resolve({cursorWcs:n,lastPoint:this._target.gripBaseWcs});return this._osnapMarkerManager.setHintMarkers(ft.displayCenterMarks(this._view.osnapResolver.acquiredCenterMarks,r)),r?(this._osnapMarkerManager.showMarker(r,ft.osnapModeToMarkerType(r.type)),{x:r.x,y:r.y,z:r.z??0}):n}}class Mn{constructor(e,t){this._host=e,this._state="normal",Mn.injectCSS(),getComputedStyle(this._host).position==="static"&&(this._host.style.position="relative"),this._el=document.createElement("div"),this._el.className="ml-grip-handle ml-grip-handle-normal",this.applyAppearance(t),this._host.appendChild(this._el)}get element(){return this._el}get state(){return this._state}setState(e){this._state!==e&&(this._state=e,this._el.className=`ml-grip-handle ml-grip-handle-${e}`)}setPosition(e){this._el.style.left=`${e.x}px`,this._el.style.top=`${e.y}px`}applyAppearance(e){this._el.style.width=`${e.size}px`,this._el.style.height=`${e.size}px`,this._el.style.setProperty("--ml-ui-grip-normal",e.colorCss),this._el.style.setProperty("--ml-ui-grip-hot",e.hotColorCss)}destroy(){this._el.remove()}static injectCSS(){if(document.getElementById("ml-grip-handle-style"))return;const e=document.createElement("style");e.id="ml-grip-handle-style",e.textContent=`
188
238
  .ml-grip-handle {
189
239
  position: absolute;
190
240
  pointer-events: auto;
@@ -202,7 +252,7 @@
202
252
  .ml-grip-handle-hot {
203
253
  background: var(--ml-ui-grip-hot, #ff0000);
204
254
  }
205
- `,document.head.appendChild(e)}}function wl(s){const e=new u.AcCmColor(u.AcCmColorMethod.ByACI,s);return e.cssColor??`rgb(${e.red}, ${e.green}, ${e.blue})`}function vl(s){const e=u.AcDbSysVarManager.instance(),t=e.getVar(u.AcDbSystemVariables.GRIPSIZE,s),i=e.getVar(u.AcDbSystemVariables.GRIPCOLOR,s),n=e.getVar(u.AcDbSystemVariables.GRIPHOT,s);return{size:t,colorCss:wl(i),hotColorCss:wl(n)}}const hm=new Set([u.AcDbSystemVariables.GRIPSIZE.toLowerCase(),u.AcDbSystemVariables.GRIPCOLOR.toLowerCase(),u.AcDbSystemVariables.GRIPHOT.toLowerCase()]);function pm(s){return hm.has(s.toLowerCase())}function mm(s,e){return e<=0?!1:s>e}function ym(s,e,t,i,n){return s!==F.Write||e||t?!1:!mm(i,n)}class kl{constructor(e){this._entries=[],this._editSession=null,this._hotEntry=null,this._boundRefresh=()=>this.refresh(),this._boundReposition=()=>this.repositionAll(),this._boundSysVarChanged=t=>this.onGripSysVarChanged(t.name),this._view=e,this.bindEvents()}get isDragging(){return this._editSession!=null}dispose(){this.unbindEvents(),this.clear()}refresh(){if(this.clearEntries(),!this.canShowGrips())return;const e=k.instance.curDocument,t=e.database.tables.blockTable,i=vl(e.database);for(const n of this._view.selectionSet.ids){const r=t.getEntityById(n);if(!r)continue;const o=r.subGetGripPoints();for(let a=0;a<o.length;++a){const l=o[a],c=new En(this._view.container,i),h={entityId:n,gripIndex:a,wcsPoint:l,handle:c};this.wireHandleEvents(h),this._entries.push(h),this.positionEntry(h)}}}canShowGrips(){const e=k.instance.curDocument,t=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.GRIPOBJLIMIT,e.database);return ym(e.openMode,this._view.editor.isActive,!!Ke.getActiveInputBox(),this._view.selectionSet.count,t)}bindEvents(){const{selectionSet:e,editor:t,events:i}=this._view;e.events.selectionAdded.addEventListener(this._boundRefresh),e.events.selectionRemoved.addEventListener(this._boundRefresh),i.viewChanged.addEventListener(this._boundReposition),i.viewResize.addEventListener(this._boundReposition),t.events.commandWillStart.addEventListener(this._boundRefresh),t.events.commandEnded.addEventListener(this._boundRefresh),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this._boundSysVarChanged)}unbindEvents(){const{selectionSet:e,editor:t,events:i}=this._view;e.events.selectionAdded.removeEventListener(this._boundRefresh),e.events.selectionRemoved.removeEventListener(this._boundRefresh),i.viewChanged.removeEventListener(this._boundReposition),i.viewResize.removeEventListener(this._boundReposition),t.events.commandWillStart.removeEventListener(this._boundRefresh),t.events.commandEnded.removeEventListener(this._boundRefresh),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this._boundSysVarChanged)}onGripSysVarChanged(e){const t=e.toLowerCase();if(t===u.AcDbSystemVariables.GRIPOBJLIMIT.toLowerCase()){this.refresh();return}pm(t)&&this.applyAppearance()}applyAppearance(){if(this._entries.length===0)return;const e=vl(k.instance.curDocument.database);for(const t of this._entries)t.handle.applyAppearance(e)}wireHandleEvents(e){const{element:t}=e.handle;t.addEventListener("mouseenter",()=>{this.isDragging||e.handle.setState("hover")}),t.addEventListener("mouseleave",()=>{this._hotEntry!==e&&e.handle.setState("normal")}),t.addEventListener("mousedown",i=>{i.button===0&&this.canShowGrips()&&(i.preventDefault(),i.stopPropagation(),this._hotEntry=e,e.handle.setState("hot"),this.startEdit(e))})}startEdit(e){const t=k.instance.curDocument.database.tables.blockTable.getEntityById(e.entityId);if(!t){this.endEdit();return}this.hideEntriesForDrag();const i={entityId:e.entityId,gripIndex:e.gripIndex,gripBaseWcs:e.wcsPoint};this._editSession=new bl(this._view,t,i,()=>this.endEdit())}endEdit(){this._editSession=null,this._hotEntry=null,this.refresh()}hideEntriesForDrag(){this.clearEntries()}positionEntry(e){const t=this._view.worldToScreen(e.wcsPoint),i=this._view.canvasToContainer(t);e.handle.setPosition(i)}repositionAll(){for(const e of this._entries)this.positionEntry(e)}clearEntries(){for(const e of this._entries)e.handle.destroy();this._entries.length=0,this._hotEntry=null}clear(){var e;(e=this._editSession)==null||e.cancel(),this._editSession=null,this.clearEntries()}}var Ce=(s=>(s[s.NoSpecialCursor=-1]="NoSpecialCursor",s[s.Crosshair=0]="Crosshair",s[s.RectCursor=1]="RectCursor",s[s.RubberBand=2]="RubberBand",s[s.NotRotated=3]="NotRotated",s[s.TargetBox=4]="TargetBox",s[s.RotatedCrosshair=5]="RotatedCrosshair",s[s.CrosshairNoRotate=6]="CrosshairNoRotate",s[s.Invisible=7]="Invisible",s[s.EntitySelect=8]="EntitySelect",s[s.Parallelogram=9]="Parallelogram",s[s.EntitySelectNoPersp=10]="EntitySelectNoPersp",s[s.PkfirstOrGrips=11]="PkfirstOrGrips",s[s.CrosshairDashed=12]="CrosshairDashed",s[s.Grab=13]="Grab",s))(Ce||{});class xl{constructor(e){this._backgroundColor=u.ACGI_MODEL_SPACE_BACKGROUND,this._totalLength=20,this._view=e,this._cursorMap=new Map,this.setCursorColor(bn(this._backgroundColor)),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(t=>{if(t.name===u.AcDbSystemVariables.PICKBOX.toLowerCase()){let i=t.newVal;i=i>=0?i:0,this._cursorMap.set(0,this.createRectCrossIcon(i,this._totalLength-i,bn(this._backgroundColor))),this.setCursor(this._currentCursor)}}),this.setCursor(0)}get currentCursor(){return this._currentCursor}setCursor(e){const t=this._view.canvas;if(e<=-1)t.style.cursor="default";else if(e==13)t.style.cursor="grab";else{const i=this._cursorMap.get(e);i&&(t.style.cursor=i)}this._currentCursor=e}syncBackgroundColor(e){this._backgroundColor=e,this.setCursorColor(bn(e))}setCursorColor(e){const i=this.createRectCrossIcon(10,this._totalLength-10,e);this._cursorMap.set(0,i),this._currentCursor===0&&(this._view.canvas.style.cursor=i)}encodeSvgToCursor(e,t,i){return`url('data:image/svg+xml;base64,${btoa(e)}') ${t} ${i}, auto`}createRectCrossIcon(e,t,i="white"){const n=e/2,r=e+2*t,o=`
255
+ `,document.head.appendChild(e)}}function Ll(s){const e=new d.AcCmColor(d.AcCmColorMethod.ByACI,s);return e.cssColor??`rgb(${e.red}, ${e.green}, ${e.blue})`}function Tl(s){const e=d.AcDbSysVarManager.instance(),t=e.getVar(d.AcDbSystemVariables.GRIPSIZE,s),i=e.getVar(d.AcDbSystemVariables.GRIPCOLOR,s),n=e.getVar(d.AcDbSystemVariables.GRIPHOT,s);return{size:t,colorCss:Ll(i),hotColorCss:Ll(n)}}const Bm=new Set([d.AcDbSystemVariables.GRIPSIZE.toLowerCase(),d.AcDbSystemVariables.GRIPCOLOR.toLowerCase(),d.AcDbSystemVariables.GRIPHOT.toLowerCase()]);function jm(s){return Bm.has(s.toLowerCase())}function Fm(s,e){return e<=0?!1:s>e}function zm(s,e,t,i,n){return s!==F.Write||e||t?!1:!Fm(i,n)}class Il{constructor(e){this._entries=[],this._editSession=null,this._hotEntry=null,this._boundRefresh=()=>this.refresh(),this._boundReposition=()=>this.repositionAll(),this._boundSysVarChanged=t=>this.onGripSysVarChanged(t.name),this._view=e,this.bindEvents()}get isDragging(){return this._editSession!=null}dispose(){this.unbindEvents(),this.clear()}refresh(){if(this.clearEntries(),!this.canShowGrips())return;const e=k.instance.curDocument,t=e.database.tables.blockTable,i=Tl(e.database);for(const n of this._view.selectionSet.ids){const r=t.getEntityById(n);if(!r)continue;const o=r.subGetGripPoints();for(let a=0;a<o.length;++a){const l=o[a],c=new Mn(this._view.container,i),h={entityId:n,gripIndex:a,wcsPoint:l,handle:c};this.wireHandleEvents(h),this._entries.push(h),this.positionEntry(h)}}}canShowGrips(){const e=k.instance.curDocument,t=d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.GRIPOBJLIMIT,e.database);return zm(e.openMode,this._view.editor.isActive,!!He.getActiveInputBox(),this._view.selectionSet.count,t)}bindEvents(){const{selectionSet:e,editor:t,events:i}=this._view;e.events.selectionAdded.addEventListener(this._boundRefresh),e.events.selectionRemoved.addEventListener(this._boundRefresh),i.viewChanged.addEventListener(this._boundReposition),i.viewResize.addEventListener(this._boundReposition),t.events.commandWillStart.addEventListener(this._boundRefresh),t.events.commandEnded.addEventListener(this._boundRefresh),d.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this._boundSysVarChanged)}unbindEvents(){const{selectionSet:e,editor:t,events:i}=this._view;e.events.selectionAdded.removeEventListener(this._boundRefresh),e.events.selectionRemoved.removeEventListener(this._boundRefresh),i.viewChanged.removeEventListener(this._boundReposition),i.viewResize.removeEventListener(this._boundReposition),t.events.commandWillStart.removeEventListener(this._boundRefresh),t.events.commandEnded.removeEventListener(this._boundRefresh),d.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this._boundSysVarChanged)}onGripSysVarChanged(e){const t=e.toLowerCase();if(t===d.AcDbSystemVariables.GRIPOBJLIMIT.toLowerCase()){this.refresh();return}jm(t)&&this.applyAppearance()}applyAppearance(){if(this._entries.length===0)return;const e=Tl(k.instance.curDocument.database);for(const t of this._entries)t.handle.applyAppearance(e)}wireHandleEvents(e){const{element:t}=e.handle;t.addEventListener("mouseenter",()=>{this.isDragging||e.handle.setState("hover")}),t.addEventListener("mouseleave",()=>{this._hotEntry!==e&&e.handle.setState("normal")}),t.addEventListener("mousedown",i=>{i.button===0&&this.canShowGrips()&&(i.preventDefault(),i.stopPropagation(),this._hotEntry=e,e.handle.setState("hot"),this.startEdit(e))})}startEdit(e){const t=k.instance.curDocument.database.tables.blockTable.getEntityById(e.entityId);if(!t){this.endEdit();return}this.hideEntriesForDrag();const i={entityId:e.entityId,gripIndex:e.gripIndex,gripBaseWcs:e.wcsPoint};this._editSession=new El(this._view,t,i,()=>this.endEdit())}endEdit(){this._editSession=null,this._hotEntry=null,this.refresh()}hideEntriesForDrag(){this.clearEntries()}positionEntry(e){const t=this._view.worldToScreen(e.wcsPoint),i=this._view.canvasToContainer(t);e.handle.setPosition(i)}repositionAll(){for(const e of this._entries)this.positionEntry(e)}clearEntries(){for(const e of this._entries)e.handle.destroy();this._entries.length=0,this._hotEntry=null}clear(){var e;(e=this._editSession)==null||e.cancel(),this._editSession=null,this.clearEntries()}}var Le=(s=>(s[s.NoSpecialCursor=-1]="NoSpecialCursor",s[s.Crosshair=0]="Crosshair",s[s.RectCursor=1]="RectCursor",s[s.RubberBand=2]="RubberBand",s[s.NotRotated=3]="NotRotated",s[s.TargetBox=4]="TargetBox",s[s.RotatedCrosshair=5]="RotatedCrosshair",s[s.CrosshairNoRotate=6]="CrosshairNoRotate",s[s.Invisible=7]="Invisible",s[s.EntitySelect=8]="EntitySelect",s[s.Parallelogram=9]="Parallelogram",s[s.EntitySelectNoPersp=10]="EntitySelectNoPersp",s[s.PkfirstOrGrips=11]="PkfirstOrGrips",s[s.CrosshairDashed=12]="CrosshairDashed",s[s.Grab=13]="Grab",s))(Le||{});class Ml{constructor(e){this._backgroundColor=d.ACGI_MODEL_SPACE_BACKGROUND,this._totalLength=20,this._view=e,this._cursorMap=new Map,this.setCursorColor(wn(this._backgroundColor)),d.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(t=>{if(t.name===d.AcDbSystemVariables.PICKBOX.toLowerCase()){let i=t.newVal;i=i>=0?i:0,this._cursorMap.set(0,this.createRectCrossIcon(i,this._totalLength-i,wn(this._backgroundColor))),this.setCursor(this._currentCursor)}}),this.setCursor(0)}get currentCursor(){return this._currentCursor}setCursor(e){const t=this._view.canvas;if(e<=-1)t.style.cursor="default";else if(e==13)t.style.cursor="grab";else{const i=this._cursorMap.get(e);i&&(t.style.cursor=i)}this._currentCursor=e}syncBackgroundColor(e){this._backgroundColor=e,this.setCursorColor(wn(e))}setCursorColor(e){const i=this.createRectCrossIcon(10,this._totalLength-10,e);this._cursorMap.set(0,i),this._currentCursor===0&&(this._view.canvas.style.cursor=i)}encodeSvgToCursor(e,t,i){return`url('data:image/svg+xml;base64,${btoa(e)}') ${t} ${i}, auto`}createRectCrossIcon(e,t,i="white"){const n=e/2,r=e+2*t,o=`
206
256
  <svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${r}" viewBox="0 0 ${r} ${r}">
207
257
  <rect x="${t}" y="${t}" width="${e}" height="${e}" fill="none" stroke="${i}" />
208
258
  <line x1="${n+t}" y1="0" x2="${n+t}" y2="${t}" stroke="${i}" />
@@ -210,7 +260,7 @@
210
260
  <line x1="${n+t}" y1="${e+t}" x2="${n+t}" y2="${e+2*t}" stroke="${i}" />
211
261
  <line x1="0" y1="${n+t}" x2="${t}" y2="${n+t}" stroke="${i}" />
212
262
  </svg>
213
- `;return this.encodeSvgToCursor(o,n+t,n+t)}}function Sl(s){const e=s??u.acdbHostApplicationServices().workingDatabase,t=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.ORTHOMODE,e);return Number(t)!==0}function Pl(s,e){const t=s.x-e.x,i=s.y-e.y;return Math.abs(t)>=Math.abs(i)?{x:s.x,y:e.y}:{x:e.x,y:s.y}}const Ht=2,Al=4;function vi(s){return s??u.acdbHostApplicationServices().workingDatabase}function Cl(s,e,t){const i=u.AcDbSysVarManager.instance().getVar(s,e),n=Number(i);return Number.isFinite(n)?n:t}function gm(s,e){const t=u.AcDbSysVarManager.instance().getVar(s,e);return t==null?"":String(t)}function Ln(s){const e=vi(s);return Cl(u.AcDbSystemVariables.POLARMODE,e,0)}function _l(s){const e=vi(s);return Cl(u.AcDbSystemVariables.POLARANG,e,90)}function El(s){const e=vi(s);return gm(u.AcDbSystemVariables.POLARADDANG,e)}function Ll(s){return(Ln(s)&Ht)!==0}function fm(s,e,t){let i=s-e;return t===1&&(i=-i),u.AcGeMathUtil.normalizeAngle(i)}function bm(s,e,t){let i=s;return t===1&&(i=-i),u.AcGeMathUtil.normalizeAngle(i+e)}function wm(s){if(!s.trim())return[];const e=[];for(const t of s.split(";")){const i=t.trim();if(!i)continue;const n=Number(i);if(Number.isFinite(n)&&(e.push((n%360+360)%360),e.length>=10))break}return e}function vm(s,e){const t=Ln(s),i=(t&Ht)!==0,n=(t&Al)!==0,r=new Set;if(e.includeOrtho)for(const o of[0,90,180,270])r.add(o);if(i){const o=_l(s);if(o>0){const a=Math.max(1,Math.round(360/o));for(let l=0;l<a;l++)r.add((l*o%360+360)%360)}if(n)for(const a of wm(El(s)))r.add(a)}return[...r].map(u.AcGeMathUtil.degToRad)}function Tl(s,e){const t=Math.abs(u.AcGeMathUtil.normalizeAngle(s-e));return Math.min(t,Math.PI*2-t)}function km(s,e){let t=e[0],i=Tl(s,t);for(let n=1;n<e.length;n++){const r=e[n],o=Tl(s,r);o<i&&(i=o,t=r)}return t}function Il(s,e,t){const i=vi(t),n=Sl(i),r=Ll(i);if(!n&&!r)return s;if(n&&!r)return Pl(s,e);const o=s.x-e.x,a=s.y-e.y,l=Math.hypot(o,a);if(l<1e-10)return s;const c=Math.atan2(a,o),h=fm(c,i.angbase,i.angdir),p=vm(i,{includeOrtho:n});if(p.length===0)return s;const m=km(h,p),g=bm(m,i.angbase,i.angdir);return{x:e.x+l*Math.cos(g),y:e.y+l*Math.sin(g)}}function xm(s){const e=vi(s),t=Ln(e),i=(t&Ht)!==0?t&~Ht:t|Ht;return u.AcDbSysVarManager.instance().setVar(u.AcDbSystemVariables.POLARMODE,i,e),i}class Tn{constructor(e=[]){this.events={selectionAdded:new u.AcCmEventManager,selectionRemoved:new u.AcCmEventManager},this._ids=new Set(e)}get ids(){return Array.from(this._ids)}get count(){return this._ids.size}add(e){Array.isArray(e)?(e.forEach(t=>this._ids.add(t)),this.events.selectionAdded.dispatch({ids:e})):(this._ids.add(e),this.events.selectionAdded.dispatch({ids:[e]}))}delete(e){Array.isArray(e)?(e.forEach(t=>this._ids.delete(t)),this.events.selectionRemoved.dispatch({ids:e})):(this._ids.delete(e),this.events.selectionRemoved.dispatch({ids:[e]}))}has(e){return this._ids.has(e)}clear(){if(this._ids.size>0){const e=Array.from(this._ids);this._ids.clear(),this.events.selectionRemoved.dispatch({ids:e})}}}class wr{constructor(e,t,i,n=!0,r=!1,o=!0){this._displayName=e,this._globalName=t??e,this._localName=i??this._globalName,this._enabled=n,this._isReadOnly=r,this._visible=o}get displayName(){return this._displayName}set displayName(e){this._isReadOnly||(this._displayName=e)}get enabled(){return this._enabled}set enabled(e){this._isReadOnly||(this._enabled=e)}get globalName(){return this._globalName}set globalName(e){this._isReadOnly||(this._globalName=e)}get isReadOnly(){return this._isReadOnly}get localName(){return this._localName}set localName(e){this._isReadOnly||(this._localName=e)}get visible(){return this._visible}set visible(e){this._isReadOnly||(this._visible=e)}get alias(){return this._globalName.replace(/[^A-Z]/g,"")}}class Ml{constructor(e){if(this._keywords=[],!e)return;const t=e.trim().split(/\s+/),i=[],n=[];let r=!1;for(const a of t){if(a==="_"){r=!0;continue}(r?n:i).push(a)}const o=Math.max(i.length,n.length);for(let a=0;a<o;a++){const l=i[a],c=n[a],h=S=>{if(!S)return;const P=S.indexOf(",");return P>=0?S.substring(0,P):S},p=h(c),m=h(l),g=p!==void 0,f=m!==void 0,w=g?p:"",v=f?m:void 0,x=new wr(w||v||"",w,v,!0,!1,!0);this._keywords.push(x)}}add(e,t,i,n=!0,r=!0){let o,a,l;t===void 0?(o=e,a=e,l=e):i===void 0?(o=t,a=e,l=t):(o=e,a=t,l=i);const c=new wr(o,a,l,n,!1,r);return this._keywords.push(c),c}clear(){this._keywords=[],this._defaultKeyword=void 0}toArray(){return this._keywords.slice()}get default(){return this._defaultKeyword}set default(e){if(e&&!this._keywords.includes(e))throw new Error("Default keyword must be one of the collection's keywords");this._defaultKeyword=e}getDisplayString(e=!1){return this._keywords.filter(i=>i.visible&&i.enabled).map(i=>(!e&&this._defaultKeyword===i,i.displayName)).join("/")}getPromptFormat(){const e=this._keywords.filter(r=>r.visible).map(r=>r.displayName),t=this._defaultKeyword&&this._defaultKeyword.visible?this._defaultKeyword.displayName:void 0,i=`[${e.join("/")}]`,n=t?` <${t}>`:"";return{visibleKeywords:e,defaultKeyword:t,formattedTail:`${i}${n}:`}}[Symbol.iterator](){let e=0;const t=this._keywords;return{next(){return e<t.length?{done:!1,value:t[e++]}:{done:!0,value:void 0}}}}findByDisplayName(e){return this._keywords.find(t=>t.displayName.toLowerCase()===e.toLowerCase())}findByGlobalName(e){return this._keywords.find(t=>t.globalName.toLowerCase()===e.toLowerCase())}findByName(e){if(!e)return;let t=e.trim();if(!t)return;const i=t.startsWith("_");i&&(t=t.substring(1));const n=t.toLowerCase();return this._keywords.find(r=>r.enabled?r.globalName.toLowerCase()===n?!0:i?!1:!!(r.localName&&r.localName.toLowerCase()===n||r.alias&&r.alias.toLowerCase()===n||r.displayName.toLowerCase()===n):!1)}get count(){return this._keywords.length}}class Ue{constructor(e,t){this._message="",this._appendKeywordsToMessage=!0,this._isReadOnly=!1,this._keywords=new Ml,t!==void 0?this.setMessageAndKeywords(e,t):this._message=e}get jig(){return this._jig}set jig(e){this._isReadOnly||(this._jig=e)}get message(){return this._message}set message(e){this._isReadOnly||(this._message=e)}getDefaultValueDisplayText(){}getDisplayMessage(){const e=this.getDefaultValueDisplayText();return e==null?this._message:`${this._message.trim().replace(/[::]\s*$/,"")} <${e}>`}get appendKeywordsToMessage(){return this._appendKeywordsToMessage}set appendKeywordsToMessage(e){this._isReadOnly||(this._appendKeywordsToMessage=e)}get isReadOnly(){return this._isReadOnly}get keywords(){return this._keywords}getKeywordPromptFormat(){return this._keywords.getPromptFormat()}setMessageAndKeywords(e,t){if(this._isReadOnly)return this;const i=e.match(/^(.*?)\s*\[(.*?)\](.*)?$/);if(i){const[,n,r]=i;if(this._message=n.trim(),r!==void 0){const o=r.split("/").map(a=>a.trim()).filter(a=>a.length>0);this._keywords.clear();for(const a of o){let c=t.split(/\s+/).find(h=>h.toLowerCase()===a.toLowerCase());c||(c=a),this._keywords.add(a,c)}}}return this}}class xe extends Ue{constructor(e,t){super(e,t),this._useBasePoint=!0,this._useDashedLine=!0,this._useAngleBase=!1,this._defaultValue=0,this._useDefaultValue=!1,this._allowZero=!0,this._allowNegative=!1,this._allowNone=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e))}get baseAngle(){return this._baseAngle??0}set baseAngle(e){this.isReadOnly||(this._baseAngle=e)}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get useAngleBase(){return this._useAngleBase}set useAngleBase(e){this.isReadOnly||(this._useAngleBase=e)}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}getDefaultValueDisplayText(){if(this._useDefaultValue)return String(this._defaultValue)}get allowZero(){return this._allowZero}set allowZero(e){this.isReadOnly||(this._allowZero=e)}get allowNegative(){return this._allowNegative}set allowNegative(e){this.isReadOnly||(this._allowNegative=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}}class In extends Ue{constructor(e,t){super(e),this._useBasePoint=!1,this._useDashedLine=!1,this._disableOSnap=!1,this._allowNone=!1,this._secondCornerMessage=t}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get firstCornerMessage(){return this.message}set firstCornerMessage(e){this.isReadOnly||(this.message=e)}get secondCornerMessage(){return this._secondCornerMessage}set secondCornerMessage(e){this.isReadOnly||(this._secondCornerMessage=e)}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get disableOSnap(){return this._disableOSnap}set disableOSnap(e){this.isReadOnly||(this._disableOSnap=e)}}class Ie{constructor(e,t){this.status=e,this.stringResult=t}}class Mn extends Ie{constructor(e,t,i){super(e,i),this.value=t}}class Dn extends Ue{constructor(e,t){super(e,t),this._defaultValue=0,this._useDefaultValue=!1,this._allowNone=!1,this._allowArbitraryInput=!1,this._allowNegative=!1,this._allowZero=!0}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}getDefaultValueDisplayText(){if(this._useDefaultValue)return String(this._defaultValue)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowArbitraryInput(){return this._allowArbitraryInput}set allowArbitraryInput(e){this.isReadOnly||(this._allowArbitraryInput=e)}get allowNegative(){return this._allowNegative}set allowNegative(e){this.isReadOnly||(this._allowNegative=e)}get allowZero(){return this._allowZero}set allowZero(e){this.isReadOnly||(this._allowZero=e)}}class be extends Dn{constructor(e){super(e),this._useBasePoint=!1,this._useDashedLine=!0,this._only2d=!0,this.allowNegative=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e))}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get only2d(){return this._only2d}set only2d(e){this.isReadOnly||(this._only2d=e)}}class ie extends Dn{}class vr extends Ie{constructor(e,t){super(e,void 0),this.value=t}}class Se extends vr{constructor(e,t){super(e,t)}}class He extends Ue{constructor(e,t){super(e,t),this._allowNone=!1,this._allowObjectOnLockedLayer=!1,this._rejectMessage="Invalid object selected.",this._allowedClasses=new Set}normalizeClassName(e){const t=e.trim();return t.startsWith("AcDb")?t.slice(4):t}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowObjectOnLockedLayer(){return this._allowObjectOnLockedLayer}set allowObjectOnLockedLayer(e){this.isReadOnly||(this._allowObjectOnLockedLayer=e)}get rejectMessage(){return this._rejectMessage}setRejectMessage(e){return this.isReadOnly||(this._rejectMessage=e),this}addAllowedClass(e){if(!this.isReadOnly){const t=this.normalizeClassName(e);t&&this._allowedClasses.add(t)}return this}removeAllowedClass(e){if(!this.isReadOnly){const t=this.normalizeClassName(e);t&&this._allowedClasses.delete(t)}return this}clearAllowedClasses(){return this.isReadOnly||this._allowedClasses.clear(),this}isClassAllowed(e){const t=this.normalizeClassName(e);return this._allowedClasses.size===0||this._allowedClasses.has(t)}}class On extends Ie{constructor(e,t,i){super(e),this.objectId=t,this.pickedPoint=i}}class kr extends Dn{constructor(e,t,i){super(e),typeof t=="number"&&(this._lowerLimit=Math.floor(t)),typeof i=="number"&&(this._upperLimit=Math.ceil(i))}get lowerLimit(){return this._lowerLimit}set lowerLimit(e){this.isReadOnly||(this._lowerLimit=typeof e=="number"?Math.floor(e):void 0)}get upperLimit(){return this._upperLimit}set upperLimit(e){this.isReadOnly||(this._upperLimit=typeof e=="number"?Math.floor(e):void 0)}}class jn extends vr{constructor(e,t){super(e,t)}}class ne extends Ue{constructor(e,t){super(e,t),this._allowNone=!1,this._allowArbitraryInput=!1}get valueDefaultDisplayText(){return this._valueDefaultDisplayText}set valueDefaultDisplayText(e){this.isReadOnly||(this._valueDefaultDisplayText=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowArbitraryInput(){return this._allowArbitraryInput}set allowArbitraryInput(e){this.isReadOnly||(this._allowArbitraryInput=e)}}class I extends Ue{constructor(e,t){super(e,t),this._useBasePoint=!1,this._useDashedLine=!1,this._allowNone=!1,this._disableOSnap=!1,this._useDefaultValue=!1}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(e==null?this._defaultValue=e:this._defaultValue=this._defaultValue?this._defaultValue.copy(e):new u.AcGePoint3d(e))}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}getDefaultValueDisplayText(){if(!this._useDefaultValue||!this._defaultValue)return;const{x:e,y:t,z:i}=this._defaultValue;return i===0?`${e},${t}`:`${e},${t},${i}`}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e))}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get disableOSnap(){return this._disableOSnap}set disableOSnap(e){this.isReadOnly||(this._disableOSnap=e)}}class Bn extends Ie{constructor(e,t){super(e,void 0),this.value=t}}class xt extends Ue{constructor(e,t){super(e,t),this._singleOnly=!1}get singleOnly(){return this._singleOnly}set singleOnly(e){this._singleOnly=e}}class ki extends Ie{constructor(e,t,i){super(e,i),this.value=t}}class le extends Ue{constructor(e,t){super(e,t),this._allowSpaces=!0,this._allowEmpty=!1,this._defaultValue="",this._useDefaultValue=!1}get allowSpaces(){return this._allowSpaces}set allowSpaces(e){this.isReadOnly||(this._allowSpaces=e)}get allowEmpty(){return this._allowEmpty}set allowEmpty(e){this.isReadOnly||(this._allowEmpty=e)}get maxLength(){return this._maxLength}set maxLength(e){this.isReadOnly||(this._maxLength=e)}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}getDefaultValueDisplayText(){if(this._useDefaultValue)return this._defaultValue}}var b=(s=>(s[s.Cancel=-5002]="Cancel",s[s.Error=-5001]="Error",s[s.Keyword=-5005]="Keyword",s[s.Modeless=5027]="Modeless",s[s.None=5e3]="None",s[s.OK=5100]="OK",s[s.Other=5028]="Other",s))(b||{});const nt=class nt{static get messages(){return this._messages}static getLocaleMessage(e){return this._messages[e]}static mergeLocaleMessage(e,t){Dl(this._messages[e],t)}static registerMessage(e,t){this.mergeLocaleMessage(e,t)}static setCurrentLocale(e){const t=this._currentLocale;this._currentLocale=e,this.events.localeChanged.dispatch({old:t,new:this._currentLocale})}static get currentLocale(){return this._currentLocale}static t(e,t){const i=this._currentLocale,n=this._messages[i],r=e.split(".");let o=n;for(const a of r){if(!o||typeof o!="object")return(t==null?void 0:t.fallback)??e;o=o[a]}return typeof o=="string"?o:(t==null?void 0:t.fallback)??e}static cmdKey(e,t,i){return`command.${e}.${t.toLowerCase()}.${i}`}static cmd(e,t,i){return this.t(this.cmdKey(e,t,i))}static cmdDescription(e,t){return this.cmd(e,t,"description")}static cmdPrompt(e,t){return this.cmd(e,t,"prompt")}static sysCmd(e,t){return this.cmd(ce.SYSTEMT_COMMAND_GROUP_NAME,e,t)}static sysCmdKey(e,t){return this.cmdKey(ce.SYSTEMT_COMMAND_GROUP_NAME,e,t)}static userCmd(e,t){return this.cmd(ce.DEFAUT_COMMAND_GROUP_NAME,e,t)}static userCmdKey(e,t){return this.cmdKey(ce.DEFAUT_COMMAND_GROUP_NAME,e,t)}static sysCmdDescription(e){return this.cmdDescription(ce.SYSTEMT_COMMAND_GROUP_NAME,e)}static sysCmdPrompt(e){return this.cmdPrompt(ce.SYSTEMT_COMMAND_GROUP_NAME,e)}};nt._messages={en:{},zh:{},tr:{},cs:{}},nt._currentLocale="en",nt.events={localeChanged:new u.AcCmEventManager},nt.userCmdDescription=e=>nt.cmdDescription(ce.DEFAUT_COMMAND_GROUP_NAME,e),nt.userCmdPrompt=e=>nt.cmdPrompt(ce.DEFAUT_COMMAND_GROUP_NAME,e);let d=nt;function Dl(s,e){for(const t of Object.keys(e)){const i=e[t],n=s[t];Ol(n)&&Ol(i)?Dl(n,i):s[t]=i}}function Ol(s){return typeof s=="object"&&s!==null}const Sm={ACAD:{"-hatch":{description:"Vytváří šrafování pomocí voleb příkazového řádku bez rozhraní pásu karet"},"-layer":{description:"Spravuje hladiny pomocí voleb příkazového řádku"},about:{description:"Zobrazí informace o mlightcad"},acadver:{description:"Ukládá identifikátor verze databáze výkresu (pouze pro čtení)"},angbase:{description:"Nastaví směr základního úhlu 0 vzhledem k aktuálnímu USS"},angdir:{description:"Určuje, zda se kladné úhly měří po směru nebo proti směru hodinových ručiček"},arc:{description:"Vytvoří oblouk"},aunits:{description:"Nastaví formát zobrazení úhlů"},auprec:{description:"Nastaví přesnost zobrazení úhlů, používá se společně s AUNITS"},cdxf:{description:"Exportuje aktuální výkres do DXF"},cpdf:{description:"Exportuje aktuální výkres do PDF"},cecolor:{description:"Nastaví aktuální výchozí barvu pro nově vytvářené objekty"},celtscale:{description:"Řídí měřítko typu čáry pro nově vytvářené objekty"},celtype:{description:"Nastaví typ čáry pro nově vytvářené objekty"},celweight:{description:"Nastaví výchozí tloušťku čáry pro nově vytvářené objekty"},cetransparency:{description:"Nastaví průhlednost pro nově vytvářené objekty"},cachefont:{description:"Uloží místní soubor fontu do IndexedDB pro vykreslování textu"},circle:{description:"Vytvoří jednu kružnici zadáním středu a poloměru"},clayer:{description:"Nastaví aktuální hladinu pro nové objekty a operace úprav"},cmleaderstyle:{description:"Nastaví název aktuálního stylu multiodkazu"},cmlscale:{description:"Řídí celkovou šířku multičáry"},cmlstyle:{description:"Nastaví název aktuálního stylu multičáry"},colortheme:{description:"Řídí barevný motiv uživatelského rozhraní (tmavý nebo světlý)"},copy:{description:"Kopíruje vybrané objekty vytvořením kopií na nových pozicích",prompt:"Vyberte objekty"},csvg:{description:"Převede aktuální výkres na SVG"},chtml:{description:"Exportuje aktuální výkres do samostatného offline souboru HTML"},"-chtml":{description:"Exportuje aktuální výkres do HTML pomocí voleb příkazového řádku"},dimlinear:{description:"Vytvoří lineární kóty"},dimstyle:{description:"Nastaví název aktuálního stylu kótování"},dwgname:{description:"Ukládá název aktuálního souboru výkresu (pouze pro čtení)"},loginname:{description:"Zobrazí přihlašovací jméno uživatele (pouze pro čtení)"},dynmode:{description:"Řídí nastavení dynamického zadávání u kurzoru"},dynprompt:{description:"Řídí zobrazení výzev v popiscích dynamického zadávání"},ellipse:{description:"Vytvoří elipsu nebo eliptický oblouk pomocí koncových bodů os nebo středu"},erase:{description:"Odstraní vybrané objekty z výkresu",prompt:"Vyberte objekty"},extmax:{description:"Ukládá pravý horní roh rozsahu výkresu v modelovém prostoru (pouze pro čtení)"},extmin:{description:"Ukládá levý dolní roh rozsahu výkresu v modelovém prostoru (pouze pro čtení)"},entout:{description:"Exportuje sloučený náhledový obrázek vybraných objektů",prompt:"Vyberte objekty"},hideobjects:{description:"Dočasně potlačí zobrazení vybraných objektů",prompt:"Vyberte objekty"},imageattach:{description:"Připojí rastrový obrázek jako externí referenci k aktuálnímu výkresu"},"-insert":{description:"Vloží definici bloku do aktuálního výkresu (příkazový řádek)"},xattach:{description:"Připojí výkres DWG nebo DXF jako externí referenci k aktuálnímu výkresu"},gripcolor:{description:"Nastaví barvu nevybraných gripů zobrazených na vybraných objektech"},griphot:{description:"Nastaví barvu vybraných (aktivních) gripů"},gripobjlimit:{description:"Potlačí zobrazení gripů, když výběr přesáhne zadaný počet objektů (0 = bez omezení)"},grips:{description:"Řídí, zda se na vybraných objektech zobrazují gripy"},gripsize:{description:"Nastaví velikost gripů v pixelech"},hatch:{description:"Vyplní uzavřenou oblast nebo vybrané objekty vzorem šrafování"},ipdf:{description:"Importuje vektorovou geometrii ze souboru PDF"},hpang:{description:"Nastaví výchozí úhel v radiánech pro nově vytvářené vzory šrafování"},hpassoc:{description:"Řídí, zda jsou nově vytvářená šrafování asociativní"},hpbackgroundcolor:{description:"Nastaví výchozí barvu pozadí pro nově vytvářené vzory šrafování"},hpcolor:{description:"Nastaví výchozí barvu pro nově vytvářená šrafování"},hpdouble:{description:"Řídí, zda jsou uživatelsky definované vzory šrafování zdvojené"},hpislanddetection:{description:"Řídí, jak se nakládá s ostrůvky uvnitř nově vytvářených hranic šrafování"},hplayer:{description:"Nastaví výchozí hladinu pro nově vytvářená šrafování a výplně"},hpname:{description:"Nastaví výchozí název vzoru pro nově vytvářená šrafování v této relaci"},hpscale:{description:"Nastaví výchozí měřítko pro nově vytvářené vzory šrafování"},hpseparate:{description:"Řídí, zda se pro více hranic vytvoří jeden nebo samostatné objekty šrafování"},hptransparency:{description:"Nastaví výchozí průhlednost pro nově vytvářená šrafování a výplně"},insunits:{description:"Určuje jednotky výkresu pro automatické měřítko vkládaných bloků, obrázků nebo externích referencí"},laycur:{description:"Změní hladinu vybraných objektů na aktuální hladinu",prompt:"Vyberte objekty pro změnu na aktuální hladinu"},laydel:{description:"Odstraní hladinu a všechny objekty na této hladině"},layerclose:{description:"Zavře Správce vlastností hladin"},layerp:{description:"Vrátí poslední změnu nebo sadu změn provedených v nastavení hladin"},layfrz:{description:"Zmrazí hladinu vybraných objektů",prompt:"Vyberte objekt na hladině ke zmrazení"},layiso:{description:"Izoluje hladiny vybraných objektů",prompt:"Vyberte objekty na hladinách k izolaci"},laylck:{description:"Uzamkne hladinu vybraných objektů",prompt:"Vyberte objekt na hladině k uzamčení"},layoff:{description:"Vypne hladinu vybraných objektů",prompt:"Vyberte objekt na hladině k vypnutí"},layon:{description:"Zapne všechny hladiny ve výkresu"},laythw:{description:"Rozmrazí všechny zmrazené hladiny ve výkresu"},layulk:{description:"Odemkne hladinu vybraných objektů",prompt:"Vyberte objekt na hladině k odemčení"},layuniso:{description:"Obnoví hladiny skryté nebo uzamčené příkazem LAYISO"},line:{description:"Kreslí úsečky mezi body"},log:{description:"Zaznamenává ladicí informace do konzole"},ltscale:{description:"Nastaví globální měřítko typu čáry pro výkres"},lunits:{description:"Nastaví formát zobrazení souřadnic a vzdáleností"},luprec:{description:"Nastaví přesnost zobrazení délkových jednotek, používá se společně s LUNITS"},lwdisplay:{description:"Řídí, zda se ve výkresu zobrazují tloušťky čar"},clearmeasurements:{description:"Odstraní všechna měření z aktuálního rozvržení"},measurementvis:{description:"Zobrazí nebo skryje měření na aktuálním rozvržení"},measurementexport:{description:"Exportuje měření do sidecar JSON souboru"},measurementimport:{description:"Importuje měření ze sidecar JSON souboru"},measurearea:{description:"Vypočítá plochu a obvod vybraných objektů nebo bodů"},measureangle:{description:"Změří úhel mezi dvěma čarami nebo třemi body"},measurearc:{description:"Změří délku oblouku"},measuredistance:{description:"Změří vzdálenost a přírůstky mezi dvěma body"},measurepoint:{description:"Změří souřadnice X/Y vybraného bodu"},measurement:{description:"Nastaví, zda výkres používá anglosaské (imperiální) nebo metrické jednotky"},measurementcolor:{description:"Nastaví barvu použitou pro překryvy měření"},modelbkcolor:{description:"Nastaví barvu pozadí kreslicí oblasti modelového prostoru"},mline:{description:"Vytvoří několik rovnoběžných čar jako jeden objekt multičáry"},move:{description:"Posune vybrané objekty o vektor přemístění",prompt:"Vyberte objekty"},offset:{description:"Vytvoří rovnoběžné kopie křivek, lomených čar nebo kružnic v zadané vzdálenosti"},mtext:{description:"Vytvoří jeden objekt víceřádkového textu"},open:{description:"Otevře existující soubor výkresu"},openprof:{description:"Řídí, zda se do konzole zaznamenávají časové profily fází otevírání souboru"},openperf:{description:"Otevře paletu výkonu otevření s časy z posledního otevření výkresu"},orthomode:{description:"Omezí pohyb kurzoru na vodorovnou nebo svislou osu"},osmode:{description:"Nastaví trvalé režimy uchopení objektů pomocí bitové hodnoty"},pan:{description:"Posune pohled beze změny směru pohledu nebo zvětšení"},paperbkcolor:{description:"Nastaví barvu pozadí kreslicí oblasti výkresového prostoru (rozvržení)"},pdmode:{description:"Řídí způsob zobrazení bodových entit POINT"},pdsize:{description:"Nastaví velikost zobrazení bodových entit POINT"},pickbox:{description:"Nastaví velikost (v pixelech) výběrového rámečku pro výběr objektů"},pline:{description:"Vytvoří křivku zadáním více bodů"},pngout:{description:"Exportuje do PNG"},point:{description:"Vytvoří body"},polaraddang:{description:"Ukládá další úhly polárního sledování jako seznam oddělený středníky"},polarang:{description:"Nastaví přírůstek polárního úhlu pro polární sledování"},polarmode:{description:"Řídí nastavení polárního sledování a sledování uchopení objektů"},polygon:{description:"Vytvoří pravidelný mnohoúhelník podle středu/poloměru nebo jedné hrany"},qnew:{description:"Zahájí nový výkres"},ray:{description:"Vytvoří polopřímku, která začíná v bodě a pokračuje do nekonečna"},rectang:{description:"Vytvoří obdélník zadáním dvou protilehlých rohů"},regen:{description:"Překreslí aktuální výkres"},revcloud:{description:"Vytvoří nebo upraví revizní obláček"},markuptext:{description:"Umístí textovou poznámku"},markupline:{description:"Vytvoří úsečkovou poznámku"},markuparrow:{description:"Vytvoří šipkovou poznámku"},markupcloud:{description:"Vytvoří revizní obláček"},markuprect:{description:"Vytvoří obdélníkovou poznámku"},markupcircle:{description:"Vytvoří kruhovou poznámku"},markuphighlight:{description:"Vytvoří zvýrazňovací obdélník"},markupcallout:{description:"Vytvoří odkazovou poznámku: zadejte hrot odkazu, umístěte textové pole a zadejte text"},markupstamp:{description:"Umístí razítko nebo vlastní symbol"},markupvis:{description:"Zobrazí nebo skryje poznámky"},clearmarkups:{description:"Vymaže všechny poznámky na aktuálním rozvržení"},markupexport:{description:"Exportuje poznámky do sidecar JSON souboru"},markupimport:{description:"Importuje poznámky ze sidecar JSON souboru"},markuppanel:{description:"Otevře paletu poznámek"},rotate:{description:"Otočí vybrané objekty kolem základního bodu",prompt:"Vyberte objekty"},select:{description:"Vybírá objekty"},shortcutmenu:{description:"Řídí dostupnost místních nabídek v oblasti výkresu"},sketch:{description:"Vytvoří řadu úseček kreslených od ruky"},spline:{description:"Vytvoří hladkou křivku splajn zadáním řídicích bodů"},textstyle:{description:"Nastaví název aktuálního textového stylu"},unitmode:{description:"Řídí zlomkové zobrazení souřadnic, když je LUNITS architektonický nebo zlomkový"},switchbg:{description:"Přepíná pozadí oblasti výkresu mezi bílou a černou"},unisolateobjects:{description:"Znovu zobrazí všechny objekty skryté příkazem HIDEOBJECTS"},undo:{description:"Vrátí zpět poslední operaci úpravy databáze",nothingToUndo:"Není co vrátit zpět."},redo:{description:"Zopakuje poslední vrácenou operaci úpravy databáze",nothingToRedo:"Není co zopakovat."},xline:{description:"Vytvoří konstrukční přímku, která se rozprostírá do nekonečna na obě strany"},zoom:{description:"Zvětší na maximální rozsah všech objektů"}},USER:{}},Pm={arc:{startPointOrCenter:"Zadejte počáteční bod oblouku nebo",secondPointOrOptions:"Zadejte druhý bod oblouku nebo",secondPoint:"Zadejte druhý bod oblouku",startPoint:"Zadejte počáteční bod oblouku",centerPoint:"Zadejte středový bod oblouku",endPoint:"Zadejte koncový bod oblouku",endPointOrOptions:"Zadejte koncový bod oblouku nebo",centerPointOrOptions:"Zadejte středový bod oblouku",includedAngle:"Zadejte středový úhel",chordLength:"Zadejte délku tětivy",tangentDirection:"Zadejte směr tečny v počátečním bodě oblouku",radius:"Zadejte poloměr oblouku",keywords:{center:{display:"Střed(C)",local:"Střed",global:"Center"},end:{display:"Konec(E)",local:"Konec",global:"End"},angle:{display:"Úhel(A)",local:"Úhel",global:"Angle"},chordLength:{display:"délka Tětivy(L)",local:"Délka tětivy",global:"ChordLength"},direction:{display:"Směr(D)",local:"Směr",global:"Direction"},radius:{display:"Poloměr(R)",local:"Poloměr",global:"Radius"}},invalid:{threePoint:"Neplatný 3bodový oblouk: body jsou kolineární nebo nelze definovat oblouk.",center:"Neplatný vstup středu: počáteční a koncový bod musí ležet na stejné kružnici.",angle:"Neplatný vstup úhlu: středový úhel musí být větší než 0 a menší než 360 stupňů.",chordLength:"Neplatná délka tětivy: hodnota je mimo rozsah pro aktuální poloměr.",direction:"Neplatný směr: z tohoto směru tečny nelze sestrojit oblouk.",radius:"Neplatný poloměr: zadaný poloměr nemůže spojit počáteční a koncový bod."}},circle:{center:"Zadejte střed kružnice",centerOrOptions:"Zadejte středový bod kružnice nebo",radius:"Zadejte poloměr kružnice",radiusOrDiameter:"Zadejte poloměr kružnice nebo",diameter:"Zadejte průměr kružnice",twoPointFirst:"Zadejte první koncový bod průměru kružnice",twoPointSecond:"Zadejte druhý koncový bod průměru kružnice",threePointFirst:"Zadejte první bod na kružnici",threePointSecond:"Zadejte druhý bod na kružnici",threePointThird:"Zadejte třetí bod na kružnici",keywords:{threeP:{display:"3B(3P)",local:"3B",global:"3P"},twoP:{display:"2B(2P)",local:"2B",global:"2P"},diameter:{display:"Průměr(D)",local:"Průměr",global:"Diameter"}}},copy:{basePointOrOptions:"Zadejte základní bod nebo",displacementOrArray:"Zadejte přemístění nebo",secondPointOrArray:"Zadejte druhý bod nebo",modePrompt:"Zadejte volbu režimu kopírování",arrayItemCount:"Zadejte počet položek v poli včetně originálu",arraySecondPointOrFit:"Zadejte druhý bod nebo",arrayFitSecondPoint:"Zadejte druhý bod",keywords:{displacement:{display:"Přemístění(D)",local:"Přemístění",global:"Displacement"},mode:{display:"Režim(O)",local:"Režim",global:"Mode"},multiple:{display:"Vícenásobné(M)",local:"Vícenásobné",global:"Multiple"},single:{display:"Jednoduché(S)",local:"Jednoduché",global:"Single"},array:{display:"Pole(A)",local:"Pole",global:"Array"},fit:{display:"Přizpůsobit(F)",local:"Přizpůsobit",global:"Fit"}}},dimlinear:{xLine1Point:"Zadejte počátek první pomocné čáry",xLine2Point:"Zadejte počátek druhé pomocné čáry",dimLinePoint:"Zadejte umístění kótovací čáry"},ellipse:{axisEndpointOrOptions:"Zadejte koncový bod osy elipsy nebo",arcAxisEndpointOrCenter:"Zadejte koncový bod osy eliptického oblouku nebo",center:"Zadejte střed elipsy",firstAxisEndpoint:"Zadejte koncový bod osy",secondAxisEndpoint:"Zadejte druhý koncový bod osy",otherAxisOrRotation:"Zadejte vzdálenost k druhé ose nebo",rotationAngle:"Zadejte úhel otočení kolem hlavní osy",arcStartAngle:"Zadejte počáteční úhel eliptického oblouku",arcEndAngle:"Zadejte koncový úhel eliptického oblouku",keywords:{arc:{display:"Oblouk(A)",local:"Oblouk",global:"Arc"},center:{display:"Střed(C)",local:"Střed",global:"Center"},rotation:{display:"Otočení(R)",local:"Otočení",global:"Rotation"}},invalid:{axis:"Neplatný vstup osy: délka osy musí být větší než 0.",otherAxis:"Neplatný vstup druhé osy: vzdálenost musí být větší než 0.",rotation:"Neplatný vstup otočení: výsledná vedlejší osa musí být větší než 0."}},hatch:{prompt:"Vyberte objekt hranice nebo",pickPoint:"Zadejte vnitřní bod (nebo stiskněte Enter pro dokončení)",select:"Vyberte objekty k šrafování",patternName:"Zadejte název vzoru šrafování",scale:"Zadejte měřítko vzoru šrafování",angle:"Zadejte úhel vzoru šrafování",style:"Zadejte styl šrafování",associative:"Zadejte asociativitu",invalidBoundary:"Vybrané objekty netvoří uzavřenou hranici.",keywords:{pick:{display:"Vybrat body(P)",local:"Vybrat body",global:"PickPoints"},select:{display:"Vybrat objekty(S)",local:"Vybrat objekty",global:"SelectObjects"},cancel:{display:"Zrušit(C)",local:"Zrušit",global:"Cancel"},pattern:{display:"Vzor(P)",local:"Vzor",global:"Pattern"},scale:{display:"Měřítko(S)",local:"Měřítko",global:"Scale"},angle:{display:"Úhel(A)",local:"Úhel",global:"Angle"},style:{display:"Styl(T)",local:"Styl",global:"HatchStyle"},associative:{display:"Asociativní(AS)",local:"Asociativní",global:"AssociativeMode"},normal:{display:"Normální(N)",local:"Normální",global:"Normal"},outer:{display:"Vnější(O)",local:"Vnější",global:"Outer"},ignore:{display:"Ignorovat(I)",local:"Ignorovat",global:"Ignore"},yes:{display:"Ano(Y)",local:"Ano",global:"Yes"},no:{display:"Ne(N)",local:"Ne",global:"No"}}},hideobjects:{hidden:"objekt(ů) skryto",restored:"objekt(ů) obnoveno",nothingToRestore:"Žádné skryté objekty k obnovení"},entout:{longSidePrompt:"Zadejte velikost delší strany náhledu v pixelech",exported:"náhled(ů) objektů exportováno",skipped:"objekt(ů) přeskočeno",failed:{"no-preview-root":"Nelze sestavit geometrii náhledu pro výběr","no-bounds":"Nelze vypočítat rozsah náhledu pro výběr","capture-failed":"Nelze vykreslit náhledový obrázek entity","download-failed":"Náhled byl vykreslen, ale stažení PNG selhalo"}},layer:{main:"Zadejte volbu",listSummary:"Seznam hladin byl vypsán do konzole prohlížeče",emptyInput:"Nebyl zadán žádný název hladiny.",newPrompt:"Zadejte název nové hladiny (nebo hladin)",makePrompt:"Zadejte název hladiny, která se má stát aktuální",setPrompt:"Zadejte název hladiny, která se má nastavit jako aktuální",onPrompt:"Zadejte název (názvy) hladiny k zapnutí",offPrompt:"Zadejte název (názvy) hladiny k vypnutí",freezePrompt:"Zadejte název (názvy) hladiny ke zmrazení",thawPrompt:"Zadejte název (názvy) hladiny k rozmrazení",lockPrompt:"Zadejte název (názvy) hladiny k uzamčení",unlockPrompt:"Zadejte název (názvy) hladiny k odemčení",colorLayerPrompt:"Zadejte název (názvy) hladiny ke změně barvy",colorValuePrompt:"Zadejte barvu (ACI 1-255, RGB např. 255,0,0, nebo CSS název barvy)",invalidColor:"Neplatný vstup barvy.",descriptionLayerPrompt:"Zadejte název hladiny k úpravě popisu",descriptionValuePrompt:"Zadejte nový popis hladiny",created:"Počet vytvořených hladin",alreadyExists:"Hladina již existuje",notFound:"Hladina nenalezena",cannotChangeCurrent:"Nelze vypnout ani zmrazit aktuální hladinu.",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"Vytvořit(M)",local:"Vytvořit",global:"Make"},set:{display:"Nastavit(S)",local:"Nastavit",global:"Set"},new:{display:"Nová(N)",local:"Nová",global:"New"},on:{display:"Zapnout(ON)",local:"Zapnout",global:"On"},off:{display:"Vypnout(OF)",local:"Vypnout",global:"Off"},color:{display:"Barva(C)",local:"Barva",global:"Color"},freeze:{display:"Zmrazit(F)",local:"Zmrazit",global:"Freeze"},thaw:{display:"Rozmrazit(T)",local:"Rozmrazit",global:"Thaw"},lock:{display:"Uzamknout(L)",local:"Uzamknout",global:"Lock"},unlock:{display:"Odemknout(U)",local:"Odemknout",global:"Unlock"},description:{display:"Popis(D)",local:"Popis",global:"Description"}}},layon:{alreadyOn:"Všechny hladiny jsou již zapnuté.",turnedOn:"Zapnuté hladiny"},laycur:{prompt:"Vyberte objekty ke změně na aktuální hladinu",currentLayerNotFound:"Aktuální hladina nenalezena.",noObjects:"Nebyly vybrány žádné platné objekty.",alreadyCurrent:"Vybrané objekty jsou již na aktuální hladině.",changed:"Objekty změněny na aktuální hladinu"},layfrz:{prompt:"Vyberte objekt na hladině ke zmrazení nebo",invalidSelection:"Vybrán neplatný objekt.",settingsPrompt:"Zadejte nastavení LAYFRZ ke změně",viewportPrompt:"Zadejte chování zmrazení ve výřezu",blockSelectionPrompt:"Zadejte chování výběru vnořeného bloku",vpfreezeFallback:"Aktuální prohlížeč nepodporuje zmrazení hladiny podle výřezu; místo toho se použije chování Zmrazit.",nestedSelectionLimited:"Nastavení výběru vnořeného bloku se uloží, ale aktuální výběr stále vyhodnocuje hladinu entity nejvyšší úrovně.",layerNotFound:"Hladina nenalezena",cannotFreezeCurrent:"Nelze zmrazit aktuální hladinu.",alreadyFrozen:"Hladina je již zmrazená",frozen:"Zmrazená hladina",restored:"Obnovená hladina",nothingToUndo:"Neexistuje žádná akce LAYFRZ k vrácení zpět.",keywords:{settings:{display:"Nastavení(S)",local:"Nastavení",global:"Settings"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},viewports:{display:"Výřezy(V)",local:"Výřezy",global:"Viewports"},blockSelection:{display:"Výběr bloku(B)",local:"Výběr bloku",global:"BlockSelection"},freeze:{display:"Zmrazit(F)",local:"Zmrazit",global:"Freeze"},vpfreeze:{display:"Zmrazit ve výřezu(V)",local:"Zmrazit ve výřezu",global:"Vpfreeze"},block:{display:"Blok(B)",local:"Blok",global:"Block"},entity:{display:"Entita(E)",local:"Entita",global:"Entity"},none:{display:"Žádný(N)",local:"Žádný",global:"None"}}},layiso:{prompt:"Vyberte objekty na hladině (hladinách) k izolaci nebo",settingsPrompt:"Zadejte nastavení pro neizolované hladiny",offModePrompt:"Zadejte chování vypnutí pro neizolované hladiny",noLayers:"Nebyly vybrány žádné platné hladiny.",layerNotFound:"Hladina nenalezena",isolated:"Izolovaná hladina (hladiny)",affectedLayers:"ovlivněné hladiny",vpfreezeFallback:"Aktuální prohlížeč nepodporuje zmrazení hladiny podle výřezu; místo toho se použije chování Vypnout.",lockFadeFallback:"Aktuální prohlížeč nepodporuje ztlumení zobrazení hladiny; neizolované hladiny budou uzamčeny bez ztlumení.",keywords:{settings:{display:"Nastavení(S)",local:"Nastavení",global:"Settings"},off:{display:"Vypnout(O)",local:"Vypnout",global:"Off"},lockAndFade:{display:"Uzamknout a ztlumit(L)",local:"Uzamknout a ztlumit",global:"LockAndFade"},vpfreeze:{display:"Zmrazit ve výřezu(V)",local:"Zmrazit ve výřezu",global:"Vpfreeze"}}},layuniso:{noPrevious:"Neexistuje žádný předchozí stav hladin LAYISO k obnovení.",layerNotFound:"Hladina nenalezena",nothingRestored:"Nebyly obnoveny žádné změny hladin LAYISO.",restored:"Obnovené hladiny"},laythw:{alreadyThawed:"Všechny hladiny jsou již rozmrazené.",thawed:"Rozmrazené hladiny"},laylck:{prompt:"Vyberte objekt na hladině k uzamčení",invalidSelection:"Vybrán neplatný objekt.",layerNotFound:"Hladina nenalezena",alreadyLocked:"Hladina je již uzamčená",locked:"Uzamčená hladina"},layulk:{prompt:"Vyberte objekt na hladině k odemčení",invalidSelection:"Vybrán neplatný objekt.",layerNotFound:"Hladina nenalezena",alreadyUnlocked:"Hladina je již odemčená",unlocked:"Odemčená hladina"},layoff:{prompt:"Vyberte objekt na hladině k vypnutí nebo",invalidSelection:"Vybrán neplatný objekt.",settingsPrompt:"Zadejte nastavení LAYOFF ke změně",viewportPrompt:"Zadejte chování výřezu",blockSelectionPrompt:"Zadejte chování výběru vnořeného bloku",vpfreezeFallback:"Aktuální prohlížeč nepodporuje vypnutí hladiny podle výřezu; místo toho se použije chování Vypnout.",nestedSelectionLimited:"Nastavení výběru vnořeného bloku se uloží, ale aktuální výběr stále vyhodnocuje hladinu entity nejvyšší úrovně.",layerNotFound:"Hladina nenalezena",cannotTurnOffCurrent:"Nelze vypnout aktuální hladinu.",alreadyOff:"Hladina je již vypnutá",turnedOff:"Vypnutá hladina",restored:"Obnovená hladina",nothingToUndo:"Neexistuje žádná akce LAYOFF k vrácení zpět.",keywords:{settings:{display:"Nastavení(S)",local:"Nastavení",global:"Settings"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},viewports:{display:"Výřezy(V)",local:"Výřezy",global:"Viewports"},blockSelection:{display:"Výběr bloku(B)",local:"Výběr bloku",global:"BlockSelection"},off:{display:"Vypnout(O)",local:"Vypnout",global:"Off"},vpfreeze:{display:"Zmrazit ve výřezu(V)",local:"Zmrazit ve výřezu",global:"Vpfreeze"},block:{display:"Blok(B)",local:"Blok",global:"Block"},entity:{display:"Entita(E)",local:"Entita",global:"Entity"},none:{display:"Žádný(N)",local:"Žádný",global:"None"}}},layerp:{restored:"Obnoven předchozí stav hladin.",noPreviousState:"Neexistuje žádný předchozí stav hladin k obnovení."},line:{firstPoint:"Zadejte první bod",firstPointOrContinue:"Zadejte první bod nebo",nextPoint:"Zadejte další bod",nextPointWithOptions:"Zadejte další bod nebo",keywords:{continue:{display:"Pokračovat(C)",local:"Pokračovat",global:"Continue"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},close:{display:"Uzavřít(C)",local:"Uzavřít",global:"Close"}}},xline:{firstPointOrOptions:"Zadejte bod nebo",secondPoint:"Zadejte druhý bod",throughPoint:"Zadejte bod, kterým má přímka procházet",angle:"Zadejte úhel konstrukční přímky",invalidDirection:"Neplatný směr pro XLINE.",keywords:{hor:{display:"Vodorovně(H)",local:"Vodorovně",global:"Hor"},ver:{display:"Svisle(V)",local:"Svisle",global:"Ver"},ang:{display:"Úhel(A)",local:"Úhel",global:"Ang"}}},ray:{startPoint:"Zadejte počáteční bod",throughPoint:"Zadejte bod, kterým má polopřímka procházet"},mline:{startPointWithOptions:"Zadejte počáteční bod nebo",nextPointWithOptions:"Zadejte další bod nebo",justificationPrompt:"Zadejte typ zarovnání",scalePrompt:"Zadejte měřítko multičáry",stylePrompt:"Zadejte název stylu multičáry nebo [?] pro seznam",styleNotFound:"Styl multičáry nenalezen",styleListHeader:"Načtené styly multičáry",styleListEmpty:"V aktuálním výkresu není načten žádný styl multičáry.",keywords:{justification:{display:"Zarovnání(J)",local:"Zarovnání",global:"Justification"},scale:{display:"Měřítko(S)",local:"Měřítko",global:"Scale"},style:{display:"Styl(ST)",local:"Styl",global:"Style"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},close:{display:"Uzavřít(C)",local:"Uzavřít",global:"Close"},top:{display:"Nahoře(T)",local:"Nahoře",global:"Top"},zero:{display:"Nula(Z)",local:"Nula",global:"Zero"},bottom:{display:"Dole(B)",local:"Dole",global:"Bottom"}}},measureAngle:{vertex:"Zadejte vrchol",arm1:"Zadejte bod na prvním rameni",arm2:"Zadejte bod na druhém rameni"},measureArc:{startPoint:"Zadejte počáteční bod oblouku",throughPoint:"Zadejte bod na oblouku",endPoint:"Zadejte koncový bod oblouku"},measureArea:{firstPoint:"Zadejte první bod",nextPoint:"Zadejte další bod (nebo stiskněte Enter pro dokončení)"},measureDistance:{firstPoint:"Zadejte první bod",secondPoint:"Zadejte druhý bod"},measurePoint:{point:"Zadejte bod"},measurement:{import:{chooseFile:"Vyberte sidecar JSON soubor měření"}},markup:{author:"Zadejte autora kontroly (uloží se pro pozdější použití)",text:{point:"Zadejte bod textové poznámky",content:"Zadejte text poznámky"},line:{firstPoint:"Zadejte první bod úsečkové poznámky",secondPoint:"Zadejte druhý bod úsečkové poznámky"},arrow:{firstPoint:"Zadejte počáteční bod šipky",secondPoint:"Zadejte hrot šipky"},cloud:{firstCorner:"Zadejte první roh obláčku",secondCorner:"Zadejte protilehlý roh obláčku"},rect:{firstCorner:"Zadejte první roh obdélníku",secondCorner:"Zadejte protilehlý roh obdélníku"},circle:{center:"Zadejte střed kružnice",radius:"Zadejte poloměr kružnice"},shape:{calloutOn:"[Odkaz zapnut]",calloutOff:"[Odkaz vypnut]",calloutAnchor:"Zadejte umístění textu odkazu",keywords:{callout:{display:"Odkaz(C)",local:"Odkaz",global:"Callout"},noCallout:{display:"BezOdkazu(N)",local:"BezOdkazu",global:"NoCallout"}}},highlight:{firstCorner:"Zadejte první roh zvýraznění",secondCorner:"Zadejte protilehlý roh zvýraznění"},callout:{tip:"Zadejte hrot odkazu (konec šipky)",anchor:"Zadejte umístění textu odkazu",content:"Zadejte text odkazu"},stamp:{kind:"Zadejte identifikátor razítka [approved/rejected/revised/for-review/custom]",imageUrl:"Zadejte URL vlastního obrázku razítka (volitelné)",caption:"Zadejte popisek razítka (volitelné)",point:"Zadejte bod vložení razítka"},import:{chooseFile:"Vyberte sidecar JSON soubor poznámek"}},move:{basePointOrDisplacement:"Zadejte základní bod nebo",secondPointOrDisplacement:"Zadejte druhý bod nebo",displacement:"Zadejte přemístění",keywords:{displacement:{display:"Přemístění(D)",local:"Přemístění",global:"Displacement"}}},offset:{distance:"Zadejte vzdálenost offsetu",selectObject:"Vyberte objekt k offsetu nebo stiskněte Enter pro dokončení",sidePoint:"Zadejte bod na straně pro offset",invalidDistance:"Vzdálenost offsetu musí být větší než 0.",invalidSelection:"Vybraný objekt nelze offsetovat.",offsetFailed:"Nelze vytvořit offsetovou křivku na zadané straně."},mtext:{point:"Zadejte bod vložení víceřádkového textu"},pngout:{boundsFirstCorner:"Zadejte první roh rozsahu",boundsSecondCorner:"Zadejte protilehlý roh",longSidePrompt:"Zadejte velikost delší strany v pixelech"},imageattach:{insertionPoint:"Zadejte bod vložení:",scale:"Zadejte faktor měřítka:",rotation:"Zadejte úhel otočení:",invalidScale:"Faktor měřítka musí být větší než 0.",decodeFailed:"Nepodařilo se načíst vybraný soubor obrázku."},insert:{blockName:"Zadejte název bloku:",insertionPoint:"Zadejte bod vložení:",scale:"Zadejte faktor měřítka:",rotation:"Zadejte úhel otočení:",invalidScale:"Faktor měřítka musí být větší než 0.",invalidBlockName:"Neplatný název bloku.",blockNotFound:"Blok nenalezen",xrefNotAllowed:"Nelze vložit externí referenci pomocí -INSERT."},xattach:{insertionPoint:"Zadejte bod vložení:",scale:"Zadejte faktor měřítka:",rotation:"Zadejte úhel otočení:",invalidScale:"Faktor měřítka musí být větší než 0.",unsupportedFile:"Vyberte soubor DWG nebo DXF.",loading:"Načítám externí referenci...",loadFailed:"Nepodařilo se načíst vybraný soubor výkresu."},point:{point:"Zadejte bod"},polygon:{numberOfSides:"Zadejte počet stran",centerOrEdge:"Zadejte střed mnohoúhelníku nebo",radiusOrType:"Zadejte volby",edgeStart:"Zadejte první koncový bod hrany",edgeEnd:"Zadejte druhý koncový bod hrany",keywords:{edge:{display:"Hrana(E)",local:"Hrana",global:"Edge"},inscribed:{display:"Vepsaný do kružnice(I)",local:"Vepsaný do kružnice",global:"Inscribed"},circumscribed:{display:"Opsaný kolem kružnice(C)",local:"Opsaný kolem kružnice",global:"Circumscribed"}},invalid:{sides:"Neplatný počet stran. Zadejte celé číslo mezi 3 a 1024.",radius:"Neplatný poloměr. Poloměr musí být větší než 0.",edge:"Neplatná hrana. Délka hrany musí být větší než 0."}},polyline:{firstPoint:"Zadejte první bod",nextPoint:"Zadejte další bod (nebo stiskněte Enter pro dokončení)",nextPointWithOptions:"Zadejte další bod nebo",nextPointWithArcOptions:"Zadejte další bod nebo",keywords:{arc:{display:"Oblouk(A)",local:"Oblouk",global:"Arc"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},close:{display:"Uzavřít(C)",local:"Uzavřít",global:"Close"},line:{display:"Úsečka(L)",local:"Úsečka",global:"Line"},angle:{display:"Úhel(A)",local:"Úhel",global:"Angle"},center:{display:"Střed(C)",local:"Střed",global:"Center"},secondPoint:{display:"Druhý bod(P)",local:"Druhý bod",global:"SecondPoint"},radius:{display:"Poloměr(R)",local:"Poloměr",global:"Radius"}},arcAngle:"Zadejte úhel oblouku",arcCenter:"Zadejte středový bod",arcSecondPoint:"Zadejte druhý bod na oblouku",arcEndPoint:"Zadejte koncový bod oblouku",arcRadius:"Zadejte poloměr oblouku"},rect:{firstPoint:"Zadejte první roh",nextPoint:"Zadejte druhý roh",firstPointWithOptions:"Zadejte první roh nebo",otherCornerWithOptions:"Zadejte druhý roh nebo",chamferFirst:"Zadejte první vzdálenost zkosení",chamferSecond:"Zadejte druhou vzdálenost zkosení",filletRadius:"Zadejte poloměr zaoblení",segmentWidth:"Zadejte šířku čáry obdélníku",elevationValue:"Zadejte výšku",thicknessValue:"Zadejte tloušťku",rotationAngle:"Zadejte úhel otočení obdélníku",dimensionLength:"Zadejte délku obdélníku",dimensionWidth:"Zadejte šířku obdélníku",areaValue:"Zadejte plochu obdélníku",areaLengthOrWidth:"Zadejte délku obdélníku",areaSpecifyWidth:"Zadejte šířku obdélníku",invalidPositive:"Neplatný vstup. Zadejte hodnotu větší než 0.",invalidRect:"Nelze vytvořit obdélník. Zadejte platné rohy nebo rozměry.",thicknessNotSupported:"Tloušťka obdélníku se aktuálně nezapisuje do dat entity. Nastavení tloušťky se ignoruje.",keywords:{chamfer:{display:"Zkosení(C)",local:"Zkosení",global:"Chamfer"},elevation:{display:"Výška(E)",local:"Výška",global:"Elevation"},fillet:{display:"Zaoblení(F)",local:"Zaoblení",global:"Fillet"},thickness:{display:"Tloušťka(T)",local:"Tloušťka",global:"Thickness"},width:{display:"Šířka(W)",local:"Šířka",global:"Width"},area:{display:"Plocha(A)",local:"Plocha",global:"Area"},dimensions:{display:"Rozměry(D)",local:"Rozměry",global:"Dimensions"},rotation:{display:"Otočení(R)",local:"Otočení",global:"Rotation"},length:{display:"Délka(L)",local:"Délka",global:"Length"},rectWidth:{display:"Šířka(W)",local:"Šířka",global:"Width"}}},rotate:{basePoint:"Zadejte základní bod",rotationAngleOrOptions:"Zadejte úhel otočení nebo",referenceAngleOrPoints:"Zadejte referenční úhel nebo",firstReferencePoint:"Zadejte první bod referenčního úhlu",secondReferencePoint:"Zadejte druhý bod",newAngle:"Zadejte nový úhel",keywords:{copy:{display:"Kopírovat(C)",local:"Kopírovat",global:"Copy"},reference:{display:"Reference(R)",local:"Reference",global:"Reference"},points:{display:"Body(P)",local:"Body",global:"Points"}},invalid:{referencePoints:"Neplatné referenční body: body musí být různé."}},revcloud:{firstCornerOrOptions:"Zadejte první rohový bod nebo",firstCorner:"Zadejte první rohový bod",oppositeCorner:"Zadejte protilehlý roh",startPoint:"Zadejte počáteční bod",nextPoint:"Zadejte další bod",nextPointOrUndo:"Zadejte další bod nebo",firstPoint:"Zadejte první bod",guideCursor:"Veďte kurzor podél obláčku (Enter dokončí)",arcLength:"Zadejte délku oblouku",selectObject:"Vyberte objekt",style:"Zadejte styl oblouků revizního obláčku",reverseDirection:"Obrátit směr",invalidArcLength:"Délka oblouku musí být větší než 0.",invalidObject:"Vybraný objekt nelze převést na revizní obláček.",keywords:{arcLength:{display:"Délka oblouku(A)",local:"Délka oblouku",global:"ArcLength"},object:{display:"Objekt(O)",local:"Objekt",global:"Object"},rectangular:{display:"Obdélníkový(R)",local:"Obdélníkový",global:"Rectangular"},polygonal:{display:"Mnohoúhelníkový(P)",local:"Mnohoúhelníkový",global:"Polygonal"},freehand:{display:"Od ruky(F)",local:"Od ruky",global:"Freehand"},style:{display:"Styl(S)",local:"Styl",global:"Style"},normal:{display:"Normální(N)",local:"Normální",global:"Normal"},calligraphy:{display:"Kaligrafie(C)",local:"Kaligrafie",global:"Calligraphy"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},yes:{display:"Ano(Y)",local:"Ano",global:"Yes"},no:{display:"Ne(N)",local:"Ne",global:"No"}}},sketch:{specifySketch:"Zadejte skicu nebo",sketching:"Pohybem ukazatele kreslete (kliknutím nebo Enter zastavíte)",type:"Zadejte typ skici",increment:"Zadejte přírůstek skici",tolerance:"Zadejte toleranci splajnu",firstPoint:"Zadejte první bod",nextPoint:"Zadejte koncový bod",keywords:{type:{display:"Typ(T)",local:"Typ",global:"Type"},increment:{display:"Přírůstek(I)",local:"Přírůstek",global:"Increment"},tolerance:{display:"toLerance(L)",local:"toLerance",global:"Tolerance"},line:{display:"Úsečky(L)",local:"Úsečky",global:"Lines"},polyline:{display:"Křivka(P)",local:"Křivka",global:"Polyline"},spline:{display:"Splajn(S)",local:"Splajn",global:"Spline"}}},spline:{firstPoint:"Zadejte první bod",nextPoint:"Zadejte další bod (nebo stiskněte Enter pro dokončení)",firstPointWithOptions:"Zadejte první bod nebo",nextPointWithFitOptions:"Zadejte další bod nebo",nextPointWithCvOptions:"Zadejte další řídicí bod nebo",methodPrompt:"Zadejte metodu vytvoření splajnu",knotsPrompt:"Zadejte parametrizaci uzlů",degreePrompt:"Zadejte stupeň splajnu",keywords:{method:{display:"Metoda(M)",local:"Metoda",global:"Method"},fit:{display:"Přizpůsobit(F)",local:"Přizpůsobit",global:"Fit"},cv:{display:"ŘB(C)",local:"ŘB",global:"CV"},knots:{display:"Uzly(K)",local:"Uzly",global:"Knots"},degree:{display:"Stupeň(D)",local:"Stupeň",global:"Degree"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},close:{display:"Uzavřít(C)",local:"Uzavřít",global:"Close"},chord:{display:"Tětiva(C)",local:"Tětiva",global:"Chord"},sqrtChord:{display:"Odmocnina tětivy(S)",local:"Odmocnina tětivy",global:"SqrtChord"},uniform:{display:"Rovnoměrné(U)",local:"Rovnoměrné",global:"Uniform"}}},sysvar:{prompt:"Zadejte novou hodnotu"},zoom:{mainPrompt:"Zadejte roh okna nebo",firstCorner:"Zadejte první roh",secondCorner:"Zadejte protilehlý roh",centerPoint:"Zadejte středový bod",heightOrScale:"Zadejte výšku nebo faktor měřítka (nX nebo nXP)",scaleFactor:"Zadejte faktor měřítka (nX nebo nXP)",keywords:{all:{display:"Vše(A)",local:"Vše",global:"All"},center:{display:"Střed(C)",local:"Střed",global:"Center"},extents:{display:"Rozsah(E)",local:"Rozsah",global:"Extents"},previous:{display:"Předchozí(P)",local:"Předchozí",global:"Previous"},scale:{display:"Měřítko(S)",local:"Měřítko",global:"Scale"},window:{display:"Okno(W)",local:"Okno",global:"Window"}}},chtml:{exportInvisibleLayers:"Exportovat neviditelné hladiny",initialView:"Počáteční pohled při otevření HTML",viewerMode:"Režim offline prohlížeče",keywords:{yes:{display:"Ano(Y)",local:"Ano",global:"Yes"},no:{display:"Ne(N)",local:"Ne",global:"No"},extents:{display:"Rozsah(E)",local:"Rozsah",global:"Extents"},current:{display:"Aktuální(C)",local:"Aktuální",global:"Current"},view:{display:"Pohled(V)",local:"Pohled",global:"View"},measure:{display:"Měření(M)",local:"Měření",global:"Measure"}}}},Am={document:{untitled:"Bez názvu"},commandLine:{noLast:"(žádný předchozí příkaz)",unknownCommand:"Neznámý příkaz",executed:"Provedený příkaz",showHistory:"Zobrazit historii příkazů",placeholder:"Zadejte příkaz",showMessages:"Zobrazit historii zpráv",canceled:"*Zrušeno*",noHistory:"(žádná historie)",invalidInput:"Neplatný vstup.",close:"Zavřít příkazový řádek"},inputManager:{firstCorner:"Zadejte první roh nebo",secondCorner:"Zadejte druhý roh nebo"},message:{fetchingDrawingFile:"Načítám soubor…",exportingDxf:"Exportuji DXF…",exportingEntityPreview:"Exportuji obrázek…",collectingMemoryProfile:"Analyzuji paměť…",fontCached:"Font úspěšně uložen do mezipaměti",fontCacheFailed:"Uložení fontu do mezipaměti selhalo"},progress:{start:"Zahajuji načítání souboru…",parse:"Načítám soubor…",font:"Stahuji fonty potřebné pro tento výkres…",ltype:"Načítám typy čar…",style:"Načítám textové styly…",dimstyle:"Načítám kótovací styly…",layer:"Načítám hladiny…",vport:"Načítám výřezy…",blockrecord:"Načítám záznamy bloků…",header:"Načítám hlavičku…",block:"Načítám bloky…",entity:"Načítám objekty…",object:"Načítám pojmenované slovníky…",rendering:"Vykreslování výkresu ...",end:"Hotovo!"},about:{title:"O aplikaci",close:"Zavřít",product:"CAD Viewer",tagline:"Vysokovýkonný webový CAD prohlížeč pro výkresy DWG a DXF.",website:"Web",docs:"Dokumentace",repository:"GitHub",copyright:"© {year} mlightcad. Všechna práva vyhrazena.",ok:"OK"},drawStyle:{color:"Barva",lineWeight:"Tloušťka čáry",fontSize:"Výška textu"}},Cm={ACAD:{"-hatch":{description:"Creates hatch fills through command-line options without the ribbon UI"},"-layer":{description:"Manages layers through command-line options"},about:{description:"Displays information about mlightcad"},acadver:{description:"Stores the drawing database version identifier (read-only)"},angbase:{description:"Sets the base angle 0 direction with respect to the current UCS"},angdir:{description:"Sets whether positive angles are measured clockwise or counterclockwise"},arc:{description:"Creates an arc"},aunits:{description:"Sets the display format for angles"},auprec:{description:"Sets the display precision for angles, used together with AUNITS"},cdxf:{description:"Exports current drawing to DXF"},cpdf:{description:"Exports current drawing to PDF"},cecolor:{description:"Sets the current default color for newly created objects"},celtscale:{description:"Controls the linetype scale factor for newly created objects"},celtype:{description:"Sets the linetype for newly created objects"},celweight:{description:"Sets the default lineweight for newly created objects"},cetransparency:{description:"Sets the transparency for newly created objects"},cachefont:{description:"Caches a local font file into IndexedDB for text rendering"},circle:{description:"Creates one circle by center and radius"},clayer:{description:"Sets the current layer for new objects and editing operations"},cmleaderstyle:{description:"Sets the name of the current multileader style"},cmlscale:{description:"Controls the overall width of a multiline"},cmlstyle:{description:"Sets the name of the current multiline style"},colortheme:{description:"Controls the color theme of the user interface (dark or light)"},copy:{description:"Copies selected entities by cloning them to new positions",prompt:"Select entities"},csvg:{description:"Converts current drawing to SVG"},chtml:{description:"Exports current drawing to a standalone offline HTML file"},"-chtml":{description:"Exports current drawing to HTML using command-line options"},dimlinear:{description:"Creates linear dimensions"},dimstyle:{description:"Sets the name of the current dimension style"},dwgname:{description:"Stores the name of the current drawing file (read-only)"},loginname:{description:"Displays the user's login name (read-only)"},dynmode:{description:"Controls Dynamic Input settings at the cursor"},dynprompt:{description:"Controls display of prompts in Dynamic Input tooltips"},ellipse:{description:"Creates an ellipse or elliptical arc by axis endpoints or center"},erase:{description:"Deletes selected entities from the drawing",prompt:"Select entities"},extmax:{description:"Stores the upper-right corner of the model-space drawing extents (read-only)"},extmin:{description:"Stores the lower-left corner of the model-space drawing extents (read-only)"},entout:{description:"Exports a merged preview image for selected entities",prompt:"Select entities"},hideobjects:{description:"Temporarily suppresses the display of selected objects",prompt:"Select objects"},imageattach:{description:"Attaches a raster image as an external reference to the current drawing"},"-insert":{description:"Inserts a block definition into the current drawing (command-line)"},xattach:{description:"Attaches a DWG or DXF drawing as an external reference to the current drawing"},gripcolor:{description:"Sets the color of unselected grips displayed on selected objects"},griphot:{description:"Sets the color of selected (hot) grips"},gripobjlimit:{description:"Suppresses grip display when the selection set exceeds the specified number of objects (0 = no limit)"},grips:{description:"Controls whether grips are displayed on selected objects"},gripsize:{description:"Sets the size of grip boxes in pixels"},hatch:{description:"Fills an enclosed area or selected objects with a hatch pattern"},ipdf:{description:"Imports vector geometry from a PDF file"},hpang:{description:"Sets the default angle, in radians, for newly created hatch patterns"},hpassoc:{description:"Controls whether newly created hatches are associative"},hpbackgroundcolor:{description:"Sets the default background color for newly created hatch patterns"},hpcolor:{description:"Sets the default color for newly created hatches"},hpdouble:{description:"Controls whether user-defined hatch patterns are doubled"},hpislanddetection:{description:"Controls how islands within newly created hatch boundaries are treated"},hplayer:{description:"Sets the default layer for newly created hatches and fills"},hpname:{description:"Sets the default pattern name for newly created hatches in this session"},hpscale:{description:"Sets the default scale factor for newly created hatch patterns"},hpseparate:{description:"Controls whether one or separate hatch objects are created for multiple boundaries"},hptransparency:{description:"Sets the default transparency for newly created hatches and fills"},insunits:{description:"Specifies drawing units for automatic scaling of inserted blocks, images, or xrefs"},laycur:{description:"Changes the layer property of selected objects to the current layer",prompt:"Select objects to be changed to the current layer"},laydel:{description:"Deletes a layer and all objects on that layer"},layerclose:{description:"Closes the Layer Properties Manager"},layerp:{description:"Undoes the last change or set of changes made to layer settings"},layfrz:{description:"Freezes the layer of selected objects",prompt:"Select object on layer to freeze"},layiso:{description:"Isolates the layers of selected objects",prompt:"Select objects on layers to isolate"},laylck:{description:"Locks the layer of selected objects",prompt:"Select object on layer to lock"},layoff:{description:"Turns off the layer of selected objects",prompt:"Select object on layer to turn off"},layon:{description:"Turns on all layers in the drawing"},laythw:{description:"Thaws all frozen layers in the drawing"},layulk:{description:"Unlocks the layer of selected objects",prompt:"Select object on layer to unlock"},layuniso:{description:"Restores layers hidden or locked by LAYISO"},line:{description:"Draws straight line segments between points"},log:{description:"Logs debug information in console"},ltscale:{description:"Sets the global linetype scale factor for the drawing"},lunits:{description:"Sets the display format for coordinates and distances"},luprec:{description:"Sets the display precision for linear units, used together with LUNITS"},lwdisplay:{description:"Controls whether lineweights are displayed in the drawing"},clearmeasurements:{description:"Removes all measurements from the current layout"},measurementvis:{description:"Shows or hides measurements on the current layout"},measurementexport:{description:"Exports measurements to a sidecar JSON file"},measurementimport:{description:"Imports measurements from a sidecar JSON file"},measurearea:{description:"Calculates the area and perimeter of selected objects or points"},measureangle:{description:"Measures the angle between two lines or three points"},measurearc:{description:"Measures the length of an arc segment"},measuredistance:{description:"Measures the distance and delta values between two points"},measurepoint:{description:"Measures the X/Y coordinates of a picked point"},measurement:{description:"Sets whether the drawing uses English (imperial) or metric units"},measurementcolor:{description:"Sets the color used for measurement overlays"},modelbkcolor:{description:"Sets the background color of the model-space drawing area"},mline:{description:"Creates multiple parallel lines as one multiline object"},move:{description:"Moves selected entities by a displacement vector",prompt:"Select entities"},offset:{description:"Creates parallel curves, polylines, or circles at a specified distance"},mtext:{description:"Creates one mtext entity"},open:{description:"Opens an existing drawing file"},openprof:{description:"Controls whether open-file stage timing profiles are logged to the console"},openperf:{description:"Opens the Open Performance palette with timings from the last drawing open"},orthomode:{description:"Constrains cursor movement to the horizontal or vertical axis"},osmode:{description:"Sets running Object Snap modes using a bitcode value"},pan:{description:"Shifts the view without changing the viewing direction or magnification"},paperbkcolor:{description:"Sets the background color of the paper-space (layout) drawing area"},pdmode:{description:"Controls how POINT entities are displayed"},pdsize:{description:"Sets the display size for POINT entities"},pickbox:{description:"Sets the size (in pixels) of the selection box used to pick objects"},pline:{description:"Creates a polyline by specifying multiple points"},pngout:{description:"Exports to PNG"},point:{description:"Creates points"},polaraddang:{description:"Stores additional polar tracking angles as a semicolon-separated list"},polarang:{description:"Sets the polar angle increment for polar tracking"},polarmode:{description:"Controls polar and object snap tracking settings"},polygon:{description:"Creates a regular polygon by center/radius or by one polygon edge"},qnew:{description:"Starts a new drawing"},ray:{description:"Creates a ray that starts at a point and extends to infinity"},rectang:{description:"Creates a rectangle by specifying two opposite corners"},regen:{description:"Redraws the current drawing"},revcloud:{description:"Creates or modifies a revision cloud"},markuptext:{description:"Places a text markup label"},markupline:{description:"Creates a line markup"},markuparrow:{description:"Creates an arrow markup"},markupcloud:{description:"Creates a revision cloud markup"},markuprect:{description:"Creates a rectangle markup"},markupcircle:{description:"Creates a circle markup"},markuphighlight:{description:"Creates a highlight rectangle markup"},markupcallout:{description:"Creates a callout: pick leader tip, place text box, then enter text"},markupstamp:{description:"Places a stamp or custom symbol"},markupvis:{description:"Shows or hides markups"},clearmarkups:{description:"Clears all markups on the current layout"},markupexport:{description:"Exports markups to a sidecar JSON file"},markupimport:{description:"Imports markups from a sidecar JSON file"},markuppanel:{description:"Opens the markup palette"},rotate:{description:"Rotates selected entities around a base point",prompt:"Select entities"},select:{description:"Selects entities"},shortcutmenu:{description:"Controls the availability of shortcut menus in the drawing area"},sketch:{description:"Creates a series of freehand line segments"},spline:{description:"Creates a smooth spline curve by specifying control points"},textstyle:{description:"Sets the name of the current text style"},unitmode:{description:"Controls fractional display of coordinates when LUNITS is Architectural or Fractional"},switchbg:{description:"Toggles the drawing area background between white and black"},unisolateobjects:{description:"Redisplay all objects hidden by HIDEOBJECTS"},undo:{description:"Undoes the last database editing operation",nothingToUndo:"Nothing to undo."},redo:{description:"Redoes the last undone database editing operation",nothingToRedo:"Nothing to redo."},xline:{description:"Creates a construction line that extends infinitely in both directions"},zoom:{description:"Zooms to display the maximum extents of all entities"}},USER:{}},_m={arc:{startPointOrCenter:"Specify start point of arc or",secondPointOrOptions:"Specify second point of arc or",secondPoint:"Specify second point of arc",startPoint:"Specify start point of arc",centerPoint:"Specify center point of arc",endPoint:"Specify end point of arc",endPointOrOptions:"Specify end point of arc or",centerPointOrOptions:"Specify center point of arc",includedAngle:"Specify included angle",chordLength:"Specify chord length",tangentDirection:"Specify tangent direction for start point of arc",radius:"Specify radius of arc",keywords:{center:{display:"Center(C)",local:"Center",global:"Center"},end:{display:"End(E)",local:"End",global:"End"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},chordLength:{display:"chord Length(L)",local:"Chord Length",global:"ChordLength"},direction:{display:"Direction(D)",local:"Direction",global:"Direction"},radius:{display:"Radius(R)",local:"Radius",global:"Radius"}},invalid:{threePoint:"Invalid 3-point arc: points are collinear or cannot define an arc.",center:"Invalid center input: start and end points must lie on the same circle.",angle:"Invalid angle input: included angle must be greater than 0 and less than 360 degrees.",chordLength:"Invalid chord length: value is out of range for the current radius.",direction:"Invalid direction: cannot construct an arc from this tangent direction.",radius:"Invalid radius: the specified radius cannot connect start and end points."}},circle:{center:"Specify the center of circle",centerOrOptions:"Specify center point of circle or",radius:"Specify the radius of circle",radiusOrDiameter:"Specify radius of circle or",diameter:"Specify diameter of circle",twoPointFirst:"Specify first endpoint of circle diameter",twoPointSecond:"Specify second endpoint of circle diameter",threePointFirst:"Specify first point on circle",threePointSecond:"Specify second point on circle",threePointThird:"Specify third point on circle",keywords:{threeP:{display:"3P(3P)",local:"3P",global:"3P"},twoP:{display:"2P(2P)",local:"2P",global:"2P"},diameter:{display:"Diameter(D)",local:"Diameter",global:"Diameter"}}},copy:{basePointOrOptions:"Specify base point or",displacementOrArray:"Specify displacement or",secondPointOrArray:"Specify second point or",modePrompt:"Enter copy mode option",arrayItemCount:"Enter the number of items in the array including the original",arraySecondPointOrFit:"Specify second point or",arrayFitSecondPoint:"Specify second point",keywords:{displacement:{display:"Displacement(D)",local:"Displacement",global:"Displacement"},mode:{display:"Mode(O)",local:"Mode",global:"Mode"},multiple:{display:"Multiple(M)",local:"Multiple",global:"Multiple"},single:{display:"Single(S)",local:"Single",global:"Single"},array:{display:"Array(A)",local:"Array",global:"Array"},fit:{display:"Fit(F)",local:"Fit",global:"Fit"}}},dimlinear:{xLine1Point:"Specify the first extension line origin",xLine2Point:"Specify the second extension line origin",dimLinePoint:"Specify dimension line location"},ellipse:{axisEndpointOrOptions:"Specify axis endpoint of ellipse or",arcAxisEndpointOrCenter:"Specify axis endpoint of elliptical arc or",center:"Specify center of ellipse",firstAxisEndpoint:"Specify endpoint of axis",secondAxisEndpoint:"Specify other endpoint of axis",otherAxisOrRotation:"Specify distance to other axis or",rotationAngle:"Specify rotation angle around major axis",arcStartAngle:"Specify start angle of elliptical arc",arcEndAngle:"Specify end angle of elliptical arc",keywords:{arc:{display:"Arc(A)",local:"Arc",global:"Arc"},center:{display:"Center(C)",local:"Center",global:"Center"},rotation:{display:"Rotation(R)",local:"Rotation",global:"Rotation"}},invalid:{axis:"Invalid axis input: axis length must be greater than 0.",otherAxis:"Invalid other-axis input: distance must be greater than 0.",rotation:"Invalid rotation input: resulting minor axis must be greater than 0."}},hatch:{prompt:"Select boundary object or",pickPoint:"Specify internal point (or press Enter to finish)",select:"Select objects to hatch",patternName:"Enter hatch pattern name",scale:"Specify hatch pattern scale",angle:"Specify hatch pattern angle",style:"Enter hatch style",associative:"Specify associativity",invalidBoundary:"Selected objects do not form a closed boundary.",keywords:{pick:{display:"Pick points(P)",local:"Pick points",global:"PickPoints"},select:{display:"Select objects(S)",local:"Select objects",global:"SelectObjects"},cancel:{display:"Cancel(C)",local:"Cancel",global:"Cancel"},pattern:{display:"Pattern(P)",local:"Pattern",global:"Pattern"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},style:{display:"Style(T)",local:"Style",global:"HatchStyle"},associative:{display:"Associative(AS)",local:"Associative",global:"AssociativeMode"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},outer:{display:"Outer(O)",local:"Outer",global:"Outer"},ignore:{display:"Ignore(I)",local:"Ignore",global:"Ignore"},yes:{display:"Yes(Y)",local:"Yes",global:"Yes"},no:{display:"No(N)",local:"No",global:"No"}}},hideobjects:{hidden:"object(s) hidden",restored:"object(s) restored",nothingToRestore:"No hidden objects to restore"},entout:{longSidePrompt:"Enter preview long side size in pixels",exported:"object preview(s) exported",skipped:"object(s) skipped",failed:{"no-preview-root":"Unable to build preview geometry for the selection","no-bounds":"Unable to compute preview bounds for the selection","capture-failed":"Unable to render the entity preview image","download-failed":"Preview rendered but the PNG download failed"}},layer:{main:"Enter option",listSummary:"Layer list was printed to browser console",emptyInput:"No layer name was entered.",newPrompt:"Enter name for new layer(s)",makePrompt:"Enter name of layer to make current",setPrompt:"Enter name of layer to set current",onPrompt:"Enter layer name(s) to turn on",offPrompt:"Enter layer name(s) to turn off",freezePrompt:"Enter layer name(s) to freeze",thawPrompt:"Enter layer name(s) to thaw",lockPrompt:"Enter layer name(s) to lock",unlockPrompt:"Enter layer name(s) to unlock",colorLayerPrompt:"Enter layer name(s) to change color",colorValuePrompt:"Enter color (ACI 1-255, RGB like 255,0,0, or CSS color name)",invalidColor:"Invalid color input.",descriptionLayerPrompt:"Enter layer name to edit description",descriptionValuePrompt:"Enter new layer description",created:"Created layer count",alreadyExists:"Layer already exists",notFound:"Layer not found",cannotChangeCurrent:"Cannot turn off or freeze the current layer.",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"Make(M)",local:"Make",global:"Make"},set:{display:"Set(S)",local:"Set",global:"Set"},new:{display:"New(N)",local:"New",global:"New"},on:{display:"On(ON)",local:"On",global:"On"},off:{display:"Off(OF)",local:"Off",global:"Off"},color:{display:"Color(C)",local:"Color",global:"Color"},freeze:{display:"Freeze(F)",local:"Freeze",global:"Freeze"},thaw:{display:"Thaw(T)",local:"Thaw",global:"Thaw"},lock:{display:"Lock(L)",local:"Lock",global:"Lock"},unlock:{display:"Unlock(U)",local:"Unlock",global:"Unlock"},description:{display:"Description(D)",local:"Description",global:"Description"}}},layon:{alreadyOn:"All layers are already on.",turnedOn:"Turned on layers"},laycur:{prompt:"Select objects to be changed to the current layer",currentLayerNotFound:"Current layer not found.",noObjects:"No valid objects were selected.",alreadyCurrent:"Selected objects are already on the current layer.",changed:"Changed objects to current layer"},layfrz:{prompt:"Select object on layer to freeze or",invalidSelection:"Invalid object selected.",settingsPrompt:"Enter LAYFRZ setting to change",viewportPrompt:"Specify viewport freeze behavior",blockSelectionPrompt:"Specify nested block selection behavior",vpfreezeFallback:"Current viewer does not support per-viewport layer freeze; using Freeze behavior instead.",nestedSelectionLimited:"Nested block selection settings are stored, but current picking still resolves the top-level entity layer.",layerNotFound:"Layer not found",cannotFreezeCurrent:"Cannot freeze the current layer.",alreadyFrozen:"Layer is already frozen",frozen:"Frozen layer",restored:"Restored layer",nothingToUndo:"There is no LAYFRZ action to undo.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},viewports:{display:"Viewports(V)",local:"Viewports",global:"Viewports"},blockSelection:{display:"Block selection(B)",local:"Block selection",global:"BlockSelection"},freeze:{display:"Freeze(F)",local:"Freeze",global:"Freeze"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"},block:{display:"Block(B)",local:"Block",global:"Block"},entity:{display:"Entity(E)",local:"Entity",global:"Entity"},none:{display:"None(N)",local:"None",global:"None"}}},layiso:{prompt:"Select objects on the layer(s) to be isolated or",settingsPrompt:"Enter setting for layers not isolated",offModePrompt:"Enter off behavior for layers not isolated",noLayers:"No valid layers were selected.",layerNotFound:"Layer not found",isolated:"Isolated layer(s)",affectedLayers:"affected layers",vpfreezeFallback:"Current viewer does not support per-viewport layer freeze; using Off behavior instead.",lockFadeFallback:"Current viewer does not support layer fade display; non-isolated layers will be locked without fade.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},off:{display:"Off(O)",local:"Off",global:"Off"},lockAndFade:{display:"Lock and fade(L)",local:"Lock and fade",global:"LockAndFade"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"}}},layuniso:{noPrevious:"No previous LAYISO layer state to restore.",layerNotFound:"Layer not found",nothingRestored:"No LAYISO layer changes were restored.",restored:"Restored layers"},laythw:{alreadyThawed:"All layers are already thawed.",thawed:"Thawed layers"},laylck:{prompt:"Select an object on the layer to be locked",invalidSelection:"Invalid object selected.",layerNotFound:"Layer not found",alreadyLocked:"Layer is already locked",locked:"Locked layer"},layulk:{prompt:"Select an object on the layer to be unlocked",invalidSelection:"Invalid object selected.",layerNotFound:"Layer not found",alreadyUnlocked:"Layer is already unlocked",unlocked:"Unlocked layer"},layoff:{prompt:"Select object on layer to turn off or",invalidSelection:"Invalid object selected.",settingsPrompt:"Enter LAYOFF setting to change",viewportPrompt:"Specify viewport behavior",blockSelectionPrompt:"Specify nested block selection behavior",vpfreezeFallback:"Current viewer does not support per-viewport layer off; using Off behavior instead.",nestedSelectionLimited:"Nested block selection settings are stored, but current picking still resolves the top-level entity layer.",layerNotFound:"Layer not found",cannotTurnOffCurrent:"Cannot turn off the current layer.",alreadyOff:"Layer is already off",turnedOff:"Turned off layer",restored:"Restored layer",nothingToUndo:"There is no LAYOFF action to undo.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},viewports:{display:"Viewports(V)",local:"Viewports",global:"Viewports"},blockSelection:{display:"Block selection(B)",local:"Block selection",global:"BlockSelection"},off:{display:"Off(O)",local:"Off",global:"Off"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"},block:{display:"Block(B)",local:"Block",global:"Block"},entity:{display:"Entity(E)",local:"Entity",global:"Entity"},none:{display:"None(N)",local:"None",global:"None"}}},layerp:{restored:"Restored previous layer state.",noPreviousState:"There is no previous layer state to restore."},line:{firstPoint:"Specify the first point",firstPointOrContinue:"Specify first point or",nextPoint:"Specify the next point",nextPointWithOptions:"Specify next point or",keywords:{continue:{display:"Continue(C)",local:"Continue",global:"Continue"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"}}},xline:{firstPointOrOptions:"Specify a point or",secondPoint:"Specify second point",throughPoint:"Specify through point",angle:"Enter angle of xline",invalidDirection:"Invalid direction for XLINE.",keywords:{hor:{display:"Hor(H)",local:"Hor",global:"Hor"},ver:{display:"Ver(V)",local:"Ver",global:"Ver"},ang:{display:"Ang(A)",local:"Ang",global:"Ang"}}},ray:{startPoint:"Specify start point",throughPoint:"Specify through point"},mline:{startPointWithOptions:"Specify start point or",nextPointWithOptions:"Specify next point or",justificationPrompt:"Enter justification type",scalePrompt:"Specify mline scale",stylePrompt:"Enter mline style name or [?] for list",styleNotFound:"Mline style not found",styleListHeader:"Loaded mline styles",styleListEmpty:"No mline style is loaded in current drawing.",keywords:{justification:{display:"Justification(J)",local:"Justification",global:"Justification"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},style:{display:"Style(ST)",local:"Style",global:"Style"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},top:{display:"Top(T)",local:"Top",global:"Top"},zero:{display:"Zero(Z)",local:"Zero",global:"Zero"},bottom:{display:"Bottom(B)",local:"Bottom",global:"Bottom"}}},measureAngle:{vertex:"Specify vertex point",arm1:"Specify point on first arm",arm2:"Specify point on second arm"},measureArc:{startPoint:"Specify arc start point",throughPoint:"Specify a point on the arc",endPoint:"Specify arc end point"},measureArea:{firstPoint:"Specify first point",nextPoint:"Specify next point (or press Enter to finish)"},measureDistance:{firstPoint:"Specify first point",secondPoint:"Specify second point"},measurePoint:{point:"Specify point"},measurement:{import:{chooseFile:"Choose a measurement sidecar JSON file"}},markup:{author:"Specify review author (saved for later)",text:{point:"Specify text markup point",content:"Enter markup text"},line:{firstPoint:"Specify first point of line markup",secondPoint:"Specify second point of line markup"},arrow:{firstPoint:"Specify arrow start point",secondPoint:"Specify arrow tip"},cloud:{firstCorner:"Specify first corner of cloud",secondCorner:"Specify opposite corner of cloud"},rect:{firstCorner:"Specify first corner of rectangle",secondCorner:"Specify opposite corner of rectangle"},circle:{center:"Specify center of circle",radius:"Specify radius of circle"},shape:{calloutOn:"[Callout on]",calloutOff:"[Callout off]",calloutAnchor:"Specify callout text location",keywords:{callout:{display:"Callout(C)",local:"Callout",global:"Callout"},noCallout:{display:"NoCallout(N)",local:"NoCallout",global:"NoCallout"}}},highlight:{firstCorner:"Specify first corner of highlight",secondCorner:"Specify opposite corner of highlight"},callout:{tip:"Specify leader tip (arrow end)",anchor:"Specify callout text location",content:"Enter callout text"},stamp:{kind:"Enter stamp id [approved/rejected/revised/for-review/custom]",imageUrl:"Enter custom stamp image URL (optional)",caption:"Enter stamp caption (optional)",point:"Specify stamp insertion point"},import:{chooseFile:"Choose a markup sidecar JSON file"}},move:{basePointOrDisplacement:"Specify base point or",secondPointOrDisplacement:"Specify second point or",displacement:"Specify displacement",keywords:{displacement:{display:"Displacement(D)",local:"Displacement",global:"Displacement"}}},offset:{distance:"Specify offset distance",selectObject:"Select object to offset or press Enter to finish",sidePoint:"Specify point on side to offset",invalidDistance:"Offset distance must be greater than 0.",invalidSelection:"Selected object cannot be offset.",offsetFailed:"Unable to create an offset curve for the specified side."},mtext:{point:"Specify mtext insertion point"},pngout:{boundsFirstCorner:"Specify first corner of bounds",boundsSecondCorner:"Specify opposite corner",longSidePrompt:"Enter long side size in pixels"},imageattach:{insertionPoint:"Specify insertion point:",scale:"Specify scale factor:",rotation:"Specify rotation angle:",invalidScale:"Scale factor must be greater than 0.",decodeFailed:"Failed to read the selected image file."},insert:{blockName:"Enter block name:",insertionPoint:"Specify insertion point:",scale:"Specify scale factor:",rotation:"Specify rotation angle:",invalidScale:"Scale factor must be greater than 0.",invalidBlockName:"Invalid block name.",blockNotFound:"Block not found",xrefNotAllowed:"Cannot insert an external reference with -INSERT."},xattach:{insertionPoint:"Specify insertion point:",scale:"Specify scale factor:",rotation:"Specify rotation angle:",invalidScale:"Scale factor must be greater than 0.",unsupportedFile:"Please select a DWG or DXF file.",loading:"Loading external reference...",loadFailed:"Failed to read the selected drawing file."},point:{point:"Specify a point"},polygon:{numberOfSides:"Enter number of sides",centerOrEdge:"Specify center of polygon or",radiusOrType:"Enter options",edgeStart:"Specify first endpoint of edge",edgeEnd:"Specify second endpoint of edge",keywords:{edge:{display:"Edge(E)",local:"Edge",global:"Edge"},inscribed:{display:"Inscribed in circle(I)",local:"Inscribed in circle",global:"Inscribed"},circumscribed:{display:"Circumscribed about circle(C)",local:"Circumscribed about circle",global:"Circumscribed"}},invalid:{sides:"Invalid number of sides. Enter an integer between 3 and 1024.",radius:"Invalid radius. Radius must be greater than 0.",edge:"Invalid edge. The edge length must be greater than 0."}},polyline:{firstPoint:"Specify the first point",nextPoint:"Specify the next point (or press Enter to finish)",nextPointWithOptions:"Specify next point or",nextPointWithArcOptions:"Specify next point or",keywords:{arc:{display:"Arc(A)",local:"Arc",global:"Arc"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},line:{display:"Line(L)",local:"Line",global:"Line"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},center:{display:"Center(C)",local:"Center",global:"Center"},secondPoint:{display:"Second point(P)",local:"Second point",global:"SecondPoint"},radius:{display:"Radius(R)",local:"Radius",global:"Radius"}},arcAngle:"Specify arc angle",arcCenter:"Specify center point",arcSecondPoint:"Specify second point on arc",arcEndPoint:"Specify arc end point",arcRadius:"Specify arc radius"},rect:{firstPoint:"Specify first corner point",nextPoint:"Specify other corner point",firstPointWithOptions:"Specify first corner point or",otherCornerWithOptions:"Specify other corner point or",chamferFirst:"Specify first chamfer distance",chamferSecond:"Specify second chamfer distance",filletRadius:"Specify fillet radius",segmentWidth:"Specify rectangle line width",elevationValue:"Specify elevation",thicknessValue:"Specify thickness",rotationAngle:"Specify rectangle rotation angle",dimensionLength:"Specify rectangle length",dimensionWidth:"Specify rectangle width",areaValue:"Specify rectangle area",areaLengthOrWidth:"Specify rectangle length",areaSpecifyWidth:"Specify rectangle width",invalidPositive:"Invalid input. Please enter a value greater than 0.",invalidRect:"Unable to create rectangle. Please specify valid corners or dimensions.",thicknessNotSupported:"Rectangle thickness is currently not written to entity data. The thickness setting is ignored.",keywords:{chamfer:{display:"Chamfer(C)",local:"Chamfer",global:"Chamfer"},elevation:{display:"Elevation(E)",local:"Elevation",global:"Elevation"},fillet:{display:"Fillet(F)",local:"Fillet",global:"Fillet"},thickness:{display:"Thickness(T)",local:"Thickness",global:"Thickness"},width:{display:"Width(W)",local:"Width",global:"Width"},area:{display:"Area(A)",local:"Area",global:"Area"},dimensions:{display:"Dimensions(D)",local:"Dimensions",global:"Dimensions"},rotation:{display:"Rotation(R)",local:"Rotation",global:"Rotation"},length:{display:"Length(L)",local:"Length",global:"Length"},rectWidth:{display:"Width(W)",local:"Width",global:"Width"}}},rotate:{basePoint:"Specify base point",rotationAngleOrOptions:"Specify rotation angle or",referenceAngleOrPoints:"Specify reference angle or",firstReferencePoint:"Specify first point of reference angle",secondReferencePoint:"Specify second point",newAngle:"Specify new angle",keywords:{copy:{display:"Copy(C)",local:"Copy",global:"Copy"},reference:{display:"Reference(R)",local:"Reference",global:"Reference"},points:{display:"Points(P)",local:"Points",global:"Points"}},invalid:{referencePoints:"Invalid reference points: points must be different."}},revcloud:{firstCornerOrOptions:"Specify first corner point or",firstCorner:"Specify first corner point",oppositeCorner:"Specify opposite corner",startPoint:"Specify start point",nextPoint:"Specify next point",nextPointOrUndo:"Specify next point or",firstPoint:"Specify first point",guideCursor:"Guide cursor along cloud path (press Enter to finish)",arcLength:"Specify arc length",selectObject:"Select object",style:"Enter revision cloud arc style",reverseDirection:"Reverse direction",invalidArcLength:"Arc length must be greater than 0.",invalidObject:"Selected object cannot be converted to a revision cloud.",keywords:{arcLength:{display:"Arc length(A)",local:"Arc length",global:"ArcLength"},object:{display:"Object(O)",local:"Object",global:"Object"},rectangular:{display:"Rectangular(R)",local:"Rectangular",global:"Rectangular"},polygonal:{display:"Polygonal(P)",local:"Polygonal",global:"Polygonal"},freehand:{display:"Freehand(F)",local:"Freehand",global:"Freehand"},style:{display:"Style(S)",local:"Style",global:"Style"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},calligraphy:{display:"Calligraphy(C)",local:"Calligraphy",global:"Calligraphy"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},yes:{display:"Yes(Y)",local:"Yes",global:"Yes"},no:{display:"No(N)",local:"No",global:"No"}}},sketch:{specifySketch:"Specify sketch or",sketching:"Move the pointer to sketch (click or press Enter to stop)",type:"Enter sketch type",increment:"Specify sketch increment",tolerance:"Specify spline tolerance",firstPoint:"Specify the first point",nextPoint:"Specify the end point",keywords:{type:{display:"Type(T)",local:"Type",global:"Type"},increment:{display:"Increment(I)",local:"Increment",global:"Increment"},tolerance:{display:"toLerance(L)",local:"toLerance",global:"Tolerance"},line:{display:"Lines(L)",local:"Lines",global:"Lines"},polyline:{display:"Polyline(P)",local:"Polyline",global:"Polyline"},spline:{display:"Spline(S)",local:"Spline",global:"Spline"}}},spline:{firstPoint:"Specify the first point",nextPoint:"Specify the next point (or press Enter to finish)",firstPointWithOptions:"Specify first point or",nextPointWithFitOptions:"Specify next point or",nextPointWithCvOptions:"Specify next control vertex or",methodPrompt:"Enter spline creation method",knotsPrompt:"Enter knot parameterization",degreePrompt:"Specify spline degree",keywords:{method:{display:"Method(M)",local:"Method",global:"Method"},fit:{display:"Fit(F)",local:"Fit",global:"Fit"},cv:{display:"CV(C)",local:"CV",global:"CV"},knots:{display:"Knots(K)",local:"Knots",global:"Knots"},degree:{display:"Degree(D)",local:"Degree",global:"Degree"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},chord:{display:"Chord(C)",local:"Chord",global:"Chord"},sqrtChord:{display:"Sqrt chord(S)",local:"Sqrt chord",global:"SqrtChord"},uniform:{display:"Uniform(U)",local:"Uniform",global:"Uniform"}}},sysvar:{prompt:"Please input new value"},zoom:{mainPrompt:"Specify corner of window or",firstCorner:"Specify first corner",secondCorner:"Specify opposite corner",centerPoint:"Specify center point",heightOrScale:"Enter height or scale factor (nX or nXP)",scaleFactor:"Enter scale factor (nX or nXP)",keywords:{all:{display:"All(A)",local:"All",global:"All"},center:{display:"Center(C)",local:"Center",global:"Center"},extents:{display:"Extents(E)",local:"Extents",global:"Extents"},previous:{display:"Previous(P)",local:"Previous",global:"Previous"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},window:{display:"Window(W)",local:"Window",global:"Window"}}},chtml:{exportInvisibleLayers:"Export invisible layers",initialView:"Initial view when opening HTML",viewerMode:"Offline viewer mode",keywords:{yes:{display:"Yes(Y)",local:"Yes",global:"Yes"},no:{display:"No(N)",local:"No",global:"No"},extents:{display:"Extents(E)",local:"Extents",global:"Extents"},current:{display:"Current(C)",local:"Current",global:"Current"},view:{display:"View(V)",local:"View",global:"View"},measure:{display:"Measure(M)",local:"Measure",global:"Measure"}}}},Em={document:{untitled:"Untitled"},commandLine:{noLast:"(no last command)",unknownCommand:"Unknown command",executed:"Executed command",showHistory:"Show command history",placeholder:"Type command",showMessages:"Show message history",canceled:"*Canceled*",noHistory:"(no history)",invalidInput:"Invalid input.",close:"Close command line"},inputManager:{firstCorner:"Specify the first corner or",secondCorner:"Specify the second corner or"},message:{fetchingDrawingFile:"Fetching file ...",exportingDxf:"Exporting DXF ...",exportingEntityPreview:"Exporting image ...",collectingMemoryProfile:"Analyzing memory ...",fontCached:"Font cached successfully",fontCacheFailed:"Failed to cache font"},progress:{start:"Start parsing file ...",parse:"Parsing file ...",font:"Downloading fonts needed by this drawing ...",ltype:"Parsing line types ...",style:"Parsing text syltes ...",dimstyle:"Parsing dimension styles ...",layer:"Parsing layers ...",vport:"Parsing viewports ...",blockrecord:"Parsing block record ...",header:"Parsing header ...",block:"Parsing blocks ...",entity:"Parsing entities ...",object:"Parsing named dictionaries ...",rendering:"Rendering drawing ...",end:"Finished!"},about:{title:"About",close:"Close",product:"CAD Viewer",tagline:"High-performance web CAD viewer for DWG and DXF drawings.",website:"Website",docs:"Documentation",repository:"GitHub",copyright:"© {year} mlightcad. All rights reserved.",ok:"OK"},drawStyle:{color:"Color",lineWeight:"Lineweight",fontSize:"Text height"}},Lm={ACAD:{"-hatch":{description:"Şerit menüsü olmadan komut satırı seçenekleriyle tarama dolgular oluşturur"},"-layer":{description:"Komut satırı seçenekleriyle katmanları yönetir"},about:{description:"mlightcad hakkında bilgi gösterir"},acadver:{description:"Çizim veritabanı sürüm tanımlayıcısını saklar (salt okunur)"},angbase:{description:"Geçerli KKS'ye göre 0 açı temel yönünü ayarlar"},angdir:{description:"Pozitif açıların saat yönünde mi yoksa saat yönünün tersine mi ölçüleceğini ayarlar"},arc:{description:"Bir yay oluşturur"},aunits:{description:"Açılar için görüntüleme biçimini ayarlar"},auprec:{description:"AUNITS ile birlikte kullanılan, açılar için görüntüleme hassasiyetini ayarlar"},cdxf:{description:"Geçerli çizimi DXF olarak dışa aktarır"},cpdf:{description:"Geçerli çizimi PDF olarak dışa aktarır"},cecolor:{description:"Yeni oluşturulan nesneler için geçerli varsayılan rengi ayarlar"},celtscale:{description:"Yeni oluşturulan nesneler için çizgi tipi ölçek faktörünü denetler"},celtype:{description:"Yeni oluşturulan nesneler için çizgi tipini ayarlar"},celweight:{description:"Yeni oluşturulan nesneler için varsayılan çizgi kalınlığını ayarlar"},cetransparency:{description:"Yeni oluşturulan nesneler için saydamlığı ayarlar"},cachefont:{description:"Metin işleme için yerel bir yazı tipi dosyasını IndexedDB'ye önbelleğe alır"},circle:{description:"Merkez ve yarıçapa göre bir daire oluşturur"},clayer:{description:"Yeni nesneler ve düzenleme işlemleri için geçerli katmanı ayarlar"},cmleaderstyle:{description:"Geçerli çoklu lider stilinin adını ayarlar"},cmlscale:{description:"Bir çoklu çizginin genel genişliğini denetler"},cmlstyle:{description:"Geçerli çoklu çizgi stilinin adını ayarlar"},colortheme:{description:"Kullanıcı arayüzünün renk temasını denetler (koyu veya açık)"},copy:{description:"Seçili varlıkları klonlayarak yeni konumlara kopyalar",prompt:"Varlıkları seçin"},csvg:{description:"Geçerli çizimi SVG'ye dönüştürür"},chtml:{description:"Geçerli çizimi bağımsız, çevrimdışı bir HTML dosyasına dışa aktarır"},"-chtml":{description:"Komut satırı seçeneklerini kullanarak geçerli çizimi HTML'e dışa aktarır"},dimlinear:{description:"Doğrusal ölçülendirmeler oluşturur"},dimstyle:{description:"Geçerli ölçülendirme stilinin adını ayarlar"},dwgname:{description:"Geçerli çizim dosyasının adını saklar (salt okunur)"},loginname:{description:"Kullanıcının oturum açma adını görüntüler (salt okunur)"},dynmode:{description:"İmleçteki Dinamik Girdi ayarlarını denetler"},dynprompt:{description:"Dinamik Girdi araç ipuçlarında istemlerin görüntülenmesini denetler"},ellipse:{description:"Eksen uç noktalarına veya merkeze göre bir elips veya eliptik yay oluşturur"},erase:{description:"Seçili varlıkları çizimden siler",prompt:"Varlıkları seçin"},extmax:{description:"Model alanı çizim kapsamının sağ üst köşesini saklar (salt okunur)"},extmin:{description:"Model alanı çizim kapsamının sol alt köşesini saklar (salt okunur)"},entout:{description:"Seçili varlıklar için birleştirilmiş bir önizleme görüntüsü dışa aktarır",prompt:"Varlıkları seçin"},hideobjects:{description:"Seçili nesnelerin görüntülenmesini geçici olarak gizler",prompt:"Nesneleri seçin"},imageattach:{description:"Geçerli çizime harici başvuru olarak bir raster görüntü ekler"},"-insert":{description:"Bir blok tanımını geçerli çizime ekler (komut satırı)"},xattach:{description:"Geçerli çizime harici başvuru olarak bir DWG veya DXF çizimi ekler"},gripcolor:{description:"Seçili nesneler üzerinde görüntülenen seçilmemiş tutamaçların rengini ayarlar"},griphot:{description:"Seçili (sıcak) tutamaçların rengini ayarlar"},gripobjlimit:{description:"Seçim kümesi belirtilen nesne sayısını aştığında tutamaç görüntülenmesini engeller (0 = sınır yok)"},grips:{description:"Seçili nesnelerde tutamaçların görüntülenip görüntülenmeyeceğini denetler"},gripsize:{description:"Tutamaç kutularının piksel cinsinden boyutunu ayarlar"},hatch:{description:"Kapalı bir alanı veya seçili nesneleri bir tarama deseniyle doldurur"},ipdf:{description:"Bir PDF dosyasından vektör geometrisini içe aktarır"},hpang:{description:"Yeni oluşturulan tarama desenleri için varsayılan açıyı radyan cinsinden ayarlar"},hpassoc:{description:"Yeni oluşturulan taramaların ilişkisel olup olmayacağını denetler"},hpbackgroundcolor:{description:"Yeni oluşturulan tarama desenleri için varsayılan arka plan rengini ayarlar"},hpcolor:{description:"Yeni oluşturulan taramalar için varsayılan rengi ayarlar"},hpdouble:{description:"Kullanıcı tanımlı tarama desenlerinin ikiye katlanıp katlanmayacağını denetler"},hpislanddetection:{description:"Yeni oluşturulan tarama sınırları içindeki adaların nasıl işleneceğini denetler"},hplayer:{description:"Yeni oluşturulan taramalar ve dolgular için varsayılan katmanı ayarlar"},hpname:{description:"Bu oturumda yeni oluşturulan taramalar için varsayılan desen adını ayarlar"},hpscale:{description:"Yeni oluşturulan tarama desenleri için varsayılan ölçek faktörünü ayarlar"},hpseparate:{description:"Birden çok sınır için tek mi yoksa ayrı tarama nesneleri mi oluşturulacağını denetler"},hptransparency:{description:"Yeni oluşturulan taramalar ve dolgular için varsayılan saydamlığı ayarlar"},insunits:{description:"Eklenen blokların, görüntülerin veya dış referansların otomatik ölçeklendirilmesi için çizim birimlerini belirtir"},laycur:{description:"Seçili nesnelerin katman özelliğini geçerli katman olarak değiştirir",prompt:"Geçerli katmana değiştirilecek nesneleri seçin"},laydel:{description:"Bir katmanı ve o katmandaki tüm nesneleri siler"},layerclose:{description:"Katman Özellikleri Yöneticisi'ni kapatır"},layerp:{description:"Katman ayarlarında yapılan son değişikliği veya değişiklik kümesini geri alır"},layfrz:{description:"Seçili nesnelerin katmanını dondurur",prompt:"Dondurulacak katmandaki nesneyi seçin"},layiso:{description:"Seçili nesnelerin katmanlarını izole eder",prompt:"İzole edilecek katmanlardaki nesneleri seçin"},laylck:{description:"Seçili nesnelerin katmanını kilitler",prompt:"Kilitlenecek katmandaki nesneyi seçin"},layoff:{description:"Seçili nesnelerin katmanını kapatır",prompt:"Kapatılacak katmandaki nesneyi seçin"},layon:{description:"Çizimdeki tüm katmanları açar"},laythw:{description:"Çizimdeki tüm donmuş katmanları çözer"},layulk:{description:"Seçili nesnelerin katmanının kilidini açar",prompt:"Kilidi açılacak katmandaki nesneyi seçin"},layuniso:{description:"LAYISO tarafından gizlenen veya kilitlenen katmanları geri yükler"},line:{description:"Noktalar arasında düz çizgi parçaları çizer"},log:{description:"Hata ayıklama bilgilerini konsola kaydeder"},ltscale:{description:"Çizim için genel çizgi tipi ölçek faktörünü ayarlar"},lunits:{description:"Koordinatlar ve mesafeler için görüntüleme biçimini ayarlar"},luprec:{description:"LUNITS ile birlikte kullanılan, doğrusal birimler için görüntüleme hassasiyetini ayarlar"},lwdisplay:{description:"Çizgi kalınlıklarının çizimde görüntülenip görüntülenmeyeceğini denetler"},clearmeasurements:{description:"Geçerli yerleşimdeki tüm ölçümleri kaldırır"},measurementvis:{description:"Geçerli yerleşimdeki ölçümleri gösterir veya gizler"},measurementexport:{description:"Ölçümleri sidecar JSON dosyasına dışa aktarır"},measurementimport:{description:"Ölçümleri sidecar JSON dosyasından içe aktarır"},measurearea:{description:"Seçili nesnelerin veya noktaların alanını ve çevresini hesaplar"},measureangle:{description:"İki çizgi veya üç nokta arasındaki açıyı ölçer"},measurearc:{description:"Bir yay parçasının uzunluğunu ölçer"},measuredistance:{description:"İki nokta arasındaki mesafeyi ve delta değerlerini ölçer"},measurepoint:{description:"Seçilen noktanın X/Y koordinatlarını ölçer"},measurement:{description:"Çizimin İngiliz (emperyal) birimlerini mi yoksa metrik birimleri mi kullanacağını ayarlar"},measurementcolor:{description:"Ölçüm katmanları için kullanılan rengi ayarlar"},modelbkcolor:{description:"Model alanı çizim alanının arka plan rengini ayarlar"},mline:{description:"Tek bir çoklu çizgi nesnesi olarak birden çok paralel çizgi oluşturur"},move:{description:"Seçili varlıkları bir yer değiştirme vektörüne göre taşır",prompt:"Varlıkları seçin"},offset:{description:"Belirtilen bir mesafede paralel eğriler, çoklu çizgiler veya daireler oluşturur"},mtext:{description:"Bir çoklu metin varlığı oluşturur"},open:{description:"Mevcut bir çizim dosyasını açar"},openprof:{description:"Dosya açma aşaması zamanlama profillerinin konsola kaydedilip kaydedilmeyeceğini denetler"},openperf:{description:"Son çizim açılışının zamanlamalarını Open Performance paletinde gösterir"},orthomode:{description:"İmleç hareketini yatay veya dikey eksenle sınırlar"},osmode:{description:"Bit kodu değeri kullanarak çalışan Nesne Yakalama modlarını ayarlar"},pan:{description:"Görüntüleme yönünü veya büyütmeyi değiştirmeden görünümü kaydırır"},paperbkcolor:{description:"Kağıt alanı (düzen) çizim alanının arka plan rengini ayarlar"},pdmode:{description:"POINT varlıklarının nasıl görüntüleneceğini denetler"},pdsize:{description:"POINT varlıkları için görüntüleme boyutunu ayarlar"},pickbox:{description:"Nesneleri seçmek için kullanılan seçim kutusunun boyutunu (piksel cinsinden) ayarlar"},pline:{description:"Birden çok nokta belirterek bir çoklu çizgi oluşturur"},pngout:{description:"PNG olarak dışa aktarır"},point:{description:"Noktalar oluşturur"},polaraddang:{description:"Ek kutupsal izleme açılarını noktalı virgülle ayrılmış liste olarak saklar"},polarang:{description:"Kutupsal izleme için kutupsal açı artımını ayarlar"},polarmode:{description:"Kutupsal ve nesne yakalama izleme ayarlarını denetler"},polygon:{description:"Merkez/yarıçapa veya bir çokgen kenarına göre düzgün bir çokgen oluşturur"},qnew:{description:"Yeni bir çizim başlatır"},ray:{description:"Bir noktadan başlayıp sonsuza uzanan bir ışın oluşturur"},rectang:{description:"İki karşıt köşe belirterek bir dikdörtgen oluşturur"},regen:{description:"Geçerli çizimi yeniden çizer"},revcloud:{description:"Revizyon bulutu oluşturur veya değiştirir"},markuptext:{description:"Metin işareti yerleştirir"},markupline:{description:"Çizgi işareti oluşturur"},markuparrow:{description:"Ok işareti oluşturur"},markupcloud:{description:"Revizyon bulutu işareti oluşturur"},markuprect:{description:"Dikdörtgen işareti oluşturur"},markupcircle:{description:"Daire işareti oluşturur"},markuphighlight:{description:"Vurgu dikdörtgeni işareti oluşturur"},markupcallout:{description:"Çağrı notu oluşturur: önce lider ucunu, sonra metin kutusunu belirtin, ardından metni girin"},markupstamp:{description:"Damga veya özel sembol yerleştirir"},markupvis:{description:"İşaretleri gösterir veya gizler"},clearmarkups:{description:"Geçerli yerleşimdeki tüm işaretleri temizler"},markupexport:{description:"İşaretleri sidecar JSON dosyasına dışa aktarır"},markupimport:{description:"İşaretleri sidecar JSON dosyasından içe aktarır"},markuppanel:{description:"İşaret paletini açar"},rotate:{description:"Seçili varlıkları bir taban noktası etrafında döndürür",prompt:"Varlıkları seçin"},select:{description:"Varlıkları seçer"},shortcutmenu:{description:"Çizim alanındaki kısayol menülerinin kullanılabilirliğini denetler"},sketch:{description:"Bir dizi serbest el çizgi parçası oluşturur"},spline:{description:"Kontrol noktaları belirterek düzgün bir spline eğrisi oluşturur"},textstyle:{description:"Geçerli metin stilinin adını ayarlar"},unitmode:{description:"LUNITS Mimari veya Kesirli olduğunda koordinatların kesirli görüntülenmesini denetler"},switchbg:{description:"Çizim alanı arka planını beyaz ve siyah arasında değiştirir"},unisolateobjects:{description:"HIDEOBJECTS tarafından gizlenen tüm nesneleri yeniden görüntüler"},undo:{description:"Son veritabanı düzenleme işlemini geri alır",nothingToUndo:"Geri alınacak işlem yok."},redo:{description:"Geri alınan son veritabanı düzenleme işlemini yineler",nothingToRedo:"Yinelenecek işlem yok."},xline:{description:"Her iki yönde de sonsuza uzanan bir yapı çizgisi oluşturur"},zoom:{description:"Tüm varlıkların maksimum sınırlarını görüntülemek için yakınlaştırır"}},USER:{}},Tm={arc:{startPointOrCenter:"Yayın başlangıç noktasını belirtin veya",secondPointOrOptions:"Yayın ikinci noktasını belirtin veya",secondPoint:"Yayın ikinci noktasını belirtin",startPoint:"Yayın başlangıç noktasını belirtin",centerPoint:"Yayın merkez noktasını belirtin",endPoint:"Yayın bitiş noktasını belirtin",endPointOrOptions:"Yayın bitiş noktasını belirtin veya",centerPointOrOptions:"Yayın merkez noktasını belirtin",includedAngle:"İç açıyı belirtin",chordLength:"Kiriş uzunluğunu belirtin",tangentDirection:"Yayın başlangıç noktası için teğet yönünü belirtin",radius:"Yayın yarıçapını belirtin",keywords:{center:{display:"Merkez(M)",local:"Merkez",global:"Center"},end:{display:"Bitiş(B)",local:"Bitiş",global:"End"},angle:{display:"Açı(A)",local:"Açı",global:"Angle"},chordLength:{display:"kiriş Uzunluğu(U)",local:"Kiriş Uzunluğu",global:"ChordLength"},direction:{display:"Yön(Y)",local:"Yön",global:"Direction"},radius:{display:"Yarıçap(R)",local:"Yarıçap",global:"Radius"}},invalid:{threePoint:"Geçersiz 3 noktalı yay: noktalar aynı doğru üzerinde veya bir yay tanımlayamıyor.",center:"Geçersiz merkez girişi: başlangıç ve bitiş noktaları aynı çember üzerinde olmalıdır.",angle:"Geçersiz açı girişi: iç açı 0 dereceden büyük ve 360 dereceden küçük olmalıdır.",chordLength:"Geçersiz kiriş uzunluğu: değer mevcut yarıçap için geçerli aralığın dışında.",direction:"Geçersiz yön: bu teğet yönünden bir yay oluşturulamıyor.",radius:"Geçersiz yarıçap: belirtilen yarıçap başlangıç ve bitiş noktalarını birleştiremiyor."}},circle:{center:"Çemberin merkezini belirtin",centerOrOptions:"Çemberin merkez noktasını belirtin veya",radius:"Çemberin yarıçapını belirtin",radiusOrDiameter:"Çemberin yarıçapını belirtin veya",diameter:"Çemberin çapını belirtin",twoPointFirst:"Çember çapının ilk uç noktasını belirtin",twoPointSecond:"Çember çapının ikinci uç noktasını belirtin",threePointFirst:"Çember üzerindeki ilk noktayı belirtin",threePointSecond:"Çember üzerindeki ikinci noktayı belirtin",threePointThird:"Çember üzerindeki üçüncü noktayı belirtin",keywords:{threeP:{display:"3N(3N)",local:"3N",global:"3P"},twoP:{display:"2N(2N)",local:"2N",global:"2P"},diameter:{display:"Çap(Ç)",local:"Çap",global:"Diameter"}}},copy:{basePointOrOptions:"Temel noktayı belirtin veya",displacementOrArray:"Yer değiştirmeyi belirtin veya",secondPointOrArray:"İkinci noktayı belirtin veya",modePrompt:"Kopyalama modu seçeneğini girin",arrayItemCount:"Orijinal dahil dizideki öğe sayısını girin",arraySecondPointOrFit:"İkinci noktayı belirtin veya",arrayFitSecondPoint:"İkinci noktayı belirtin",keywords:{displacement:{display:"Yer değiştirme(Y)",local:"Yer değiştirme",global:"Displacement"},mode:{display:"Mod(O)",local:"Mod",global:"Mode"},multiple:{display:"Çoklu(Ç)",local:"Çoklu",global:"Multiple"},single:{display:"Tekli(T)",local:"Tekli",global:"Single"},array:{display:"Dizi(D)",local:"Dizi",global:"Array"},fit:{display:"Uydur(U)",local:"Uydur",global:"Fit"}}},dimlinear:{xLine1Point:"İlk uzatma çizgisinin başlangıç noktasını belirtin",xLine2Point:"İkinci uzatma çizgisinin başlangıç noktasını belirtin",dimLinePoint:"Ölçü çizgisi konumunu belirtin"},ellipse:{axisEndpointOrOptions:"Elipsin eksen uç noktasını belirtin veya",arcAxisEndpointOrCenter:"Eliptik yayın eksen uç noktasını belirtin veya",center:"Elipsin merkezini belirtin",firstAxisEndpoint:"Eksenin uç noktasını belirtin",secondAxisEndpoint:"Eksenin diğer uç noktasını belirtin",otherAxisOrRotation:"Diğer eksene olan mesafeyi belirtin veya",rotationAngle:"Ana eksen etrafındaki döndürme açısını belirtin",arcStartAngle:"Eliptik yayın başlangıç açısını belirtin",arcEndAngle:"Eliptik yayın bitiş açısını belirtin",keywords:{arc:{display:"Yay(Y)",local:"Yay",global:"Arc"},center:{display:"Merkez(M)",local:"Merkez",global:"Center"},rotation:{display:"Döndürme(D)",local:"Döndürme",global:"Rotation"}},invalid:{axis:"Geçersiz eksen girişi: eksen uzunluğu 0'dan büyük olmalıdır.",otherAxis:"Geçersiz diğer eksen girişi: mesafe 0'dan büyük olmalıdır.",rotation:"Geçersiz döndürme girişi: elde edilen küçük eksen 0'dan büyük olmalıdır."}},hatch:{prompt:"Sınır nesnesini seçin veya",pickPoint:"İç noktayı belirtin (bitirmek için Enter'a basın)",select:"Tarama yapılacak nesneleri seçin",patternName:"Tarama deseni adını girin",scale:"Tarama deseni ölçeğini belirtin",angle:"Tarama deseni açısını belirtin",style:"Tarama stilini girin",associative:"İlişkiselliği belirtin",invalidBoundary:"Seçilen nesneler kapalı bir sınır oluşturmuyor.",keywords:{pick:{display:"Nokta seç(N)",local:"Nokta seç",global:"PickPoints"},select:{display:"Nesne seç(S)",local:"Nesne seç",global:"SelectObjects"},cancel:{display:"İptal(İ)",local:"İptal",global:"Cancel"},pattern:{display:"Desen(D)",local:"Desen",global:"Pattern"},scale:{display:"Ölçek(Ö)",local:"Ölçek",global:"Scale"},angle:{display:"Açı(A)",local:"Açı",global:"Angle"},style:{display:"Stil(T)",local:"Stil",global:"HatchStyle"},associative:{display:"İlişkisel(İL)",local:"İlişkisel",global:"AssociativeMode"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},outer:{display:"Dış(D)",local:"Dış",global:"Outer"},ignore:{display:"Yoksay(Y)",local:"Yoksay",global:"Ignore"},yes:{display:"Evet(E)",local:"Evet",global:"Yes"},no:{display:"Hayır(H)",local:"Hayır",global:"No"}}},hideobjects:{hidden:"nesne gizlendi",restored:"nesne geri yüklendi",nothingToRestore:"Geri yüklenecek gizli nesne yok"},entout:{longSidePrompt:"Önizleme uzun kenar boyutunu piksel olarak girin",exported:"nesne önizlemesi dışa aktarıldı",skipped:"nesne atlandı",failed:{"no-preview-root":"Seçim için önizleme geometrisi oluşturulamadı","no-bounds":"Seçim için önizleme sınırları hesaplanamadı","capture-failed":"Nesne önizleme görüntüsü oluşturulamadı","download-failed":"Önizleme oluşturuldu ancak PNG indirmesi başarısız oldu"}},layer:{main:"Seçenek girin",listSummary:"Katman listesi tarayıcı konsoluna yazdırıldı",emptyInput:"Katman adı girilmedi.",newPrompt:"Yeni katman(lar) için ad girin",makePrompt:"Geçerli yapılacak katmanın adını girin",setPrompt:"Geçerli olarak ayarlanacak katmanın adını girin",onPrompt:"Açılacak katman ad(lar)ını girin",offPrompt:"Kapatılacak katman ad(lar)ını girin",freezePrompt:"Dondurulacak katman ad(lar)ını girin",thawPrompt:"Çözülecek katman ad(lar)ını girin",lockPrompt:"Kilitlenecek katman ad(lar)ını girin",unlockPrompt:"Kilidi açılacak katman ad(lar)ını girin",colorLayerPrompt:"Rengi değiştirilecek katman ad(lar)ını girin",colorValuePrompt:"Renk girin (ACI 1-255, 255,0,0 gibi RGB veya CSS renk adı)",invalidColor:"Geçersiz renk girişi.",descriptionLayerPrompt:"Açıklaması düzenlenecek katman adını girin",descriptionValuePrompt:"Yeni katman açıklamasını girin",created:"Oluşturulan katman sayısı",alreadyExists:"Katman zaten mevcut",notFound:"Katman bulunamadı",cannotChangeCurrent:"Geçerli katman kapatılamaz veya dondurulamaz.",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"Yap(Y)",local:"Yap",global:"Make"},set:{display:"Ayarla(A)",local:"Ayarla",global:"Set"},new:{display:"Yeni(Y)",local:"Yeni",global:"New"},on:{display:"Aç(A)",local:"Aç",global:"On"},off:{display:"Kapat(K)",local:"Kapat",global:"Off"},color:{display:"Renk(R)",local:"Renk",global:"Color"},freeze:{display:"Dondur(D)",local:"Dondur",global:"Freeze"},thaw:{display:"Çöz(Ç)",local:"Çöz",global:"Thaw"},lock:{display:"Kilitle(K)",local:"Kilitle",global:"Lock"},unlock:{display:"Kilidi aç(A)",local:"Kilidi aç",global:"Unlock"},description:{display:"Açıklama(A)",local:"Açıklama",global:"Description"}}},layon:{alreadyOn:"Tüm katmanlar zaten açık.",turnedOn:"Açılan katmanlar"},laycur:{prompt:"Geçerli katmana değiştirilecek nesneleri seçin",currentLayerNotFound:"Geçerli katman bulunamadı.",noObjects:"Geçerli nesne seçilmedi.",alreadyCurrent:"Seçilen nesneler zaten geçerli katmanda.",changed:"Geçerli katmana değiştirilen nesneler"},layfrz:{prompt:"Dondurulacak katmandaki nesneyi seçin veya",invalidSelection:"Geçersiz nesne seçildi.",settingsPrompt:"Değiştirilecek LAYFRZ ayarını girin",viewportPrompt:"Görüntü penceresi dondurma davranışını belirtin",blockSelectionPrompt:"İç içe blok seçim davranışını belirtin",vpfreezeFallback:"Mevcut görüntüleyici, görüntü penceresi başına katman dondurmayı desteklemiyor; bunun yerine Dondur davranışı kullanılıyor.",nestedSelectionLimited:"İç içe blok seçim ayarları kaydedildi, ancak mevcut seçim işlemi yine de üst düzey nesnenin katmanını çözümlüyor.",layerNotFound:"Katman bulunamadı",cannotFreezeCurrent:"Geçerli katman dondurulamaz.",alreadyFrozen:"Katman zaten donuk",frozen:"Dondurulan katman",restored:"Geri yüklenen katman",nothingToUndo:"Geri alınacak bir LAYFRZ işlemi yok.",keywords:{settings:{display:"Ayarlar(A)",local:"Ayarlar",global:"Settings"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},viewports:{display:"Görüntü pencereleri(G)",local:"Görüntü pencereleri",global:"Viewports"},blockSelection:{display:"Blok seçimi(B)",local:"Blok seçimi",global:"BlockSelection"},freeze:{display:"Dondur(D)",local:"Dondur",global:"Freeze"},vpfreeze:{display:"Görüntü dondur(V)",local:"Görüntü dondur",global:"Vpfreeze"},block:{display:"Blok(B)",local:"Blok",global:"Block"},entity:{display:"Nesne(N)",local:"Nesne",global:"Entity"},none:{display:"Hiçbiri(H)",local:"Hiçbiri",global:"None"}}},layiso:{prompt:"İzole edilecek katman(lar)daki nesneleri seçin veya",settingsPrompt:"İzole edilmeyen katmanlar için ayarı girin",offModePrompt:"İzole edilmeyen katmanlar için kapatma davranışını girin",noLayers:"Geçerli katman seçilmedi.",layerNotFound:"Katman bulunamadı",isolated:"İzole edilen katman(lar)",affectedLayers:"etkilenen katmanlar",vpfreezeFallback:"Mevcut görüntüleyici, görüntü penceresi başına katman dondurmayı desteklemiyor; bunun yerine Kapat davranışı kullanılıyor.",lockFadeFallback:"Mevcut görüntüleyici katman solma görüntüsünü desteklemiyor; izole edilmeyen katmanlar solma olmadan kilitlenecek.",keywords:{settings:{display:"Ayarlar(A)",local:"Ayarlar",global:"Settings"},off:{display:"Kapat(K)",local:"Kapat",global:"Off"},lockAndFade:{display:"Kilitle ve soldur(K)",local:"Kilitle ve soldur",global:"LockAndFade"},vpfreeze:{display:"Görüntü dondur(V)",local:"Görüntü dondur",global:"Vpfreeze"}}},layuniso:{noPrevious:"Geri yüklenecek önceki LAYISO katman durumu yok.",layerNotFound:"Katman bulunamadı",nothingRestored:"Hiçbir LAYISO katman değişikliği geri yüklenmedi.",restored:"Geri yüklenen katmanlar"},laythw:{alreadyThawed:"Tüm katmanlar zaten çözülmüş.",thawed:"Çözülen katmanlar"},laylck:{prompt:"Kilitlenecek katmandaki bir nesneyi seçin",invalidSelection:"Geçersiz nesne seçildi.",layerNotFound:"Katman bulunamadı",alreadyLocked:"Katman zaten kilitli",locked:"Kilitlenen katman"},layulk:{prompt:"Kilidi açılacak katmandaki bir nesneyi seçin",invalidSelection:"Geçersiz nesne seçildi.",layerNotFound:"Katman bulunamadı",alreadyUnlocked:"Katmanın kilidi zaten açık",unlocked:"Kilidi açılan katman"},layoff:{prompt:"Kapatılacak katmandaki nesneyi seçin veya",invalidSelection:"Geçersiz nesne seçildi.",settingsPrompt:"Değiştirilecek LAYOFF ayarını girin",viewportPrompt:"Görüntü penceresi davranışını belirtin",blockSelectionPrompt:"İç içe blok seçim davranışını belirtin",vpfreezeFallback:"Mevcut görüntüleyici, görüntü penceresi başına katman kapatmayı desteklemiyor; bunun yerine Kapat davranışı kullanılıyor.",nestedSelectionLimited:"İç içe blok seçim ayarları kaydedildi, ancak mevcut seçim işlemi yine de üst düzey nesnenin katmanını çözümlüyor.",layerNotFound:"Katman bulunamadı",cannotTurnOffCurrent:"Geçerli katman kapatılamaz.",alreadyOff:"Katman zaten kapalı",turnedOff:"Kapatılan katman",restored:"Geri yüklenen katman",nothingToUndo:"Geri alınacak bir LAYOFF işlemi yok.",keywords:{settings:{display:"Ayarlar(A)",local:"Ayarlar",global:"Settings"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},viewports:{display:"Görüntü pencereleri(G)",local:"Görüntü pencereleri",global:"Viewports"},blockSelection:{display:"Blok seçimi(B)",local:"Blok seçimi",global:"BlockSelection"},off:{display:"Kapat(K)",local:"Kapat",global:"Off"},vpfreeze:{display:"Görüntü dondur(V)",local:"Görüntü dondur",global:"Vpfreeze"},block:{display:"Blok(B)",local:"Blok",global:"Block"},entity:{display:"Nesne(N)",local:"Nesne",global:"Entity"},none:{display:"Hiçbiri(H)",local:"Hiçbiri",global:"None"}}},layerp:{restored:"Önceki katman durumu geri yüklendi.",noPreviousState:"Geri yüklenecek önceki bir katman durumu yok."},line:{firstPoint:"İlk noktayı belirtin",firstPointOrContinue:"İlk noktayı belirtin veya",nextPoint:"Sonraki noktayı belirtin",nextPointWithOptions:"Sonraki noktayı belirtin veya",keywords:{continue:{display:"Devam et(D)",local:"Devam et",global:"Continue"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},close:{display:"Kapat(K)",local:"Kapat",global:"Close"}}},xline:{firstPointOrOptions:"Bir nokta belirtin veya",secondPoint:"İkinci noktayı belirtin",throughPoint:"Geçiş noktasını belirtin",angle:"Sonsuz doğru açısını girin",invalidDirection:"XLINE için geçersiz yön.",keywords:{hor:{display:"Yatay(Y)",local:"Yatay",global:"Hor"},ver:{display:"Dikey(D)",local:"Dikey",global:"Ver"},ang:{display:"Açı(A)",local:"Açı",global:"Ang"}}},ray:{startPoint:"Başlangıç noktasını belirtin",throughPoint:"Geçiş noktasını belirtin"},mline:{startPointWithOptions:"Başlangıç noktasını belirtin veya",nextPointWithOptions:"Sonraki noktayı belirtin veya",justificationPrompt:"Hizalama türünü girin",scalePrompt:"Çoklu çizgi ölçeğini belirtin",stylePrompt:"Çoklu çizgi stil adını girin veya liste için [?]",styleNotFound:"Çoklu çizgi stili bulunamadı",styleListHeader:"Yüklenen çoklu çizgi stilleri",styleListEmpty:"Mevcut çizimde yüklü çoklu çizgi stili yok.",keywords:{justification:{display:"Hizalama(H)",local:"Hizalama",global:"Justification"},scale:{display:"Ölçek(Ö)",local:"Ölçek",global:"Scale"},style:{display:"Stil(ST)",local:"Stil",global:"Style"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},close:{display:"Kapat(K)",local:"Kapat",global:"Close"},top:{display:"Üst(Ü)",local:"Üst",global:"Top"},zero:{display:"Sıfır(S)",local:"Sıfır",global:"Zero"},bottom:{display:"Alt(A)",local:"Alt",global:"Bottom"}}},measureAngle:{vertex:"Köşe noktasını belirtin",arm1:"Birinci kol üzerindeki noktayı belirtin",arm2:"İkinci kol üzerindeki noktayı belirtin"},measureArc:{startPoint:"Yayın başlangıç noktasını belirtin",throughPoint:"Yay üzerinde bir nokta belirtin",endPoint:"Yayın bitiş noktasını belirtin"},measureArea:{firstPoint:"İlk noktayı belirtin",nextPoint:"Sonraki noktayı belirtin (bitirmek için Enter'a basın)"},measureDistance:{firstPoint:"İlk noktayı belirtin",secondPoint:"İkinci noktayı belirtin"},measurePoint:{point:"Noktayı belirtin"},measurement:{import:{chooseFile:"Bir ölçüm sidecar JSON dosyası seçin"}},markup:{author:"İnceleme yazarını belirtin (sonraki kullanımlar için kaydedilir)",text:{point:"Metin işaretinin noktasını belirtin",content:"İşaret metnini girin"},line:{firstPoint:"Çizgi işaretinin ilk noktasını belirtin",secondPoint:"Çizgi işaretinin ikinci noktasını belirtin"},arrow:{firstPoint:"Okun başlangıç noktasını belirtin",secondPoint:"Ok ucunu belirtin"},cloud:{firstCorner:"Bulutun ilk köşesini belirtin",secondCorner:"Bulutun karşı köşesini belirtin"},rect:{firstCorner:"Dikdörtgenin ilk köşesini belirtin",secondCorner:"Dikdörtgenin karşı köşesini belirtin"},circle:{center:"Dairenin merkezini belirtin",radius:"Dairenin yarıçapını belirtin"},shape:{calloutOn:"[Çağrı açık]",calloutOff:"[Çağrı kapalı]",calloutAnchor:"Çağrı metninin konumunu belirtin",keywords:{callout:{display:"Çağrı(C)",local:"Çağrı",global:"Callout"},noCallout:{display:"ÇağrıYok(N)",local:"ÇağrıYok",global:"NoCallout"}}},highlight:{firstCorner:"Vurgu dikdörtgeninin ilk köşesini belirtin",secondCorner:"Vurgu dikdörtgeninin karşı köşesini belirtin"},callout:{tip:"Lider ucunu belirtin (ok ucu)",anchor:"Çağrı metninin konumunu belirtin",content:"Çağrı metnini girin"},stamp:{kind:"Damga kimliğini girin [approved/rejected/revised/for-review/custom]",imageUrl:"Özel damga görüntüsü URL’sini girin (isteğe bağlı)",caption:"Damga açıklamasını girin (isteğe bağlı)",point:"Damga ekleme noktasını belirtin"},import:{chooseFile:"Bir işaret sidecar JSON dosyası seçin"}},move:{basePointOrDisplacement:"Temel noktayı belirtin veya",secondPointOrDisplacement:"İkinci noktayı belirtin veya",displacement:"Yer değiştirmeyi belirtin",keywords:{displacement:{display:"Yer değiştirme(Y)",local:"Yer değiştirme",global:"Displacement"}}},offset:{distance:"Öteleme mesafesini belirtin",selectObject:"Ötelenecek nesneyi seçin veya bitirmek için Enter'a basın",sidePoint:"Ötelenecek tarafta bir nokta belirtin",invalidDistance:"Öteleme mesafesi 0'dan büyük olmalıdır.",invalidSelection:"Seçilen nesne ötelenemez.",offsetFailed:"Belirtilen taraf için bir öteleme eğrisi oluşturulamadı."},mtext:{point:"Çok satırlı metin ekleme noktasını belirtin"},pngout:{boundsFirstCorner:"Sınırların ilk köşesini belirtin",boundsSecondCorner:"Karşı köşeyi belirtin",longSidePrompt:"Uzun kenar boyutunu piksel olarak girin"},imageattach:{insertionPoint:"Ekleme noktasını belirtin:",scale:"Ölçek faktörünü belirtin:",rotation:"Döndürme açısını belirtin:",invalidScale:"Ölçek faktörü 0 dan büyük olmalıdır.",decodeFailed:"Seçilen görüntü dosyası okunamadı."},insert:{blockName:"Blok adını girin:",insertionPoint:"Ekleme noktasını belirtin:",scale:"Ölçek faktörünü belirtin:",rotation:"Döndürme açısını belirtin:",invalidScale:"Ölçek faktörü 0 dan büyük olmalıdır.",invalidBlockName:"Geçersiz blok adı.",blockNotFound:"Blok bulunamadı",xrefNotAllowed:"Harici referans -INSERT ile eklenemez."},xattach:{insertionPoint:"Ekleme noktasını belirtin:",scale:"Ölçek faktörünü belirtin:",rotation:"Döndürme açısını belirtin:",invalidScale:"Ölçek faktörü 0 dan büyük olmalıdır.",unsupportedFile:"Lütfen bir DWG veya DXF dosyası seçin.",loading:"Harici referans yükleniyor...",loadFailed:"Seçilen çizim dosyası okunamadı."},point:{point:"Bir nokta belirtin"},polygon:{numberOfSides:"Kenar sayısını girin",centerOrEdge:"Çokgenin merkezini belirtin veya",radiusOrType:"Seçenekleri girin",edgeStart:"Kenarın ilk uç noktasını belirtin",edgeEnd:"Kenarın ikinci uç noktasını belirtin",keywords:{edge:{display:"Kenar(K)",local:"Kenar",global:"Edge"},inscribed:{display:"Çembere iç teğet(İ)",local:"Çembere iç teğet",global:"Inscribed"},circumscribed:{display:"Çembere dış teğet(D)",local:"Çembere dış teğet",global:"Circumscribed"}},invalid:{sides:"Geçersiz kenar sayısı. 3 ile 1024 arasında bir tam sayı girin.",radius:"Geçersiz yarıçap. Yarıçap 0'dan büyük olmalıdır.",edge:"Geçersiz kenar. Kenar uzunluğu 0'dan büyük olmalıdır."}},polyline:{firstPoint:"İlk noktayı belirtin",nextPoint:"Sonraki noktayı belirtin (bitirmek için Enter'a basın)",nextPointWithOptions:"Sonraki noktayı belirtin veya",nextPointWithArcOptions:"Sonraki noktayı belirtin veya",keywords:{arc:{display:"Yay(Y)",local:"Yay",global:"Arc"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},close:{display:"Kapat(K)",local:"Kapat",global:"Close"},line:{display:"Doğru(D)",local:"Doğru",global:"Line"},angle:{display:"Açı(A)",local:"Açı",global:"Angle"},center:{display:"Merkez(M)",local:"Merkez",global:"Center"},secondPoint:{display:"İkinci nokta(İ)",local:"İkinci nokta",global:"SecondPoint"},radius:{display:"Yarıçap(R)",local:"Yarıçap",global:"Radius"}},arcAngle:"Yay açısını belirtin",arcCenter:"Merkez noktasını belirtin",arcSecondPoint:"Yay üzerinde ikinci noktayı belirtin",arcEndPoint:"Yayın bitiş noktasını belirtin",arcRadius:"Yay yarıçapını belirtin"},rect:{firstPoint:"İlk köşe noktasını belirtin",nextPoint:"Diğer köşe noktasını belirtin",firstPointWithOptions:"İlk köşe noktasını belirtin veya",otherCornerWithOptions:"Diğer köşe noktasını belirtin veya",chamferFirst:"İlk pah mesafesini belirtin",chamferSecond:"İkinci pah mesafesini belirtin",filletRadius:"Yuvarlatma yarıçapını belirtin",segmentWidth:"Dikdörtgen çizgi genişliğini belirtin",elevationValue:"Kotu belirtin",thicknessValue:"Kalınlığı belirtin",rotationAngle:"Dikdörtgen döndürme açısını belirtin",dimensionLength:"Dikdörtgen uzunluğunu belirtin",dimensionWidth:"Dikdörtgen genişliğini belirtin",areaValue:"Dikdörtgen alanını belirtin",areaLengthOrWidth:"Dikdörtgen uzunluğunu belirtin",areaSpecifyWidth:"Dikdörtgen genişliğini belirtin",invalidPositive:"Geçersiz giriş. Lütfen 0'dan büyük bir değer girin.",invalidRect:"Dikdörtgen oluşturulamadı. Lütfen geçerli köşeler veya boyutlar belirtin.",thicknessNotSupported:"Dikdörtgen kalınlığı şu anda nesne verisine yazılmıyor. Kalınlık ayarı yok sayılıyor.",keywords:{chamfer:{display:"Pah(P)",local:"Pah",global:"Chamfer"},elevation:{display:"Kot(K)",local:"Kot",global:"Elevation"},fillet:{display:"Yuvarlatma(Y)",local:"Yuvarlatma",global:"Fillet"},thickness:{display:"Kalınlık(K)",local:"Kalınlık",global:"Thickness"},width:{display:"Genişlik(G)",local:"Genişlik",global:"Width"},area:{display:"Alan(A)",local:"Alan",global:"Area"},dimensions:{display:"Boyutlar(B)",local:"Boyutlar",global:"Dimensions"},rotation:{display:"Döndürme(D)",local:"Döndürme",global:"Rotation"},length:{display:"Uzunluk(U)",local:"Uzunluk",global:"Length"},rectWidth:{display:"Genişlik(G)",local:"Genişlik",global:"Width"}}},rotate:{basePoint:"Temel noktayı belirtin",rotationAngleOrOptions:"Döndürme açısını belirtin veya",referenceAngleOrPoints:"Referans açısını belirtin veya",firstReferencePoint:"Referans açısının ilk noktasını belirtin",secondReferencePoint:"İkinci noktayı belirtin",newAngle:"Yeni açıyı belirtin",keywords:{copy:{display:"Kopyala(K)",local:"Kopyala",global:"Copy"},reference:{display:"Referans(R)",local:"Referans",global:"Reference"},points:{display:"Noktalar(N)",local:"Noktalar",global:"Points"}},invalid:{referencePoints:"Geçersiz referans noktaları: noktalar farklı olmalıdır."}},revcloud:{firstCornerOrOptions:"İlk köşe noktasını belirtin veya",firstCorner:"İlk köşe noktasını belirtin",oppositeCorner:"Karşı köşeyi belirtin",startPoint:"Başlangıç noktasını belirtin",nextPoint:"Sonraki noktayı belirtin",nextPointOrUndo:"Sonraki noktayı belirtin veya",firstPoint:"İlk noktayı belirtin",guideCursor:"İmleci bulut yolu boyunca götürün (bitirmek için Enter)",arcLength:"Yay uzunluğunu belirtin",selectObject:"Nesne seçin",style:"Revizyon bulutu yay stilini girin",reverseDirection:"Yönü ters çevir",invalidArcLength:"Yay uzunluğu 0'dan büyük olmalıdır.",invalidObject:"Seçilen nesne revizyon bulutuna dönüştürülemez.",keywords:{arcLength:{display:"Yay uzunluğu(A)",local:"Yay uzunluğu",global:"ArcLength"},object:{display:"Nesne(O)",local:"Nesne",global:"Object"},rectangular:{display:"Dikdörtgen(R)",local:"Dikdörtgen",global:"Rectangular"},polygonal:{display:"Çokgen(P)",local:"Çokgen",global:"Polygonal"},freehand:{display:"Serbest(F)",local:"Serbest",global:"Freehand"},style:{display:"Stil(S)",local:"Stil",global:"Style"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},calligraphy:{display:"Kaligrafi(C)",local:"Kaligrafi",global:"Calligraphy"},undo:{display:"Geri al(U)",local:"Geri al",global:"Undo"},yes:{display:"Evet(Y)",local:"Evet",global:"Yes"},no:{display:"Hayır(N)",local:"Hayır",global:"No"}}},sketch:{specifySketch:"Eskizi belirtin veya",sketching:"Eskiz için işaretçiyi hareket ettirin (durdurmak için tıklayın veya Enter)",type:"Eskiz türünü girin",increment:"Eskiz artışını belirtin",tolerance:"Spline toleransını belirtin",firstPoint:"İlk noktayı belirtin",nextPoint:"Bitiş noktasını belirtin",keywords:{type:{display:"Tür(T)",local:"Tür",global:"Type"},increment:{display:"Artış(I)",local:"Artış",global:"Increment"},tolerance:{display:"toLerance(L)",local:"toLerance",global:"Tolerance"},line:{display:"Çizgiler(L)",local:"Çizgiler",global:"Lines"},polyline:{display:"Çoklu çizgi(P)",local:"Çoklu çizgi",global:"Polyline"},spline:{display:"Spline(S)",local:"Spline",global:"Spline"}}},spline:{firstPoint:"İlk noktayı belirtin",nextPoint:"Sonraki noktayı belirtin (bitirmek için Enter'a basın)",firstPointWithOptions:"İlk noktayı belirtin veya",nextPointWithFitOptions:"Sonraki noktayı belirtin veya",nextPointWithCvOptions:"Sonraki kontrol noktasını belirtin veya",methodPrompt:"Spline oluşturma yöntemini girin",knotsPrompt:"Düğüm parametrelemesini girin",degreePrompt:"Spline derecesini belirtin",keywords:{method:{display:"Yöntem(Y)",local:"Yöntem",global:"Method"},fit:{display:"Uydur(U)",local:"Uydur",global:"Fit"},cv:{display:"KN(K)",local:"KN",global:"CV"},knots:{display:"Düğümler(D)",local:"Düğümler",global:"Knots"},degree:{display:"Derece(D)",local:"Derece",global:"Degree"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},close:{display:"Kapat(K)",local:"Kapat",global:"Close"},chord:{display:"Kiriş(K)",local:"Kiriş",global:"Chord"},sqrtChord:{display:"Karekök kiriş(K)",local:"Karekök kiriş",global:"SqrtChord"},uniform:{display:"Düzgün(D)",local:"Düzgün",global:"Uniform"}}},sysvar:{prompt:"Lütfen yeni değeri girin"},zoom:{mainPrompt:"Pencerenin köşesini belirtin veya",firstCorner:"İlk köşeyi belirtin",secondCorner:"Karşı köşeyi belirtin",centerPoint:"Merkez noktasını belirtin",heightOrScale:"Yükseklik veya ölçek faktörünü girin (nX veya nXP)",scaleFactor:"Ölçek faktörünü girin (nX veya nXP)",keywords:{all:{display:"Tümü(T)",local:"Tümü",global:"All"},center:{display:"Merkez(M)",local:"Merkez",global:"Center"},extents:{display:"Kapsam(K)",local:"Kapsam",global:"Extents"},previous:{display:"Önceki(Ö)",local:"Önceki",global:"Previous"},scale:{display:"Ölçek(Ö)",local:"Ölçek",global:"Scale"},window:{display:"Pencere(P)",local:"Pencere",global:"Window"}}},chtml:{exportInvisibleLayers:"Görünmez katmanları dışa aktar",initialView:"HTML açılırken başlangıç görünümü",viewerMode:"Çevrimdışı görüntüleyici modu",keywords:{yes:{display:"Evet(E)",local:"Evet",global:"Yes"},no:{display:"Hayır(H)",local:"Hayır",global:"No"},extents:{display:"Kapsam(K)",local:"Kapsam",global:"Extents"},current:{display:"Geçerli(G)",local:"Geçerli",global:"Current"},view:{display:"Görünüm(G)",local:"Görünüm",global:"View"},measure:{display:"Ölç(Ö)",local:"Ölç",global:"Measure"}}}},Im={document:{untitled:"Adsız"},commandLine:{noLast:"(önceki komut yok)",unknownCommand:"Bilinmeyen komut",executed:"Komut çalıştırıldı",showHistory:"Komut geçmişini göster",placeholder:"Komut girin",showMessages:"Mesaj geçmişini göster",canceled:"*İptal edildi*",noHistory:"(geçmiş yok)",invalidInput:"Geçersiz giriş.",close:"Komut satırını kapat"},inputManager:{firstCorner:"İlk köşeyi belirtin veya",secondCorner:"İkinci köşeyi belirtin veya"},message:{fetchingDrawingFile:"Dosya alınıyor ...",exportingDxf:"DXF dışa aktarılıyor ...",exportingEntityPreview:"Görüntü dışa aktarılıyor ...",collectingMemoryProfile:"Bellek analiz ediliyor ...",fontCached:"Yazı tipi başarıyla önbelleğe alındı",fontCacheFailed:"Yazı tipi önbelleğe alınamadı"},progress:{start:"Dosya ayrıştırma başlatılıyor ...",parse:"Dosya ayrıştırılıyor ...",font:"Bu çizim için gerekli yazı tipleri indiriliyor ...",ltype:"Çizgi tipleri ayrıştırılıyor ...",style:"Metin stilleri ayrıştırılıyor ...",dimstyle:"Ölçülendirme stilleri ayrıştırılıyor ...",layer:"Katmanlar ayrıştırılıyor ...",vport:"Görüntü portları ayrıştırılıyor ...",blockrecord:"Blok kaydı ayrıştırılıyor ...",header:"Başlık ayrıştırılıyor ...",block:"Bloklar ayrıştırılıyor ...",entity:"Nesneler ayrıştırılıyor ...",object:"Adlandırılmış sözlükler ayrıştırılıyor ...",rendering:"Çizim render ediliyor ...",end:"Tamamlandı!"},about:{title:"Hakkında",close:"Kapat",product:"CAD Viewer",tagline:"DWG ve DXF çizimleri için yüksek performanslı web CAD görüntüleyici.",website:"Web sitesi",docs:"Belgeler",repository:"GitHub",copyright:"© {year} mlightcad. Tüm hakları saklıdır.",ok:"Tamam"},drawStyle:{color:"Renk",lineWeight:"Çizgi kalınlığı",fontSize:"Yazı yüksekliği"}},Mm={ACAD:{"-hatch":{description:"通过命令行选项创建填充,不显示 Ribbon 界面"},"-layer":{description:"通过命令行选项管理图层"},about:{description:"显示 mlightcad 产品信息"},acadver:{description:"存储图形数据库版本标识符(只读)"},angbase:{description:"设置当前 UCS 中 0 度的基准角方向"},angdir:{description:"设置正角度的方向为顺时针或逆时针"},arc:{description:"创建圆弧"},aunits:{description:"设置角度显示格式"},auprec:{description:"设置角度显示精度(小数位数),与 AUNITS 配合使用"},cdxf:{description:"导出当前图纸为DXF格式"},cpdf:{description:"导出当前图纸为PDF格式"},cecolor:{description:"设置新创建对象的当前默认颜色"},celtscale:{description:"控制新创建对象的线型比例系数"},celtype:{description:"设置新创建对象的线型"},celweight:{description:"设置新创建对象的默认线宽"},cetransparency:{description:"设置新创建对象的透明度"},cachefont:{description:"将本地字体文件缓存到 IndexedDB 以供文字渲染使用"},circle:{description:"使用圆心和半径创建圆"},clayer:{description:"设置新建对象和编辑操作所使用的当前图层"},cmleaderstyle:{description:"设置当前多重引线样式名称"},cmlscale:{description:"控制多线的整体宽度"},cmlstyle:{description:"设置当前多线样式名称"},colortheme:{description:"控制用户界面的颜色主题(深色或浅色)"},copy:{description:"通过克隆将所选图元复制到新位置",prompt:"选择对象"},csvg:{description:"转换当前图纸为SVG格式"},chtml:{description:"将当前图纸导出为可离线打开的 HTML 文件"},"-chtml":{description:"通过命令行选项将当前图纸导出为 HTML 文件"},dimlinear:{description:"创建线性尺寸标注"},dimstyle:{description:"设置当前标注样式的名称"},dwgname:{description:"存储当前图形文件的名称(只读)"},loginname:{description:"显示当前用户的登录名(只读)"},dynmode:{description:"控制光标处的动态输入设置"},dynprompt:{description:"控制动态输入工具提示中提示的显示"},ellipse:{description:"通过轴端点或中心点创建椭圆或椭圆弧"},erase:{description:"从图纸中删除所选对象",prompt:"选择对象"},extmax:{description:"存储模型空间图形范围的右上角(只读)"},extmin:{description:"存储模型空间图形范围的左下角(只读)"},entout:{description:"导出所选对象的合并预览图",prompt:"选择对象"},hideobjects:{description:"临时隐藏所选对象的显示",prompt:"选择对象"},imageattach:{description:"将光栅图像作为外部参照附着到当前图形"},"-insert":{description:"将块定义插入到当前图形(命令行)"},xattach:{description:"将 DWG 或 DXF 图形作为外部参照附着到当前图形"},gripcolor:{description:"设置所选对象上未选中夹点的颜色"},griphot:{description:"设置所选(热)夹点的颜色"},gripobjlimit:{description:"当选择集中的对象数超过指定值时不显示夹点(0 表示无限制)"},grips:{description:"控制是否在所选对象上显示夹点"},gripsize:{description:"设置夹点框的大小(像素)"},hatch:{description:"用填充图案填充封闭区域或所选对象"},ipdf:{description:"从 PDF 文件导入矢量几何"},hpang:{description:"设置新创建填充图案的默认角度(弧度)"},hpassoc:{description:"控制新创建的填充是否具有关联性"},hpbackgroundcolor:{description:"设置新创建填充图案的默认背景颜色"},hpcolor:{description:"设置新创建填充的默认颜色"},hpdouble:{description:"控制用户定义的填充图案是否加倍"},hpislanddetection:{description:"控制新创建填充边界内孤岛的处理方式"},hplayer:{description:"设置新创建填充和填充区域的默认图层"},hpname:{description:"设置当前会话中新创建填充的默认图案名称"},hpscale:{description:"设置新创建填充图案的默认比例系数"},hpseparate:{description:"控制为多个边界创建单个还是独立的填充对象"},hptransparency:{description:"设置新创建填充和填充区域的默认透明度"},insunits:{description:"指定插入块、图像或外部参照时用于自动缩放的图形单位"},laycur:{description:"将所选对象的图层属性更改为当前图层",prompt:"选择要更改到当前图层的对象"},laydel:{description:"删除图层及该图层上的所有对象"},layerclose:{description:"关闭图层属性管理器"},layerp:{description:"撤销对图层设置的最后一次更改或一组更改"},layfrz:{description:"冻结所选对象所在的图层",prompt:"选择要冻结其图层的对象"},layiso:{description:"隔离所选对象所在的图层",prompt:"选择要隔离其图层的对象"},laylck:{description:"锁定所选对象所在的图层",prompt:"选择要锁定其图层的对象"},layoff:{description:"关闭所选对象所在的图层",prompt:"选择要关闭其图层的对象"},layon:{description:"打开图纸中的所有图层"},laythw:{description:"解冻图纸中的所有冻结图层"},layulk:{description:"解锁所选对象所在的图层",prompt:"选择要解锁其图层的对象"},layuniso:{description:"恢复由 LAYISO 隐藏或锁定的图层"},line:{description:"在指定点之间绘制直线段"},log:{description:"在控制台输出调试信息"},ltscale:{description:"设置图形的全局线型比例系数"},lunits:{description:"设置坐标和距离的显示格式"},luprec:{description:"设置线性单位的显示精度(小数位数),与 LUNITS 配合使用"},lwdisplay:{description:"用于控制是否在图纸中显示线宽效果"},clearmeasurements:{description:"清除当前布局上的所有测量标注"},measurementvis:{description:"显示或隐藏当前布局上的测量标注"},measurementexport:{description:"将测量标注导出为 sidecar JSON 文件"},measurementimport:{description:"从 sidecar JSON 文件导入测量标注"},measurearea:{description:"计算所选对象或点定义区域的面积和周长"},measureangle:{description:"测量两条线或三个点之间的夹角"},measurearc:{description:"测量圆弧段的弧长"},measuredistance:{description:"测量两点之间的距离及坐标增量"},measurepoint:{description:"测量拾取点的 X/Y 坐标"},measurement:{description:"设置图形使用英制或公制单位"},measurementcolor:{description:"设置测量标注覆盖图形使用的颜色"},modelbkcolor:{description:"设置模型空间绘图区域的背景颜色"},mline:{description:"创建由多条平行线组成的多线对象"},move:{description:"通过位移向量移动所选图元",prompt:"选择对象"},offset:{description:"按指定距离创建平行曲线、多段线或圆"},mtext:{description:"创建多行文本"},open:{description:"打开图纸"},openprof:{description:"控制是否在控制台记录文件打开阶段的耗时分析"},openperf:{description:"打开“打开性能”面板,显示最近一次打开图纸的关键耗时"},orthomode:{description:"将光标移动限制为水平或垂直方向"},osmode:{description:"使用位码设置运行中的对象捕捉模式"},pan:{description:"平移视图"},paperbkcolor:{description:"设置图纸空间(布局)绘图区域的背景颜色"},pdmode:{description:"控制点对象的显示样式"},pdsize:{description:"设置点对象的显示大小"},pickbox:{description:"控制用于选择对象的拾取框大小(像素)"},pline:{description:"通过指定多个点创建多段线"},pngout:{description:"导出为 PNG 图片"},point:{description:"连续创建点"},polaraddang:{description:"以分号分隔的列表存储附加极轴追踪角度"},polarang:{description:"设置极轴追踪的极轴角增量"},polarmode:{description:"控制极轴追踪和对象捕捉追踪设置"},polygon:{description:"通过中心和半径或指定一条边创建正多边形"},qnew:{description:"创建新图纸"},ray:{description:"创建从起点向单一方向无限延伸的射线"},rectang:{description:"通过指定两个对角点创建矩形"},regen:{description:"重绘图纸"},revcloud:{description:"创建或修改修订云线"},markuptext:{description:"放置文字批注"},markupline:{description:"创建直线批注"},markuparrow:{description:"创建箭头批注"},markupcloud:{description:"创建修订云线批注"},markuprect:{description:"创建矩形批注"},markupcircle:{description:"创建圆形批注"},markuphighlight:{description:"创建高亮矩形批注"},markupcallout:{description:"创建标注:先指定引线尖端,再放置文字框,最后输入文字"},markupstamp:{description:"放置图章或自定义符号"},markupvis:{description:"显示或隐藏批注"},clearmarkups:{description:"清除当前布局上的所有批注"},markupexport:{description:"将批注导出为 sidecar JSON 文件"},markupimport:{description:"从 sidecar JSON 文件导入批注"},markuppanel:{description:"打开批注面板"},rotate:{description:"绕基点旋转所选图元",prompt:"选择对象"},select:{description:"选择图元"},shortcutmenu:{description:"控制图形区域中快捷菜单的可用性"},sketch:{description:"创建一系列徒手线段"},spline:{description:"通过指定控制点创建平滑的样条曲线"},textstyle:{description:"设置当前文字样式的名称"},unitmode:{description:"当 LUNITS 为建筑或分数格式时,控制坐标的分数显示格式"},switchbg:{description:"切换绘图区域背景颜色,在白色和黑色背景之间切换"},unisolateobjects:{description:"重新显示 HIDEOBJECTS 隐藏的所有对象"},undo:{description:"撤销上一次数据库编辑操作",nothingToUndo:"没有可撤销的操作。"},redo:{description:"重做上一次撤销的操作",nothingToRedo:"没有可重做的操作。"},xline:{description:"创建在两个方向上无限延伸的构造线"},zoom:{description:"缩放以显示所有对象"}},USER:{}},Dm={arc:{startPointOrCenter:"指定圆弧的起点或",secondPointOrOptions:"指定圆弧上的第二点或",secondPoint:"指定圆弧上的第二点",startPoint:"指定圆弧的起点",centerPoint:"指定圆弧的圆心",endPoint:"指定圆弧的端点",endPointOrOptions:"指定圆弧的端点或",centerPointOrOptions:"指定圆弧的圆心或",includedAngle:"指定圆弧的夹角",chordLength:"指定圆弧的弦长",tangentDirection:"指定圆弧起点的切线方向",radius:"指定圆弧的半径",keywords:{center:{display:"圆心(C)",local:"圆心",global:"Center"},end:{display:"端点(E)",local:"端点",global:"End"},angle:{display:"角度(A)",local:"角度",global:"Angle"},chordLength:{display:"弦长(L)",local:"弦长",global:"ChordLength"},direction:{display:"方向(D)",local:"方向",global:"Direction"},radius:{display:"半径(R)",local:"半径",global:"Radius"}},invalid:{threePoint:"三点圆弧无效:三点共线或无法确定圆弧。",center:"圆心输入无效:起点与终点必须在同一圆上。",angle:"角度输入无效:夹角必须大于 0 且小于 360 度。",chordLength:"弦长输入无效:该值超出当前半径可用范围。",direction:"方向输入无效:无法根据该切线方向构造圆弧。",radius:"半径输入无效:指定半径无法连接起点与终点。"}},circle:{center:"指定圆的圆心",centerOrOptions:"指定圆的圆心或",radius:"指定圆的半径",radiusOrDiameter:"指定圆的半径或",diameter:"指定圆的直径",twoPointFirst:"指定圆直径的第一个端点",twoPointSecond:"指定圆直径的第二个端点",threePointFirst:"指定圆上的第一个点",threePointSecond:"指定圆上的第二个点",threePointThird:"指定圆上的第三个点",keywords:{threeP:{display:"三点(3P)",local:"三点",global:"3P"},twoP:{display:"两点(2P)",local:"两点",global:"2P"},diameter:{display:"直径(D)",local:"直径",global:"Diameter"}}},copy:{basePointOrOptions:"指定基点或",displacementOrArray:"指定位移或",secondPointOrArray:"指定第二个点或",modePrompt:"输入复制模式选项",arrayItemCount:"输入阵列中的项目数(包括原对象)",arraySecondPointOrFit:"指定第二个点或",arrayFitSecondPoint:"指定第二个点",keywords:{displacement:{display:"位移(D)",local:"位移",global:"Displacement"},mode:{display:"模式(O)",local:"模式",global:"Mode"},multiple:{display:"多个(M)",local:"多个",global:"Multiple"},single:{display:"单个(S)",local:"单个",global:"Single"},array:{display:"阵列(A)",local:"阵列",global:"Array"},fit:{display:"布满(F)",local:"布满",global:"Fit"}}},dimlinear:{xLine1Point:"指定第一条尺寸界限原点",xLine2Point:"指定第二条尺寸界限原点",dimLinePoint:"指定尺寸线位置"},ellipse:{axisEndpointOrOptions:"指定椭圆的轴端点或",arcAxisEndpointOrCenter:"指定椭圆弧的轴端点或",center:"指定椭圆中心点",firstAxisEndpoint:"指定轴的端点",secondAxisEndpoint:"指定轴的另一个端点",otherAxisOrRotation:"指定到另一轴的距离或",rotationAngle:"指定绕长轴的旋转角度",arcStartAngle:"指定椭圆弧起始角",arcEndAngle:"指定椭圆弧终止角",keywords:{arc:{display:"圆弧(A)",local:"圆弧",global:"Arc"},center:{display:"中心点(C)",local:"中心点",global:"Center"},rotation:{display:"旋转(R)",local:"旋转",global:"Rotation"}},invalid:{axis:"轴输入无效:轴长必须大于 0。",otherAxis:"另一轴输入无效:距离必须大于 0。",rotation:"旋转输入无效:计算得到的短轴必须大于 0。"}},hatch:{prompt:"选择边界对象或",pickPoint:"指定内部点(或按 Enter 结束)",select:"选择要填充的对象",patternName:"输入填充图案名称",scale:"指定填充图案比例",angle:"指定填充图案角度",style:"输入填充样式",associative:"指定关联性",invalidBoundary:"所选对象无法构成闭合边界。",keywords:{pick:{display:"拾取点(P)",local:"拾取点",global:"PickPoints"},select:{display:"选择对象(S)",local:"选择对象",global:"SelectObjects"},cancel:{display:"放弃(C)",local:"放弃",global:"Cancel"},pattern:{display:"图案(P)",local:"图案",global:"Pattern"},scale:{display:"比例(S)",local:"比例",global:"Scale"},angle:{display:"角度(A)",local:"角度",global:"Angle"},style:{display:"样式(T)",local:"样式",global:"HatchStyle"},associative:{display:"关联(AS)",local:"关联",global:"AssociativeMode"},normal:{display:"普通(N)",local:"普通",global:"Normal"},outer:{display:"外部(O)",local:"外部",global:"Outer"},ignore:{display:"忽略(I)",local:"忽略",global:"Ignore"},yes:{display:"是(Y)",local:"是",global:"Yes"},no:{display:"否(N)",local:"否",global:"No"}}},hideobjects:{hidden:"个对象已隐藏",restored:"个对象已恢复显示",nothingToRestore:"没有可恢复显示的对象"},entout:{longSidePrompt:"输入预览图长边像素尺寸",exported:"个对象预览已导出",skipped:"个对象已跳过",failed:{"no-preview-root":"无法为所选对象构建预览几何","no-bounds":"无法计算所选对象的预览范围","capture-failed":"无法渲染实体预览图","download-failed":"预览已渲染,但 PNG 下载失败"}},layer:{main:"输入选项",listSummary:"图层列表已输出到浏览器控制台",emptyInput:"未输入图层名。",newPrompt:"输入新建图层名称(可用逗号分隔多个)",makePrompt:"输入要创建并设为当前的图层名",setPrompt:"输入要设为当前的图层名",onPrompt:"输入要打开的图层名",offPrompt:"输入要关闭的图层名",freezePrompt:"输入要冻结的图层名",thawPrompt:"输入要解冻的图层名",lockPrompt:"输入要锁定的图层名",unlockPrompt:"输入要解锁的图层名",colorLayerPrompt:"输入要修改颜色的图层名",colorValuePrompt:"输入颜色(ACI 1-255、RGB 如 255,0,0 或颜色名)",invalidColor:"颜色输入无效。",descriptionLayerPrompt:"输入要修改说明的图层名",descriptionValuePrompt:"输入新的图层说明",created:"已创建图层数量",alreadyExists:"图层已存在",notFound:"未找到图层",cannotChangeCurrent:"不能关闭或冻结当前图层。",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"创建并置为当前(M)",local:"创建并置为当前",global:"Make"},set:{display:"置为当前(S)",local:"置为当前",global:"Set"},new:{display:"新建(N)",local:"新建",global:"New"},on:{display:"打开(ON)",local:"打开",global:"On"},off:{display:"关闭(OF)",local:"关闭",global:"Off"},color:{display:"颜色(C)",local:"颜色",global:"Color"},freeze:{display:"冻结(F)",local:"冻结",global:"Freeze"},thaw:{display:"解冻(T)",local:"解冻",global:"Thaw"},lock:{display:"锁定(L)",local:"锁定",global:"Lock"},unlock:{display:"解锁(U)",local:"解锁",global:"Unlock"},description:{display:"说明(D)",local:"说明",global:"Description"}}},layon:{alreadyOn:"所有图层都已经打开。",turnedOn:"已打开图层数量"},laycur:{prompt:"选择要更改到当前图层的对象",currentLayerNotFound:"未找到当前图层。",noObjects:"没有选择有效对象。",alreadyCurrent:"所选对象已位于当前图层。",changed:"已将对象更改到当前图层"},layfrz:{prompt:"选择要冻结其图层的对象或",invalidSelection:"所选对象无效。",settingsPrompt:"输入要修改的 LAYFRZ 设置",viewportPrompt:"指定视口冻结行为",blockSelectionPrompt:"指定嵌套块选择行为",vpfreezeFallback:"当前 viewer 不支持按视口冻结图层,已退化为普通 Freeze 行为。",nestedSelectionLimited:"嵌套块选择设置会被保存,但当前拾取仍只能解析顶层对象所在图层。",layerNotFound:"未找到图层",cannotFreezeCurrent:"不能冻结当前图层。",alreadyFrozen:"图层已处于冻结状态",frozen:"已冻结图层",restored:"已恢复图层",nothingToUndo:"当前没有可撤销的 LAYFRZ 操作。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},viewports:{display:"视口(V)",local:"视口",global:"Viewports"},blockSelection:{display:"块选择(B)",local:"块选择",global:"BlockSelection"},freeze:{display:"冻结(F)",local:"冻结",global:"Freeze"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"},block:{display:"块(B)",local:"块",global:"Block"},entity:{display:"对象(E)",local:"对象",global:"Entity"},none:{display:"无(N)",local:"无",global:"None"}}},layiso:{prompt:"选择要隔离其图层的对象或",settingsPrompt:"输入未隔离图层的处理设置",offModePrompt:"输入未隔离图层的关闭行为",noLayers:"未选择有效图层。",layerNotFound:"未找到图层",isolated:"已隔离图层",affectedLayers:"受影响图层数",vpfreezeFallback:"当前 viewer 不支持按视口冻结图层,已退化为普通 Off 行为。",lockFadeFallback:"当前 viewer 不支持图层淡显显示,未隔离图层将仅被锁定。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},off:{display:"关闭(O)",local:"关闭",global:"Off"},lockAndFade:{display:"锁定并淡显(L)",local:"锁定并淡显",global:"LockAndFade"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"}}},laythw:{alreadyThawed:"所有图层都已经解冻。",thawed:"已解冻图层数量"},layuniso:{noPrevious:"没有可恢复的上一次 LAYISO 图层状态。",layerNotFound:"未找到图层",nothingRestored:"没有恢复任何 LAYISO 图层改动。",restored:"已恢复图层数量"},laylck:{prompt:"选择要锁定其图层的对象",invalidSelection:"所选对象无效。",layerNotFound:"未找到图层",alreadyLocked:"图层已处于锁定状态",locked:"已锁定图层"},layulk:{prompt:"选择要解锁其图层的对象",invalidSelection:"所选对象无效。",layerNotFound:"未找到图层",alreadyUnlocked:"图层已处于解锁状态",unlocked:"已解锁图层"},layoff:{prompt:"选择要关闭其图层的对象或",invalidSelection:"所选对象无效。",settingsPrompt:"输入要修改的 LAYOFF 设置",viewportPrompt:"指定视口行为",blockSelectionPrompt:"指定嵌套块选择行为",vpfreezeFallback:"当前 viewer 不支持按视口关闭图层,已退化为普通 Off 行为。",nestedSelectionLimited:"嵌套块选择设置会被保存,但当前拾取仍只能解析顶层对象所在图层。",layerNotFound:"未找到图层",cannotTurnOffCurrent:"不能关闭当前图层。",alreadyOff:"图层已处于关闭状态",turnedOff:"已关闭图层",restored:"已恢复图层",nothingToUndo:"当前没有可撤销的 LAYOFF 操作。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},viewports:{display:"视口(V)",local:"视口",global:"Viewports"},blockSelection:{display:"块选择(B)",local:"块选择",global:"BlockSelection"},off:{display:"关闭(O)",local:"关闭",global:"Off"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"},block:{display:"块(B)",local:"块",global:"Block"},entity:{display:"对象(E)",local:"对象",global:"Entity"},none:{display:"无(N)",local:"无",global:"None"}}},layerp:{restored:"恢复了之前的图层状态。",noPreviousState:"没有可恢复的先前图层状态。"},line:{firstPoint:"指定第一个点",firstPointOrContinue:"请指定第一个点或",nextPoint:"指定下一个点",nextPointWithOptions:"请指定下一个点或",keywords:{continue:{display:"继续(C)",local:"继续",global:"Continue"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"}}},xline:{firstPointOrOptions:"指定点或",secondPoint:"指定第二个点",throughPoint:"指定穿过点",angle:"输入构造线角度",invalidDirection:"XLINE 的方向无效。",keywords:{hor:{display:"水平(H)",local:"水平",global:"Hor"},ver:{display:"垂直(V)",local:"垂直",global:"Ver"},ang:{display:"角度(A)",local:"角度",global:"Ang"}}},ray:{startPoint:"指定起点",throughPoint:"指定通过点"},mline:{startPointWithOptions:"指定起点或",nextPointWithOptions:"指定下一点或",justificationPrompt:"输入对正方式",scalePrompt:"指定多线比例",stylePrompt:"输入多线样式名或 [?] 列出样式",styleNotFound:"未找到多线样式",styleListHeader:"已加载的多线样式",styleListEmpty:"当前图纸没有已加载的多线样式。",keywords:{justification:{display:"对正(J)",local:"对正",global:"Justification"},scale:{display:"比例(S)",local:"比例",global:"Scale"},style:{display:"样式(ST)",local:"样式",global:"Style"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},top:{display:"上(T)",local:"上",global:"Top"},zero:{display:"零(Z)",local:"零",global:"Zero"},bottom:{display:"下(B)",local:"下",global:"Bottom"}}},measureArc:{startPoint:"指定弧的起点",throughPoint:"指定弧上的一个点",endPoint:"指定弧的终点"},measureAngle:{vertex:"指定顶点",arm1:"指定第一条边上的点",arm2:"指定第二条边上的点"},measureArea:{firstPoint:"指定第一个点",nextPoint:"指定下一个点(或按 Enter 完成)"},measureDistance:{firstPoint:"指定第一个点",secondPoint:"指定第二个点"},measurePoint:{point:"指定点"},measurement:{import:{chooseFile:"选择测量 sidecar JSON 文件"}},markup:{author:"指定批注作者(将保存供以后使用)",text:{point:"指定文字批注点",content:"输入批注文字"},line:{firstPoint:"指定直线批注的第一点",secondPoint:"指定直线批注的第二点"},arrow:{firstPoint:"指定箭头起点",secondPoint:"指定箭头尖端"},cloud:{firstCorner:"指定云线的第一个角点",secondCorner:"指定云线的对角点"},rect:{firstCorner:"指定矩形的第一个角点",secondCorner:"指定矩形的对角点"},circle:{center:"指定圆心",radius:"指定圆的半径"},shape:{calloutOn:"[标注开启]",calloutOff:"[标注关闭]",calloutAnchor:"指定标注文字框位置",keywords:{callout:{display:"标注(C)",local:"标注",global:"Callout"},noCallout:{display:"无标注(N)",local:"无标注",global:"NoCallout"}}},highlight:{firstCorner:"指定高亮的第一个角点",secondCorner:"指定高亮的对角点"},callout:{tip:"指定引线尖端(箭头端)",anchor:"指定标注文字框位置",content:"输入标注文字"},stamp:{kind:"输入图章类型 [approved/rejected/revised/for-review/custom]",imageUrl:"输入自定义图章图片 URL(可选)",caption:"输入图章说明文字(可选)",point:"指定图章插入点"},import:{chooseFile:"选择批注 sidecar JSON 文件"}},move:{basePointOrDisplacement:"指定基点或",secondPointOrDisplacement:"指定第二个点或",displacement:"指定位移",keywords:{displacement:{display:"位移(D)",local:"位移",global:"Displacement"}}},offset:{distance:"指定偏移距离",selectObject:"选择要偏移的对象,或按 Enter 结束",sidePoint:"指定要偏移到的那一侧的点",invalidDistance:"偏移距离必须大于 0。",invalidSelection:"所选对象不能偏移。",offsetFailed:"无法在指定侧创建偏移曲线。"},mtext:{point:"指定多行文本插入点"},pngout:{boundsFirstCorner:"指定边界的第一个角点",boundsSecondCorner:"指定对角点",longSidePrompt:"输入长边像素大小"},imageattach:{insertionPoint:"指定插入点:",scale:"指定比例因子:",rotation:"指定旋转角度:",invalidScale:"比例因子必须大于 0。",decodeFailed:"无法读取所选图像文件。"},insert:{blockName:"输入块名:",insertionPoint:"指定插入点:",scale:"指定比例因子:",rotation:"指定旋转角度:",invalidScale:"比例因子必须大于 0。",invalidBlockName:"无效的块名。",blockNotFound:"未找到块",xrefNotAllowed:"不能使用 -INSERT 插入外部参照。"},xattach:{insertionPoint:"指定插入点:",scale:"指定比例因子:",rotation:"指定旋转角度:",invalidScale:"比例因子必须大于 0。",unsupportedFile:"请选择 DWG 或 DXF 文件。",loading:"正在加载外部参照...",loadFailed:"无法读取所选图形文件。"},point:{point:"指定点"},polygon:{numberOfSides:"输入边数",centerOrEdge:"指定多边形中心点或",radiusOrType:"输入选项",edgeStart:"指定边的第一个端点",edgeEnd:"指定边的第二个端点",keywords:{edge:{display:"边(E)",local:"边",global:"Edge"},inscribed:{display:"内接于圆(I)",local:"内接于圆",global:"Inscribed"},circumscribed:{display:"外切于圆(C)",local:"外切于圆",global:"Circumscribed"}},invalid:{sides:"边数无效:请输入 3 到 1024 之间的整数。",radius:"半径无效:半径必须大于 0。",edge:"边无效:边长必须大于 0。"}},polyline:{firstPoint:"指定第一个点",nextPoint:"指定下一个点(或按 Enter 完成)",nextPointWithOptions:"请指定下一个点或",nextPointWithArcOptions:"请指定下一个点或",keywords:{arc:{display:"圆弧(A)",local:"圆弧",global:"Arc"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},line:{display:"直线(L)",local:"直线",global:"Line"},angle:{display:"角度(A)",local:"角度",global:"Angle"},center:{display:"圆心(C)",local:"圆心",global:"Center"},secondPoint:{display:"第二点(P)",local:"第二点",global:"SecondPoint"},radius:{display:"半径(R)",local:"半径",global:"Radius"}},arcAngle:"指定弧角度",arcCenter:"指定圆心",arcSecondPoint:"指定弧上的第二点",arcEndPoint:"指定弧的终点",arcRadius:"指定弧半径"},rotate:{basePoint:"指定基点",rotationAngleOrOptions:"指定旋转角度或",referenceAngleOrPoints:"指定参考角或",firstReferencePoint:"指定参考角的第一点",secondReferencePoint:"指定第二点",newAngle:"指定新角度",keywords:{copy:{display:"复制(C)",local:"复制",global:"Copy"},reference:{display:"参照(R)",local:"参照",global:"Reference"},points:{display:"点(P)",local:"点",global:"Points"}},invalid:{referencePoints:"参考点输入无效:两点必须不同。"}},rect:{firstPoint:"指定第一个角点",nextPoint:"指定另一个角点",firstPointWithOptions:"指定第一个角点或者",otherCornerWithOptions:"指定另一个角点或者",chamferFirst:"指定第一个倒角距离",chamferSecond:"指定第二个倒角距离",filletRadius:"指定圆角半径",segmentWidth:"指定矩形线宽",elevationValue:"指定标高",thicknessValue:"指定厚度",rotationAngle:"指定矩形旋转角度",dimensionLength:"指定矩形长度",dimensionWidth:"指定矩形宽度",areaValue:"指定矩形面积",areaLengthOrWidth:"指定矩形长度",areaSpecifyWidth:"指定矩形宽度",invalidPositive:"输入无效:请输入大于 0 的数值。",invalidRect:"无法创建矩形:请输入有效的角点或尺寸。",thicknessNotSupported:"当前版本暂不支持将矩形厚度写入图元,已忽略厚度设置。",keywords:{chamfer:{display:"倒角(C)",local:"倒角",global:"Chamfer"},elevation:{display:"标高(E)",local:"标高",global:"Elevation"},fillet:{display:"圆角(F)",local:"圆角",global:"Fillet"},thickness:{display:"厚度(T)",local:"厚度",global:"Thickness"},width:{display:"宽度(W)",local:"宽度",global:"Width"},area:{display:"面积(A)",local:"面积",global:"Area"},dimensions:{display:"尺寸(D)",local:"尺寸",global:"Dimensions"},rotation:{display:"旋转(R)",local:"旋转",global:"Rotation"},length:{display:"长度(L)",local:"长度",global:"Length"},rectWidth:{display:"宽度(W)",local:"宽度",global:"Width"}}},revcloud:{firstCornerOrOptions:"指定第一个角点或",firstCorner:"指定第一个角点",oppositeCorner:"指定对角点",startPoint:"指定起点",nextPoint:"指定下一点",nextPointOrUndo:"指定下一点或",firstPoint:"指定第一个点",guideCursor:"沿云线路径移动光标(按 Enter 结束)",arcLength:"指定圆弧长度",selectObject:"选择对象",style:"输入修订云线圆弧样式",reverseDirection:"反转方向",invalidArcLength:"圆弧长度必须大于 0。",invalidObject:"所选对象无法转换为修订云线。",keywords:{arcLength:{display:"圆弧长度(A)",local:"圆弧长度",global:"ArcLength"},object:{display:"对象(O)",local:"对象",global:"Object"},rectangular:{display:"矩形(R)",local:"矩形",global:"Rectangular"},polygonal:{display:"多边形(P)",local:"多边形",global:"Polygonal"},freehand:{display:"手绘(F)",local:"手绘",global:"Freehand"},style:{display:"样式(S)",local:"样式",global:"Style"},normal:{display:"普通(N)",local:"普通",global:"Normal"},calligraphy:{display:"书法(C)",local:"书法",global:"Calligraphy"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},yes:{display:"是(Y)",local:"是",global:"Yes"},no:{display:"否(N)",local:"否",global:"No"}}},sketch:{specifySketch:"指定草图或",sketching:"移动指针进行草图绘制(单击或按 Enter 停止)",type:"输入草图类型",increment:"指定草图增量",tolerance:"指定样条曲线公差",firstPoint:"指定第一个点",nextPoint:"指定结束点",keywords:{type:{display:"类型(T)",local:"类型",global:"Type"},increment:{display:"增量(I)",local:"增量",global:"Increment"},tolerance:{display:"公差(L)",local:"公差",global:"Tolerance"},line:{display:"直线(L)",local:"直线",global:"Lines"},polyline:{display:"多段线(P)",local:"多段线",global:"Polyline"},spline:{display:"样条曲线(S)",local:"样条曲线",global:"Spline"}}},spline:{firstPoint:"指定第一个点",nextPoint:"指定下一个点(或按 Enter 完成)",firstPointWithOptions:"指定第一个点或",nextPointWithFitOptions:"指定下一个点或",nextPointWithCvOptions:"指定下一个控制顶点或",methodPrompt:"输入样条创建方式",knotsPrompt:"输入节点参数化方式",degreePrompt:"指定样条次数",keywords:{method:{display:"方法(M)",local:"方法",global:"Method"},fit:{display:"拟合(F)",local:"拟合",global:"Fit"},cv:{display:"控制顶点(C)",local:"控制顶点",global:"CV"},knots:{display:"节点(K)",local:"节点",global:"Knots"},degree:{display:"次数(D)",local:"次数",global:"Degree"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},chord:{display:"弦长(C)",local:"弦长",global:"Chord"},sqrtChord:{display:"平方根弦长(S)",local:"平方根弦长",global:"SqrtChord"},uniform:{display:"均匀(U)",local:"均匀",global:"Uniform"}}},sysvar:{prompt:"请输入新的值"},zoom:{mainPrompt:"指定窗口角点或",firstCorner:"指定第一个角点",secondCorner:"指定对角点",centerPoint:"指定缩放中心点",heightOrScale:"输入高度或比例因子(nX 或 nXP)",scaleFactor:"输入比例因子(nX 或 nXP)",keywords:{all:{display:"全部(A)",local:"全部",global:"All"},center:{display:"中心(C)",local:"中心",global:"Center"},extents:{display:"范围(E)",local:"范围",global:"Extents"},previous:{display:"上一个(P)",local:"上一个",global:"Previous"},scale:{display:"比例(S)",local:"比例",global:"Scale"},window:{display:"窗口(W)",local:"窗口",global:"Window"}}},chtml:{exportInvisibleLayers:"是否导出不可见图层",initialView:"打开 HTML 时的初始视图",viewerMode:"离线查看器模式",keywords:{yes:{display:"是(Y)",local:"是",global:"Yes"},no:{display:"否(N)",local:"否",global:"No"},extents:{display:"范围(E)",local:"范围",global:"Extents"},current:{display:"当前(C)",local:"当前",global:"Current"},view:{display:"查看(V)",local:"查看",global:"View"},measure:{display:"测量(M)",local:"测量",global:"Measure"}}}},Om={document:{untitled:"未命名"},commandLine:{noLast:"(无上一次命令)",unknownCommand:"未知命令",executed:"已执行命令",showHistory:"显示命令历史",placeholder:"输入命令",showMessages:"显示消息历史",canceled:"*已取消*",noHistory:"(无历史记录)",invalidInput:"输入无效。",close:"关闭命令行"},inputManager:{firstCorner:"指定第一个角点或",secondCorner:"指定第二个角点或"},message:{fetchingDrawingFile:"正在加载图纸文件...",exportingDxf:"正在导出 DXF ...",exportingEntityPreview:"正在导出图片 ...",collectingMemoryProfile:"正在分析内存 ...",fontCached:"字体已成功缓存",fontCacheFailed:"缓存字体失败"},progress:{start:"开始解析文件...",parse:"正在解析文件 ...",font:"正在下载图纸所需字体...",ltype:"正在解析线形...",style:"正在解析文字样式...",dimstyle:"正在解析标注样式...",layer:"正在解析图层...",vport:"正在解析视口...",blockrecord:"正在解析BTRs...",header:"正在解析文件头...",block:"正在解析块..",entity:"正在解析图元...",object:"正在解析NODs...",rendering:"正在渲染图纸 ...",end:"完成!"},about:{title:"关于",close:"关闭",product:"CAD 查看器",tagline:"面向 DWG/DXF 图纸的高性能 Web CAD 查看器。",website:"官网",docs:"文档",repository:"GitHub",copyright:"© {year} mlightcad。保留所有权利。",ok:"确定"},drawStyle:{color:"颜色",lineWeight:"线宽",fontSize:"字号"}};d.mergeLocaleMessage("en",{command:Cm,jig:_m,main:Em}),d.mergeLocaleMessage("zh",{command:Mm,jig:Dm,main:Om}),d.mergeLocaleMessage("tr",{command:Lm,jig:Tm,main:Im}),d.mergeLocaleMessage("cs",{command:Sm,jig:Pm,main:Am});const xr=(s,e)=>{const t=`command.${s}.${e}`;return d.t(t)},jm=s=>xr(ce.SYSTEMT_COMMAND_GROUP_NAME,s),Bm=s=>xr(ce.DEFAUT_COMMAND_GROUP_NAME,s);class Sr{constructor(e){this.options=e}parse(e){const t=e.trim();if(t.length===0)return this.options.allowNone,null;const i=this.options.keywords.findByName(t);return i?i.globalName:this.options.allowArbitraryInput?t:null}parseCommandLine(e,t){return this.parse(e)}}class jl{start(){return new Promise(e=>{this.resolve=e,this.onStart()})}finish(e){this.cleanup(),this.resolve(e)}}class Fm extends jl{constructor(e,t,i=!0){super(),this.cli=e,this.options=t,this.allowTyping=i,this.handler=new Sr(t)}onStart(){this.cli.clearInput(),this.cli.setInputReadOnly(!this.allowTyping),this.cli.renderKeywordPrompt(this.options,e=>this.finish(e)),this.cli.focusInput()}handleEnter(e){if(!this.allowTyping)return!0;if(!e.trim()){const i=this.options.keywords.default;return i!=null&&i.enabled?(this.finish(i.globalName),!0):this.options.allowNone?(this.finish(""),!0):!1}const t=this.handler.parse(e);return t!==null?(this.finish(t),!0):!1}handleEscape(){this.finish("")}cleanup(){this.cli.setInputReadOnly(!1),this.cli.clear()}}class zm extends jl{constructor(e,t,i,n,r,o=!0){super(),this.cli=e,this.options=t,this.parseValue=i,this.mode=n,this.allowNone=r,this.allowTyping=o,this.options.keywords.count>0&&(this.keywordHandler=new Sr(this.options))}onStart(){this.cli.clearInput(),this.cli.setInputReadOnly(!this.allowTyping),this.cli.renderKeywordPrompt(this.options,e=>this.finish({kind:"keyword",keyword:e})),this.cli.focusInput()}handleEnter(e){if(!this.allowTyping)return!0;if(!e.trim()){const i=this.options.keywords.default;return i!=null&&i.enabled?(this.finish({kind:"keyword",keyword:i.globalName}),!0):this.allowNone?(this.finish({kind:"none"}),!0):!1}if(this.mode==="keyword")return this.tryResolveKeyword(e);if(this.mode==="string"){if(this.tryResolveKeyword(e))return!0;const i=this.parseValue(e);return i!==null?(this.finish({kind:"value",value:i}),!0):!1}const t=this.parseValue(e);return t!==null?(this.finish({kind:"value",value:t}),!0):this.tryResolveKeyword(e)}handleEscape(){this.finish({kind:"none"})}cleanup(){this.cli.setInputReadOnly(!1),this.cli.clear()}tryResolveKeyword(e){if(!this.keywordHandler)return!1;const t=this.keywordHandler.parse(e);return t===null?!1:(this.finish({kind:"keyword",keyword:t}),!0)}}class Bl{constructor(e=document.body){this.isPromptActive=!1,this.recentMessages=[],this.isCommandLifecycleBound=!1,this.container=e,this.history=[],this.historyIndex=-1,this.lastExecuted=null,this.isCmdPopupOpen=!1,this.isMsgPanelOpen=!1,this.minWidth=420,this.widthRatio=.66,this.autoCompleteIndex=-1,this.injectCSS(),this.createUI(),this.bindEvents(),this.bindCommandLifecycleEvents(),this.resizeHandler(),window.addEventListener("resize",()=>this.resizeHandler()),this.resizeObserver=new ResizeObserver(()=>this.resizeHandler()),this.resizeObserver.observe(this.container),d.events.localeChanged.addEventListener(()=>this.refreshLocale())}get visible(){return this.cliContainer.style.display!=="none"}set visible(e){this.cliContainer.style.display=e?"block":"none"}setPrompt(e){this.isPromptActive=!0;const t=(e==null?void 0:e.trim().replace(/[::]\s*$/,""))??"";this.promptEl.innerHTML=t?`${t}: `:"",this.textInput.placeholder="",this.recordRecentMessage(t?`${t}:`:e)}clear(){this.clearPrompt(),this.clearInput()}clearPrompt(){this.promptEl.innerHTML="",this.isPromptActive=!1}clearInput(){this.textInput.value="",this.textInput.placeholder=this.isPromptActive?"":this.localize("main.commandLine.placeholder")}focusInput(){this.textInput.focus()}setInputReadOnly(e){this.textInput.readOnly=e}showMessage(e,t="info",i){this.appendMessage(e,t,i)}cancelActiveSession(){this.activeSession&&(this.activeSession.handleEscape(),this.activeSession=void 0)}async getKeywords(e,t=!0){const i=new Fm(this,e,t);this.activeSession=i;try{return await i.start()}finally{this.activeSession=void 0}}async getPromptInput(e,t,i){const n=new zm(this,e,t,i.mode,i.allowNone,i.allowTyping??!0);this.activeSession=n;try{return await n.start()}finally{this.activeSession=void 0}}localize(e,t){return d.t(e,{fallback:t})}refreshLocale(){Array.from(this.msgPanel.children).forEach(e=>{var n,r,o,a;const t=e,i=t.dataset.msgKey;if(i)if(i==="main.commandLine.executed"){const l=((r=(n=t.textContent)==null?void 0:n.split(":")[1])==null?void 0:r.trim())??"";t.textContent=`${this.localize(i)}: ${l}`}else if(i==="main.commandLine.unknownCommand"){const l=((a=(o=t.textContent)==null?void 0:o.split(":")[1])==null?void 0:a.trim())??"";t.textContent=`${this.localize(i)}: ${l}`}else t.textContent=this.localize(i)}),this.centerEl.setAttribute("data-placeholder",this.localize("main.commandLine.placeholder")),!this.isPromptActive&&!this.textInput.value&&(this.textInput.placeholder=this.localize("main.commandLine.placeholder")),this.downBtn.title=this.localize("main.commandLine.showHistory"),this.upBtn.title=this.localize("main.commandLine.showMessages")}executeCommand(e){if(!e||!e.trim())if(this.lastExecuted)e=this.lastExecuted;else{this.showMessage(this.localize("main.commandLine.noLast","(no last command)"));return}const t=this.resolveCommand(e);if(!t){const n=this.localize("main.commandLine.unknownCommand");this.showMessage(`${n}: ${e}`,"warning");return}this.history.push(t.globalName),this.historyIndex=this.history.length,this.lastExecuted=t.globalName,this.printHistoryLine(e);const i=this.localize("main.commandLine.executed");this.showMessage(`${i}: ${t.localName}`),k.instance.sendStringToExecute(e),this.clearInput()}injectCSS(){const e=document.createElement("style");e.textContent=`
263
+ `;return this.encodeSvgToCursor(o,n+t,n+t)}}function Dl(s){const e=s??d.acdbHostApplicationServices().workingDatabase,t=d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.ORTHOMODE,e);return Number(t)!==0}function Ol(s,e){const t=s.x-e.x,i=s.y-e.y;return Math.abs(t)>=Math.abs(i)?{x:s.x,y:e.y}:{x:e.x,y:s.y}}const Wt=2,Bl=4;function ki(s){return s??d.acdbHostApplicationServices().workingDatabase}function jl(s,e,t){const i=d.AcDbSysVarManager.instance().getVar(s,e),n=Number(i);return Number.isFinite(n)?n:t}function Nm(s,e){const t=d.AcDbSysVarManager.instance().getVar(s,e);return t==null?"":String(t)}function Dn(s){const e=ki(s);return jl(d.AcDbSystemVariables.POLARMODE,e,0)}function Fl(s){const e=ki(s);return jl(d.AcDbSystemVariables.POLARANG,e,90)}function zl(s){const e=ki(s);return Nm(d.AcDbSystemVariables.POLARADDANG,e)}function Nl(s){return(Dn(s)&Wt)!==0}function Rm(s,e,t){let i=s-e;return t===1&&(i=-i),d.AcGeMathUtil.normalizeAngle(i)}function Vm(s,e,t){let i=s;return t===1&&(i=-i),d.AcGeMathUtil.normalizeAngle(i+e)}function Gm(s){if(!s.trim())return[];const e=[];for(const t of s.split(";")){const i=t.trim();if(!i)continue;const n=Number(i);if(Number.isFinite(n)&&(e.push((n%360+360)%360),e.length>=10))break}return e}function Km(s,e){const t=Dn(s),i=(t&Wt)!==0,n=(t&Bl)!==0,r=new Set;if(e.includeOrtho)for(const o of[0,90,180,270])r.add(o);if(i){const o=Fl(s);if(o>0){const a=Math.max(1,Math.round(360/o));for(let l=0;l<a;l++)r.add((l*o%360+360)%360)}if(n)for(const a of Gm(zl(s)))r.add(a)}return[...r].map(d.AcGeMathUtil.degToRad)}function Rl(s,e){const t=Math.abs(d.AcGeMathUtil.normalizeAngle(s-e));return Math.min(t,Math.PI*2-t)}function Um(s,e){let t=e[0],i=Rl(s,t);for(let n=1;n<e.length;n++){const r=e[n],o=Rl(s,r);o<i&&(i=o,t=r)}return t}function Vl(s,e,t){const i=ki(t),n=Dl(i),r=Nl(i);if(!n&&!r)return s;if(n&&!r)return Ol(s,e);const o=s.x-e.x,a=s.y-e.y,l=Math.hypot(o,a);if(l<1e-10)return s;const c=Math.atan2(a,o),h=Rm(c,i.angbase,i.angdir),p=Km(i,{includeOrtho:n});if(p.length===0)return s;const m=Um(h,p),g=Vm(m,i.angbase,i.angdir);return{x:e.x+l*Math.cos(g),y:e.y+l*Math.sin(g)}}function Hm(s){const e=ki(s),t=Dn(e),i=(t&Wt)!==0?t&~Wt:t|Wt;return d.AcDbSysVarManager.instance().setVar(d.AcDbSystemVariables.POLARMODE,i,e),i}class On{constructor(e=[]){this.events={selectionAdded:new d.AcCmEventManager,selectionRemoved:new d.AcCmEventManager},this._ids=new Set(e)}get ids(){return Array.from(this._ids)}get count(){return this._ids.size}add(e){Array.isArray(e)?(e.forEach(t=>this._ids.add(t)),this.events.selectionAdded.dispatch({ids:e})):(this._ids.add(e),this.events.selectionAdded.dispatch({ids:[e]}))}delete(e){Array.isArray(e)?(e.forEach(t=>this._ids.delete(t)),this.events.selectionRemoved.dispatch({ids:e})):(this._ids.delete(e),this.events.selectionRemoved.dispatch({ids:[e]}))}has(e){return this._ids.has(e)}clear(){if(this._ids.size>0){const e=Array.from(this._ids);this._ids.clear(),this.events.selectionRemoved.dispatch({ids:e})}}}class Cr{constructor(e,t,i,n=!0,r=!1,o=!0){this._displayName=e,this._globalName=t??e,this._localName=i??this._globalName,this._enabled=n,this._isReadOnly=r,this._visible=o}get displayName(){return this._displayName}set displayName(e){this._isReadOnly||(this._displayName=e)}get enabled(){return this._enabled}set enabled(e){this._isReadOnly||(this._enabled=e)}get globalName(){return this._globalName}set globalName(e){this._isReadOnly||(this._globalName=e)}get isReadOnly(){return this._isReadOnly}get localName(){return this._localName}set localName(e){this._isReadOnly||(this._localName=e)}get visible(){return this._visible}set visible(e){this._isReadOnly||(this._visible=e)}get alias(){return this._globalName.replace(/[^A-Z]/g,"")}}class Gl{constructor(e){if(this._keywords=[],!e)return;const t=e.trim().split(/\s+/),i=[],n=[];let r=!1;for(const a of t){if(a==="_"){r=!0;continue}(r?n:i).push(a)}const o=Math.max(i.length,n.length);for(let a=0;a<o;a++){const l=i[a],c=n[a],h=S=>{if(!S)return;const P=S.indexOf(",");return P>=0?S.substring(0,P):S},p=h(c),m=h(l),g=p!==void 0,f=m!==void 0,w=g?p:"",v=f?m:void 0,x=new Cr(w||v||"",w,v,!0,!1,!0);this._keywords.push(x)}}add(e,t,i,n=!0,r=!0){let o,a,l;t===void 0?(o=e,a=e,l=e):i===void 0?(o=t,a=e,l=t):(o=e,a=t,l=i);const c=new Cr(o,a,l,n,!1,r);return this._keywords.push(c),c}clear(){this._keywords=[],this._defaultKeyword=void 0}toArray(){return this._keywords.slice()}get default(){return this._defaultKeyword}set default(e){if(e&&!this._keywords.includes(e))throw new Error("Default keyword must be one of the collection's keywords");this._defaultKeyword=e}getDisplayString(e=!1){return this._keywords.filter(i=>i.visible&&i.enabled).map(i=>(!e&&this._defaultKeyword===i,i.displayName)).join("/")}getPromptFormat(){const e=this._keywords.filter(r=>r.visible).map(r=>r.displayName),t=this._defaultKeyword&&this._defaultKeyword.visible?this._defaultKeyword.displayName:void 0,i=`[${e.join("/")}]`,n=t?` <${t}>`:"";return{visibleKeywords:e,defaultKeyword:t,formattedTail:`${i}${n}:`}}[Symbol.iterator](){let e=0;const t=this._keywords;return{next(){return e<t.length?{done:!1,value:t[e++]}:{done:!0,value:void 0}}}}findByDisplayName(e){return this._keywords.find(t=>t.displayName.toLowerCase()===e.toLowerCase())}findByGlobalName(e){return this._keywords.find(t=>t.globalName.toLowerCase()===e.toLowerCase())}findByName(e){if(!e)return;let t=e.trim();if(!t)return;const i=t.startsWith("_");i&&(t=t.substring(1));const n=t.toLowerCase();return this._keywords.find(r=>r.enabled?r.globalName.toLowerCase()===n?!0:i?!1:!!(r.localName&&r.localName.toLowerCase()===n||r.alias&&r.alias.toLowerCase()===n||r.displayName.toLowerCase()===n):!1)}get count(){return this._keywords.length}}class We{constructor(e,t){this._message="",this._appendKeywordsToMessage=!0,this._isReadOnly=!1,this._keywords=new Gl,t!==void 0?this.setMessageAndKeywords(e,t):this._message=e}get jig(){return this._jig}set jig(e){this._isReadOnly||(this._jig=e)}get message(){return this._message}set message(e){this._isReadOnly||(this._message=e)}getDefaultValueDisplayText(){}getDisplayMessage(){const e=this.getDefaultValueDisplayText();return e==null?this._message:`${this._message.trim().replace(/[::]\s*$/,"")} <${e}>`}get appendKeywordsToMessage(){return this._appendKeywordsToMessage}set appendKeywordsToMessage(e){this._isReadOnly||(this._appendKeywordsToMessage=e)}get isReadOnly(){return this._isReadOnly}get keywords(){return this._keywords}getKeywordPromptFormat(){return this._keywords.getPromptFormat()}setMessageAndKeywords(e,t){if(this._isReadOnly)return this;const i=e.match(/^(.*?)\s*\[(.*?)\](.*)?$/);if(i){const[,n,r]=i;if(this._message=n.trim(),r!==void 0){const o=r.split("/").map(a=>a.trim()).filter(a=>a.length>0);this._keywords.clear();for(const a of o){let c=t.split(/\s+/).find(h=>h.toLowerCase()===a.toLowerCase());c||(c=a),this._keywords.add(a,c)}}}return this}}class Se extends We{constructor(e,t){super(e,t),this._useBasePoint=!0,this._useDashedLine=!0,this._useAngleBase=!1,this._defaultValue=0,this._useDefaultValue=!1,this._allowZero=!0,this._allowNegative=!1,this._allowNone=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new d.AcGePoint3d(e))}get baseAngle(){return this._baseAngle??0}set baseAngle(e){this.isReadOnly||(this._baseAngle=e)}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get useAngleBase(){return this._useAngleBase}set useAngleBase(e){this.isReadOnly||(this._useAngleBase=e)}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}getDefaultValueDisplayText(){if(this._useDefaultValue)return String(this._defaultValue)}get allowZero(){return this._allowZero}set allowZero(e){this.isReadOnly||(this._allowZero=e)}get allowNegative(){return this._allowNegative}set allowNegative(e){this.isReadOnly||(this._allowNegative=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}}class Bn extends We{constructor(e,t){super(e),this._useBasePoint=!1,this._useDashedLine=!1,this._disableOSnap=!1,this._allowNone=!1,this._secondCornerMessage=t}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get firstCornerMessage(){return this.message}set firstCornerMessage(e){this.isReadOnly||(this.message=e)}get secondCornerMessage(){return this._secondCornerMessage}set secondCornerMessage(e){this.isReadOnly||(this._secondCornerMessage=e)}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get disableOSnap(){return this._disableOSnap}set disableOSnap(e){this.isReadOnly||(this._disableOSnap=e)}}class Fe{constructor(e,t){this.status=e,this.stringResult=t}}class jn extends Fe{constructor(e,t,i){super(e,i),this.value=t}}class Fn extends We{constructor(e,t){super(e,t),this._defaultValue=0,this._useDefaultValue=!1,this._allowNone=!1,this._allowArbitraryInput=!1,this._allowNegative=!1,this._allowZero=!0}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}getDefaultValueDisplayText(){if(this._useDefaultValue)return String(this._defaultValue)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowArbitraryInput(){return this._allowArbitraryInput}set allowArbitraryInput(e){this.isReadOnly||(this._allowArbitraryInput=e)}get allowNegative(){return this._allowNegative}set allowNegative(e){this.isReadOnly||(this._allowNegative=e)}get allowZero(){return this._allowZero}set allowZero(e){this.isReadOnly||(this._allowZero=e)}}class be extends Fn{constructor(e){super(e),this._useBasePoint=!1,this._useDashedLine=!0,this._only2d=!0,this.allowNegative=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new d.AcGePoint3d(e))}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get only2d(){return this._only2d}set only2d(e){this.isReadOnly||(this._only2d=e)}}class ie extends Fn{}class _r extends Fe{constructor(e,t){super(e,void 0),this.value=t}}class Pe extends _r{constructor(e,t){super(e,t)}}class $e extends We{constructor(e,t){super(e,t),this._allowNone=!1,this._allowObjectOnLockedLayer=!1,this._rejectMessage="Invalid object selected.",this._allowedClasses=new Set}normalizeClassName(e){const t=e.trim();return t.startsWith("AcDb")?t.slice(4):t}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowObjectOnLockedLayer(){return this._allowObjectOnLockedLayer}set allowObjectOnLockedLayer(e){this.isReadOnly||(this._allowObjectOnLockedLayer=e)}get rejectMessage(){return this._rejectMessage}setRejectMessage(e){return this.isReadOnly||(this._rejectMessage=e),this}addAllowedClass(e){if(!this.isReadOnly){const t=this.normalizeClassName(e);t&&this._allowedClasses.add(t)}return this}removeAllowedClass(e){if(!this.isReadOnly){const t=this.normalizeClassName(e);t&&this._allowedClasses.delete(t)}return this}clearAllowedClasses(){return this.isReadOnly||this._allowedClasses.clear(),this}isClassAllowed(e){const t=this.normalizeClassName(e);return this._allowedClasses.size===0||this._allowedClasses.has(t)}}class zn extends Fe{constructor(e,t,i){super(e),this.objectId=t,this.pickedPoint=i}}class Er extends Fn{constructor(e,t,i){super(e),typeof t=="number"&&(this._lowerLimit=Math.floor(t)),typeof i=="number"&&(this._upperLimit=Math.ceil(i))}get lowerLimit(){return this._lowerLimit}set lowerLimit(e){this.isReadOnly||(this._lowerLimit=typeof e=="number"?Math.floor(e):void 0)}get upperLimit(){return this._upperLimit}set upperLimit(e){this.isReadOnly||(this._upperLimit=typeof e=="number"?Math.floor(e):void 0)}}class Nn extends _r{constructor(e,t){super(e,t)}}class ne extends We{constructor(e,t){super(e,t),this._allowNone=!1,this._allowArbitraryInput=!1}get valueDefaultDisplayText(){return this._valueDefaultDisplayText}set valueDefaultDisplayText(e){this.isReadOnly||(this._valueDefaultDisplayText=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowArbitraryInput(){return this._allowArbitraryInput}set allowArbitraryInput(e){this.isReadOnly||(this._allowArbitraryInput=e)}}class T extends We{constructor(e,t){super(e,t),this._useBasePoint=!1,this._useDashedLine=!1,this._allowNone=!1,this._disableOSnap=!1,this._useDefaultValue=!1}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(e==null?this._defaultValue=e:this._defaultValue=this._defaultValue?this._defaultValue.copy(e):new d.AcGePoint3d(e))}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}getDefaultValueDisplayText(){if(!this._useDefaultValue||!this._defaultValue)return;const{x:e,y:t,z:i}=this._defaultValue;return i===0?`${e},${t}`:`${e},${t},${i}`}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new d.AcGePoint3d(e))}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get disableOSnap(){return this._disableOSnap}set disableOSnap(e){this.isReadOnly||(this._disableOSnap=e)}}class Rn extends Fe{constructor(e,t){super(e,void 0),this.value=t}}class Pt extends We{constructor(e,t){super(e,t),this._singleOnly=!1}get singleOnly(){return this._singleOnly}set singleOnly(e){this._singleOnly=e}}class xi extends Fe{constructor(e,t,i){super(e,i),this.value=t}}class ce extends We{constructor(e,t){super(e,t),this._allowSpaces=!0,this._allowEmpty=!1,this._defaultValue="",this._useDefaultValue=!1}get allowSpaces(){return this._allowSpaces}set allowSpaces(e){this.isReadOnly||(this._allowSpaces=e)}get allowEmpty(){return this._allowEmpty}set allowEmpty(e){this.isReadOnly||(this._allowEmpty=e)}get maxLength(){return this._maxLength}set maxLength(e){this.isReadOnly||(this._maxLength=e)}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}getDefaultValueDisplayText(){if(this._useDefaultValue)return this._defaultValue}}var b=(s=>(s[s.Cancel=-5002]="Cancel",s[s.Error=-5001]="Error",s[s.Keyword=-5005]="Keyword",s[s.Modeless=5027]="Modeless",s[s.None=5e3]="None",s[s.OK=5100]="OK",s[s.Other=5028]="Other",s))(b||{});const at=class at{static get messages(){return this._messages}static getLocaleMessage(e){return this._messages[e]}static mergeLocaleMessage(e,t){Kl(this._messages[e],t)}static registerMessage(e,t){this.mergeLocaleMessage(e,t)}static setCurrentLocale(e){const t=this._currentLocale;this._currentLocale=e,this.events.localeChanged.dispatch({old:t,new:this._currentLocale})}static get currentLocale(){return this._currentLocale}static t(e,t){const i=this._currentLocale,n=this._messages[i],r=e.split(".");let o=n;for(const a of r){if(!o||typeof o!="object")return(t==null?void 0:t.fallback)??e;o=o[a]}return typeof o=="string"?o:(t==null?void 0:t.fallback)??e}static cmdKey(e,t,i){return`command.${e}.${t.toLowerCase()}.${i}`}static cmd(e,t,i){return this.t(this.cmdKey(e,t,i))}static cmdDescription(e,t){return this.cmd(e,t,"description")}static cmdPrompt(e,t){return this.cmd(e,t,"prompt")}static sysCmd(e,t){return this.cmd(de.SYSTEMT_COMMAND_GROUP_NAME,e,t)}static sysCmdKey(e,t){return this.cmdKey(de.SYSTEMT_COMMAND_GROUP_NAME,e,t)}static userCmd(e,t){return this.cmd(de.DEFAUT_COMMAND_GROUP_NAME,e,t)}static userCmdKey(e,t){return this.cmdKey(de.DEFAUT_COMMAND_GROUP_NAME,e,t)}static sysCmdDescription(e){return this.cmdDescription(de.SYSTEMT_COMMAND_GROUP_NAME,e)}static sysCmdPrompt(e){return this.cmdPrompt(de.SYSTEMT_COMMAND_GROUP_NAME,e)}};at._messages={en:{},zh:{},tr:{},cs:{}},at._currentLocale="en",at.events={localeChanged:new d.AcCmEventManager},at.userCmdDescription=e=>at.cmdDescription(de.DEFAUT_COMMAND_GROUP_NAME,e),at.userCmdPrompt=e=>at.cmdPrompt(de.DEFAUT_COMMAND_GROUP_NAME,e);let u=at;function Kl(s,e){for(const t of Object.keys(e)){const i=e[t],n=s[t];Ul(n)&&Ul(i)?Kl(n,i):s[t]=i}}function Ul(s){return typeof s=="object"&&s!==null}const Wm={ACAD:{"-hatch":{description:"Vytváří šrafování pomocí voleb příkazového řádku bez rozhraní pásu karet"},"-layer":{description:"Spravuje hladiny pomocí voleb příkazového řádku"},about:{description:"Zobrazí informace o mlightcad"},acadver:{description:"Ukládá identifikátor verze databáze výkresu (pouze pro čtení)"},angbase:{description:"Nastaví směr základního úhlu 0 vzhledem k aktuálnímu USS"},angdir:{description:"Určuje, zda se kladné úhly měří po směru nebo proti směru hodinových ručiček"},arc:{description:"Vytvoří oblouk"},aunits:{description:"Nastaví formát zobrazení úhlů"},auprec:{description:"Nastaví přesnost zobrazení úhlů, používá se společně s AUNITS"},cdxf:{description:"Exportuje aktuální výkres do DXF"},cpdf:{description:"Exportuje aktuální výkres do PDF"},cecolor:{description:"Nastaví aktuální výchozí barvu pro nově vytvářené objekty"},celtscale:{description:"Řídí měřítko typu čáry pro nově vytvářené objekty"},celtype:{description:"Nastaví typ čáry pro nově vytvářené objekty"},celweight:{description:"Nastaví výchozí tloušťku čáry pro nově vytvářené objekty"},cetransparency:{description:"Nastaví průhlednost pro nově vytvářené objekty"},cachefont:{description:"Uloží místní soubor fontu do IndexedDB pro vykreslování textu"},circle:{description:"Vytvoří jednu kružnici zadáním středu a poloměru"},clayer:{description:"Nastaví aktuální hladinu pro nové objekty a operace úprav"},cmleaderstyle:{description:"Nastaví název aktuálního stylu multiodkazu"},cmlscale:{description:"Řídí celkovou šířku multičáry"},cmlstyle:{description:"Nastaví název aktuálního stylu multičáry"},colortheme:{description:"Řídí barevný motiv uživatelského rozhraní (tmavý nebo světlý)"},copy:{description:"Kopíruje vybrané objekty vytvořením kopií na nových pozicích",prompt:"Vyberte objekty"},csvg:{description:"Převede aktuální výkres na SVG"},chtml:{description:"Exportuje aktuální výkres do samostatného offline souboru HTML"},"-chtml":{description:"Exportuje aktuální výkres do HTML pomocí voleb příkazového řádku"},dimlinear:{description:"Vytvoří lineární kóty"},dimstyle:{description:"Nastaví název aktuálního stylu kótování"},dwgname:{description:"Ukládá název aktuálního souboru výkresu (pouze pro čtení)"},loginname:{description:"Zobrazí přihlašovací jméno uživatele (pouze pro čtení)"},dynmode:{description:"Řídí nastavení dynamického zadávání u kurzoru"},dynprompt:{description:"Řídí zobrazení výzev v popiscích dynamického zadávání"},ellipse:{description:"Vytvoří elipsu nebo eliptický oblouk pomocí koncových bodů os nebo středu"},erase:{description:"Odstraní vybrané objekty z výkresu",prompt:"Vyberte objekty"},extmax:{description:"Ukládá pravý horní roh rozsahu výkresu v modelovém prostoru (pouze pro čtení)"},extmin:{description:"Ukládá levý dolní roh rozsahu výkresu v modelovém prostoru (pouze pro čtení)"},entout:{description:"Exportuje sloučený náhledový obrázek vybraných objektů",prompt:"Vyberte objekty"},hideobjects:{description:"Dočasně potlačí zobrazení vybraných objektů",prompt:"Vyberte objekty"},imageattach:{description:"Připojí rastrový obrázek jako externí referenci k aktuálnímu výkresu"},"-insert":{description:"Vloží definici bloku do aktuálního výkresu (příkazový řádek)"},xattach:{description:"Připojí výkres DWG nebo DXF jako externí referenci k aktuálnímu výkresu"},gripcolor:{description:"Nastaví barvu nevybraných gripů zobrazených na vybraných objektech"},griphot:{description:"Nastaví barvu vybraných (aktivních) gripů"},gripobjlimit:{description:"Potlačí zobrazení gripů, když výběr přesáhne zadaný počet objektů (0 = bez omezení)"},grips:{description:"Řídí, zda se na vybraných objektech zobrazují gripy"},gripsize:{description:"Nastaví velikost gripů v pixelech"},hatch:{description:"Vyplní uzavřenou oblast nebo vybrané objekty vzorem šrafování"},ipdf:{description:"Importuje vektorovou geometrii ze souboru PDF"},hpang:{description:"Nastaví výchozí úhel v radiánech pro nově vytvářené vzory šrafování"},hpassoc:{description:"Řídí, zda jsou nově vytvářená šrafování asociativní"},hpbackgroundcolor:{description:"Nastaví výchozí barvu pozadí pro nově vytvářené vzory šrafování"},hpcolor:{description:"Nastaví výchozí barvu pro nově vytvářená šrafování"},hpdouble:{description:"Řídí, zda jsou uživatelsky definované vzory šrafování zdvojené"},hpislanddetection:{description:"Řídí, jak se nakládá s ostrůvky uvnitř nově vytvářených hranic šrafování"},hplayer:{description:"Nastaví výchozí hladinu pro nově vytvářená šrafování a výplně"},hpname:{description:"Nastaví výchozí název vzoru pro nově vytvářená šrafování v této relaci"},hpscale:{description:"Nastaví výchozí měřítko pro nově vytvářené vzory šrafování"},hpseparate:{description:"Řídí, zda se pro více hranic vytvoří jeden nebo samostatné objekty šrafování"},hptransparency:{description:"Nastaví výchozí průhlednost pro nově vytvářená šrafování a výplně"},insunits:{description:"Určuje jednotky výkresu pro automatické měřítko vkládaných bloků, obrázků nebo externích referencí"},laycur:{description:"Změní hladinu vybraných objektů na aktuální hladinu",prompt:"Vyberte objekty pro změnu na aktuální hladinu"},laydel:{description:"Odstraní hladinu a všechny objekty na této hladině"},layerclose:{description:"Zavře Správce vlastností hladin"},layerp:{description:"Vrátí poslední změnu nebo sadu změn provedených v nastavení hladin"},layfrz:{description:"Zmrazí hladinu vybraných objektů",prompt:"Vyberte objekt na hladině ke zmrazení"},layiso:{description:"Izoluje hladiny vybraných objektů",prompt:"Vyberte objekty na hladinách k izolaci"},laylck:{description:"Uzamkne hladinu vybraných objektů",prompt:"Vyberte objekt na hladině k uzamčení"},layoff:{description:"Vypne hladinu vybraných objektů",prompt:"Vyberte objekt na hladině k vypnutí"},layon:{description:"Zapne všechny hladiny ve výkresu"},laythw:{description:"Rozmrazí všechny zmrazené hladiny ve výkresu"},layulk:{description:"Odemkne hladinu vybraných objektů",prompt:"Vyberte objekt na hladině k odemčení"},layuniso:{description:"Obnoví hladiny skryté nebo uzamčené příkazem LAYISO"},line:{description:"Kreslí úsečky mezi body"},log:{description:"Zaznamenává ladicí informace do konzole"},ltscale:{description:"Nastaví globální měřítko typu čáry pro výkres"},lunits:{description:"Nastaví formát zobrazení souřadnic a vzdáleností"},luprec:{description:"Nastaví přesnost zobrazení délkových jednotek, používá se společně s LUNITS"},lwdisplay:{description:"Řídí, zda se ve výkresu zobrazují tloušťky čar"},clearmeasurements:{description:"Odstraní všechna měření z aktuálního rozvržení"},measurementvis:{description:"Zobrazí nebo skryje měření na aktuálním rozvržení"},measurementexport:{description:"Exportuje měření do sidecar JSON souboru"},measurementimport:{description:"Importuje měření ze sidecar JSON souboru"},measurearea:{description:"Vypočítá plochu a obvod vybraných objektů nebo bodů"},measureangle:{description:"Změří úhel mezi dvěma čarami nebo třemi body"},measurearc:{description:"Změří délku oblouku"},measuredistance:{description:"Změří vzdálenost a přírůstky mezi dvěma body"},measurepoint:{description:"Změří souřadnice X/Y vybraného bodu"},measurement:{description:"Nastaví, zda výkres používá anglosaské (imperiální) nebo metrické jednotky"},measurementcolor:{description:"Nastaví barvu použitou pro překryvy měření"},modelbkcolor:{description:"Nastaví barvu pozadí kreslicí oblasti modelového prostoru"},mline:{description:"Vytvoří několik rovnoběžných čar jako jeden objekt multičáry"},move:{description:"Posune vybrané objekty o vektor přemístění",prompt:"Vyberte objekty"},offset:{description:"Vytvoří rovnoběžné kopie křivek, lomených čar nebo kružnic v zadané vzdálenosti"},mtext:{description:"Vytvoří jeden objekt víceřádkového textu"},open:{description:"Otevře existující soubor výkresu"},openprof:{description:"Řídí, zda se do konzole zaznamenávají časové profily fází otevírání souboru"},openperf:{description:"Otevře paletu výkonu otevření s časy z posledního otevření výkresu"},orthomode:{description:"Omezí pohyb kurzoru na vodorovnou nebo svislou osu"},osmode:{description:"Nastaví trvalé režimy uchopení objektů pomocí bitové hodnoty"},pan:{description:"Posune pohled beze změny směru pohledu nebo zvětšení"},paperbkcolor:{description:"Nastaví barvu pozadí kreslicí oblasti výkresového prostoru (rozvržení)"},pdmode:{description:"Řídí způsob zobrazení bodových entit POINT"},pdsize:{description:"Nastaví velikost zobrazení bodových entit POINT"},pickbox:{description:"Nastaví velikost (v pixelech) výběrového rámečku pro výběr objektů"},pline:{description:"Vytvoří křivku zadáním více bodů"},pngout:{description:"Exportuje do PNG"},point:{description:"Vytvoří body"},polaraddang:{description:"Ukládá další úhly polárního sledování jako seznam oddělený středníky"},polarang:{description:"Nastaví přírůstek polárního úhlu pro polární sledování"},polarmode:{description:"Řídí nastavení polárního sledování a sledování uchopení objektů"},polygon:{description:"Vytvoří pravidelný mnohoúhelník podle středu/poloměru nebo jedné hrany"},qnew:{description:"Zahájí nový výkres"},ray:{description:"Vytvoří polopřímku, která začíná v bodě a pokračuje do nekonečna"},rectang:{description:"Vytvoří obdélník zadáním dvou protilehlých rohů"},regen:{description:"Překreslí aktuální výkres"},revcloud:{description:"Vytvoří nebo upraví revizní obláček"},markuptext:{description:"Umístí textovou poznámku"},markupline:{description:"Vytvoří úsečkovou poznámku"},markuparrow:{description:"Vytvoří šipkovou poznámku"},markupcloud:{description:"Vytvoří revizní obláček"},markuprect:{description:"Vytvoří obdélníkovou poznámku"},markupcircle:{description:"Vytvoří kruhovou poznámku"},markuphighlight:{description:"Vytvoří zvýrazňovací obdélník"},markupcallout:{description:"Vytvoří odkazovou poznámku: zadejte hrot odkazu, umístěte textové pole a zadejte text"},markupstamp:{description:"Umístí razítko nebo vlastní symbol"},markupvis:{description:"Zobrazí nebo skryje poznámky"},clearmarkups:{description:"Vymaže všechny poznámky na aktuálním rozvržení"},markupexport:{description:"Exportuje poznámky do sidecar JSON souboru"},markupimport:{description:"Importuje poznámky ze sidecar JSON souboru"},markuppanel:{description:"Otevře paletu poznámek"},rotate:{description:"Otočí vybrané objekty kolem základního bodu",prompt:"Vyberte objekty"},select:{description:"Vybírá objekty"},shortcutmenu:{description:"Řídí dostupnost místních nabídek v oblasti výkresu"},sketch:{description:"Vytvoří řadu úseček kreslených od ruky"},spline:{description:"Vytvoří hladkou křivku splajn zadáním řídicích bodů"},textstyle:{description:"Nastaví název aktuálního textového stylu"},unitmode:{description:"Řídí zlomkové zobrazení souřadnic, když je LUNITS architektonický nebo zlomkový"},switchbg:{description:"Přepíná pozadí oblasti výkresu mezi bílou a černou"},unisolateobjects:{description:"Znovu zobrazí všechny objekty skryté příkazem HIDEOBJECTS"},undo:{description:"Vrátí zpět poslední operaci úpravy databáze",nothingToUndo:"Není co vrátit zpět."},redo:{description:"Zopakuje poslední vrácenou operaci úpravy databáze",nothingToRedo:"Není co zopakovat."},xline:{description:"Vytvoří konstrukční přímku, která se rozprostírá do nekonečna na obě strany"},zoom:{description:"Zvětší na maximální rozsah všech objektů"}},USER:{}},$m={arc:{startPointOrCenter:"Zadejte počáteční bod oblouku nebo",secondPointOrOptions:"Zadejte druhý bod oblouku nebo",secondPoint:"Zadejte druhý bod oblouku",startPoint:"Zadejte počáteční bod oblouku",centerPoint:"Zadejte středový bod oblouku",endPoint:"Zadejte koncový bod oblouku",endPointOrOptions:"Zadejte koncový bod oblouku nebo",centerPointOrOptions:"Zadejte středový bod oblouku",includedAngle:"Zadejte středový úhel",chordLength:"Zadejte délku tětivy",tangentDirection:"Zadejte směr tečny v počátečním bodě oblouku",radius:"Zadejte poloměr oblouku",keywords:{center:{display:"Střed(C)",local:"Střed",global:"Center"},end:{display:"Konec(E)",local:"Konec",global:"End"},angle:{display:"Úhel(A)",local:"Úhel",global:"Angle"},chordLength:{display:"délka Tětivy(L)",local:"Délka tětivy",global:"ChordLength"},direction:{display:"Směr(D)",local:"Směr",global:"Direction"},radius:{display:"Poloměr(R)",local:"Poloměr",global:"Radius"}},invalid:{threePoint:"Neplatný 3bodový oblouk: body jsou kolineární nebo nelze definovat oblouk.",center:"Neplatný vstup středu: počáteční a koncový bod musí ležet na stejné kružnici.",angle:"Neplatný vstup úhlu: středový úhel musí být větší než 0 a menší než 360 stupňů.",chordLength:"Neplatná délka tětivy: hodnota je mimo rozsah pro aktuální poloměr.",direction:"Neplatný směr: z tohoto směru tečny nelze sestrojit oblouk.",radius:"Neplatný poloměr: zadaný poloměr nemůže spojit počáteční a koncový bod."}},circle:{center:"Zadejte střed kružnice",centerOrOptions:"Zadejte středový bod kružnice nebo",radius:"Zadejte poloměr kružnice",radiusOrDiameter:"Zadejte poloměr kružnice nebo",diameter:"Zadejte průměr kružnice",twoPointFirst:"Zadejte první koncový bod průměru kružnice",twoPointSecond:"Zadejte druhý koncový bod průměru kružnice",threePointFirst:"Zadejte první bod na kružnici",threePointSecond:"Zadejte druhý bod na kružnici",threePointThird:"Zadejte třetí bod na kružnici",keywords:{threeP:{display:"3B(3P)",local:"3B",global:"3P"},twoP:{display:"2B(2P)",local:"2B",global:"2P"},diameter:{display:"Průměr(D)",local:"Průměr",global:"Diameter"}}},copy:{basePointOrOptions:"Zadejte základní bod nebo",displacementOrArray:"Zadejte přemístění nebo",secondPointOrArray:"Zadejte druhý bod nebo",modePrompt:"Zadejte volbu režimu kopírování",arrayItemCount:"Zadejte počet položek v poli včetně originálu",arraySecondPointOrFit:"Zadejte druhý bod nebo",arrayFitSecondPoint:"Zadejte druhý bod",keywords:{displacement:{display:"Přemístění(D)",local:"Přemístění",global:"Displacement"},mode:{display:"Režim(O)",local:"Režim",global:"Mode"},multiple:{display:"Vícenásobné(M)",local:"Vícenásobné",global:"Multiple"},single:{display:"Jednoduché(S)",local:"Jednoduché",global:"Single"},array:{display:"Pole(A)",local:"Pole",global:"Array"},fit:{display:"Přizpůsobit(F)",local:"Přizpůsobit",global:"Fit"}}},dimlinear:{xLine1Point:"Zadejte počátek první pomocné čáry",xLine2Point:"Zadejte počátek druhé pomocné čáry",dimLinePoint:"Zadejte umístění kótovací čáry"},ellipse:{axisEndpointOrOptions:"Zadejte koncový bod osy elipsy nebo",arcAxisEndpointOrCenter:"Zadejte koncový bod osy eliptického oblouku nebo",center:"Zadejte střed elipsy",firstAxisEndpoint:"Zadejte koncový bod osy",secondAxisEndpoint:"Zadejte druhý koncový bod osy",otherAxisOrRotation:"Zadejte vzdálenost k druhé ose nebo",rotationAngle:"Zadejte úhel otočení kolem hlavní osy",arcStartAngle:"Zadejte počáteční úhel eliptického oblouku",arcEndAngle:"Zadejte koncový úhel eliptického oblouku",keywords:{arc:{display:"Oblouk(A)",local:"Oblouk",global:"Arc"},center:{display:"Střed(C)",local:"Střed",global:"Center"},rotation:{display:"Otočení(R)",local:"Otočení",global:"Rotation"}},invalid:{axis:"Neplatný vstup osy: délka osy musí být větší než 0.",otherAxis:"Neplatný vstup druhé osy: vzdálenost musí být větší než 0.",rotation:"Neplatný vstup otočení: výsledná vedlejší osa musí být větší než 0."}},hatch:{prompt:"Vyberte objekt hranice nebo",pickPoint:"Zadejte vnitřní bod (nebo stiskněte Enter pro dokončení)",select:"Vyberte objekty k šrafování",patternName:"Zadejte název vzoru šrafování",scale:"Zadejte měřítko vzoru šrafování",angle:"Zadejte úhel vzoru šrafování",style:"Zadejte styl šrafování",associative:"Zadejte asociativitu",invalidBoundary:"Vybrané objekty netvoří uzavřenou hranici.",keywords:{pick:{display:"Vybrat body(P)",local:"Vybrat body",global:"PickPoints"},select:{display:"Vybrat objekty(S)",local:"Vybrat objekty",global:"SelectObjects"},cancel:{display:"Zrušit(C)",local:"Zrušit",global:"Cancel"},pattern:{display:"Vzor(P)",local:"Vzor",global:"Pattern"},scale:{display:"Měřítko(S)",local:"Měřítko",global:"Scale"},angle:{display:"Úhel(A)",local:"Úhel",global:"Angle"},style:{display:"Styl(T)",local:"Styl",global:"HatchStyle"},associative:{display:"Asociativní(AS)",local:"Asociativní",global:"AssociativeMode"},normal:{display:"Normální(N)",local:"Normální",global:"Normal"},outer:{display:"Vnější(O)",local:"Vnější",global:"Outer"},ignore:{display:"Ignorovat(I)",local:"Ignorovat",global:"Ignore"},yes:{display:"Ano(Y)",local:"Ano",global:"Yes"},no:{display:"Ne(N)",local:"Ne",global:"No"}}},hideobjects:{hidden:"objekt(ů) skryto",restored:"objekt(ů) obnoveno",nothingToRestore:"Žádné skryté objekty k obnovení"},entout:{longSidePrompt:"Zadejte velikost delší strany náhledu v pixelech",exported:"náhled(ů) objektů exportováno",skipped:"objekt(ů) přeskočeno",failed:{"no-preview-root":"Nelze sestavit geometrii náhledu pro výběr","no-bounds":"Nelze vypočítat rozsah náhledu pro výběr","capture-failed":"Nelze vykreslit náhledový obrázek entity","download-failed":"Náhled byl vykreslen, ale stažení PNG selhalo"}},layer:{main:"Zadejte volbu",listSummary:"Seznam hladin byl vypsán do konzole prohlížeče",emptyInput:"Nebyl zadán žádný název hladiny.",newPrompt:"Zadejte název nové hladiny (nebo hladin)",makePrompt:"Zadejte název hladiny, která se má stát aktuální",setPrompt:"Zadejte název hladiny, která se má nastavit jako aktuální",onPrompt:"Zadejte název (názvy) hladiny k zapnutí",offPrompt:"Zadejte název (názvy) hladiny k vypnutí",freezePrompt:"Zadejte název (názvy) hladiny ke zmrazení",thawPrompt:"Zadejte název (názvy) hladiny k rozmrazení",lockPrompt:"Zadejte název (názvy) hladiny k uzamčení",unlockPrompt:"Zadejte název (názvy) hladiny k odemčení",colorLayerPrompt:"Zadejte název (názvy) hladiny ke změně barvy",colorValuePrompt:"Zadejte barvu (ACI 1-255, RGB např. 255,0,0, nebo CSS název barvy)",invalidColor:"Neplatný vstup barvy.",descriptionLayerPrompt:"Zadejte název hladiny k úpravě popisu",descriptionValuePrompt:"Zadejte nový popis hladiny",created:"Počet vytvořených hladin",alreadyExists:"Hladina již existuje",notFound:"Hladina nenalezena",cannotChangeCurrent:"Nelze vypnout ani zmrazit aktuální hladinu.",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"Vytvořit(M)",local:"Vytvořit",global:"Make"},set:{display:"Nastavit(S)",local:"Nastavit",global:"Set"},new:{display:"Nová(N)",local:"Nová",global:"New"},on:{display:"Zapnout(ON)",local:"Zapnout",global:"On"},off:{display:"Vypnout(OF)",local:"Vypnout",global:"Off"},color:{display:"Barva(C)",local:"Barva",global:"Color"},freeze:{display:"Zmrazit(F)",local:"Zmrazit",global:"Freeze"},thaw:{display:"Rozmrazit(T)",local:"Rozmrazit",global:"Thaw"},lock:{display:"Uzamknout(L)",local:"Uzamknout",global:"Lock"},unlock:{display:"Odemknout(U)",local:"Odemknout",global:"Unlock"},description:{display:"Popis(D)",local:"Popis",global:"Description"}}},layon:{alreadyOn:"Všechny hladiny jsou již zapnuté.",turnedOn:"Zapnuté hladiny"},laycur:{prompt:"Vyberte objekty ke změně na aktuální hladinu",currentLayerNotFound:"Aktuální hladina nenalezena.",noObjects:"Nebyly vybrány žádné platné objekty.",alreadyCurrent:"Vybrané objekty jsou již na aktuální hladině.",changed:"Objekty změněny na aktuální hladinu"},layfrz:{prompt:"Vyberte objekt na hladině ke zmrazení nebo",invalidSelection:"Vybrán neplatný objekt.",settingsPrompt:"Zadejte nastavení LAYFRZ ke změně",viewportPrompt:"Zadejte chování zmrazení ve výřezu",blockSelectionPrompt:"Zadejte chování výběru vnořeného bloku",vpfreezeFallback:"Aktuální prohlížeč nepodporuje zmrazení hladiny podle výřezu; místo toho se použije chování Zmrazit.",nestedSelectionLimited:"Nastavení výběru vnořeného bloku se uloží, ale aktuální výběr stále vyhodnocuje hladinu entity nejvyšší úrovně.",layerNotFound:"Hladina nenalezena",cannotFreezeCurrent:"Nelze zmrazit aktuální hladinu.",alreadyFrozen:"Hladina je již zmrazená",frozen:"Zmrazená hladina",restored:"Obnovená hladina",nothingToUndo:"Neexistuje žádná akce LAYFRZ k vrácení zpět.",keywords:{settings:{display:"Nastavení(S)",local:"Nastavení",global:"Settings"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},viewports:{display:"Výřezy(V)",local:"Výřezy",global:"Viewports"},blockSelection:{display:"Výběr bloku(B)",local:"Výběr bloku",global:"BlockSelection"},freeze:{display:"Zmrazit(F)",local:"Zmrazit",global:"Freeze"},vpfreeze:{display:"Zmrazit ve výřezu(V)",local:"Zmrazit ve výřezu",global:"Vpfreeze"},block:{display:"Blok(B)",local:"Blok",global:"Block"},entity:{display:"Entita(E)",local:"Entita",global:"Entity"},none:{display:"Žádný(N)",local:"Žádný",global:"None"}}},layiso:{prompt:"Vyberte objekty na hladině (hladinách) k izolaci nebo",settingsPrompt:"Zadejte nastavení pro neizolované hladiny",offModePrompt:"Zadejte chování vypnutí pro neizolované hladiny",noLayers:"Nebyly vybrány žádné platné hladiny.",layerNotFound:"Hladina nenalezena",isolated:"Izolovaná hladina (hladiny)",affectedLayers:"ovlivněné hladiny",vpfreezeFallback:"Aktuální prohlížeč nepodporuje zmrazení hladiny podle výřezu; místo toho se použije chování Vypnout.",lockFadeFallback:"Aktuální prohlížeč nepodporuje ztlumení zobrazení hladiny; neizolované hladiny budou uzamčeny bez ztlumení.",keywords:{settings:{display:"Nastavení(S)",local:"Nastavení",global:"Settings"},off:{display:"Vypnout(O)",local:"Vypnout",global:"Off"},lockAndFade:{display:"Uzamknout a ztlumit(L)",local:"Uzamknout a ztlumit",global:"LockAndFade"},vpfreeze:{display:"Zmrazit ve výřezu(V)",local:"Zmrazit ve výřezu",global:"Vpfreeze"}}},layuniso:{noPrevious:"Neexistuje žádný předchozí stav hladin LAYISO k obnovení.",layerNotFound:"Hladina nenalezena",nothingRestored:"Nebyly obnoveny žádné změny hladin LAYISO.",restored:"Obnovené hladiny"},laythw:{alreadyThawed:"Všechny hladiny jsou již rozmrazené.",thawed:"Rozmrazené hladiny"},laylck:{prompt:"Vyberte objekt na hladině k uzamčení",invalidSelection:"Vybrán neplatný objekt.",layerNotFound:"Hladina nenalezena",alreadyLocked:"Hladina je již uzamčená",locked:"Uzamčená hladina"},layulk:{prompt:"Vyberte objekt na hladině k odemčení",invalidSelection:"Vybrán neplatný objekt.",layerNotFound:"Hladina nenalezena",alreadyUnlocked:"Hladina je již odemčená",unlocked:"Odemčená hladina"},layoff:{prompt:"Vyberte objekt na hladině k vypnutí nebo",invalidSelection:"Vybrán neplatný objekt.",settingsPrompt:"Zadejte nastavení LAYOFF ke změně",viewportPrompt:"Zadejte chování výřezu",blockSelectionPrompt:"Zadejte chování výběru vnořeného bloku",vpfreezeFallback:"Aktuální prohlížeč nepodporuje vypnutí hladiny podle výřezu; místo toho se použije chování Vypnout.",nestedSelectionLimited:"Nastavení výběru vnořeného bloku se uloží, ale aktuální výběr stále vyhodnocuje hladinu entity nejvyšší úrovně.",layerNotFound:"Hladina nenalezena",cannotTurnOffCurrent:"Nelze vypnout aktuální hladinu.",alreadyOff:"Hladina je již vypnutá",turnedOff:"Vypnutá hladina",restored:"Obnovená hladina",nothingToUndo:"Neexistuje žádná akce LAYOFF k vrácení zpět.",keywords:{settings:{display:"Nastavení(S)",local:"Nastavení",global:"Settings"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},viewports:{display:"Výřezy(V)",local:"Výřezy",global:"Viewports"},blockSelection:{display:"Výběr bloku(B)",local:"Výběr bloku",global:"BlockSelection"},off:{display:"Vypnout(O)",local:"Vypnout",global:"Off"},vpfreeze:{display:"Zmrazit ve výřezu(V)",local:"Zmrazit ve výřezu",global:"Vpfreeze"},block:{display:"Blok(B)",local:"Blok",global:"Block"},entity:{display:"Entita(E)",local:"Entita",global:"Entity"},none:{display:"Žádný(N)",local:"Žádný",global:"None"}}},layerp:{restored:"Obnoven předchozí stav hladin.",noPreviousState:"Neexistuje žádný předchozí stav hladin k obnovení."},line:{firstPoint:"Zadejte první bod",firstPointOrContinue:"Zadejte první bod nebo",nextPoint:"Zadejte další bod",nextPointWithOptions:"Zadejte další bod nebo",keywords:{continue:{display:"Pokračovat(C)",local:"Pokračovat",global:"Continue"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},close:{display:"Uzavřít(C)",local:"Uzavřít",global:"Close"}}},xline:{firstPointOrOptions:"Zadejte bod nebo",secondPoint:"Zadejte druhý bod",throughPoint:"Zadejte bod, kterým má přímka procházet",angle:"Zadejte úhel konstrukční přímky",invalidDirection:"Neplatný směr pro XLINE.",keywords:{hor:{display:"Vodorovně(H)",local:"Vodorovně",global:"Hor"},ver:{display:"Svisle(V)",local:"Svisle",global:"Ver"},ang:{display:"Úhel(A)",local:"Úhel",global:"Ang"}}},ray:{startPoint:"Zadejte počáteční bod",throughPoint:"Zadejte bod, kterým má polopřímka procházet"},mline:{startPointWithOptions:"Zadejte počáteční bod nebo",nextPointWithOptions:"Zadejte další bod nebo",justificationPrompt:"Zadejte typ zarovnání",scalePrompt:"Zadejte měřítko multičáry",stylePrompt:"Zadejte název stylu multičáry nebo [?] pro seznam",styleNotFound:"Styl multičáry nenalezen",styleListHeader:"Načtené styly multičáry",styleListEmpty:"V aktuálním výkresu není načten žádný styl multičáry.",keywords:{justification:{display:"Zarovnání(J)",local:"Zarovnání",global:"Justification"},scale:{display:"Měřítko(S)",local:"Měřítko",global:"Scale"},style:{display:"Styl(ST)",local:"Styl",global:"Style"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},close:{display:"Uzavřít(C)",local:"Uzavřít",global:"Close"},top:{display:"Nahoře(T)",local:"Nahoře",global:"Top"},zero:{display:"Nula(Z)",local:"Nula",global:"Zero"},bottom:{display:"Dole(B)",local:"Dole",global:"Bottom"}}},measureAngle:{vertex:"Zadejte vrchol",arm1:"Zadejte bod na prvním rameni",arm2:"Zadejte bod na druhém rameni"},measureArc:{startPoint:"Zadejte počáteční bod oblouku",throughPoint:"Zadejte bod na oblouku",endPoint:"Zadejte koncový bod oblouku",lockedEndPoint:"Zadejte koncový bod oblouku (Ctrl přepne velký/malý oblouk)",invalidPoints:"Tři body jsou kolineární a nedefinují oblouk."},measureArea:{firstPoint:"Zadejte první bod",nextPoint:"Zadejte další bod (nebo stiskněte Enter pro dokončení)"},measureDistance:{firstPoint:"Zadejte první bod",secondPoint:"Zadejte druhý bod"},measurePoint:{point:"Zadejte bod"},measurement:{import:{chooseFile:"Vyberte sidecar JSON soubor měření"}},markup:{author:"Zadejte autora kontroly (uloží se pro pozdější použití)",text:{point:"Zadejte bod textové poznámky",content:"Zadejte text poznámky"},line:{firstPoint:"Zadejte první bod úsečkové poznámky",secondPoint:"Zadejte druhý bod úsečkové poznámky"},arrow:{firstPoint:"Zadejte počáteční bod šipky",secondPoint:"Zadejte hrot šipky"},cloud:{firstCorner:"Zadejte první roh obláčku",secondCorner:"Zadejte protilehlý roh obláčku"},rect:{firstCorner:"Zadejte první roh obdélníku",secondCorner:"Zadejte protilehlý roh obdélníku"},circle:{center:"Zadejte střed kružnice",radius:"Zadejte poloměr kružnice"},shape:{calloutOn:"[Odkaz zapnut]",calloutOff:"[Odkaz vypnut]",calloutAnchor:"Zadejte umístění textu odkazu",keywords:{callout:{display:"Odkaz(C)",local:"Odkaz",global:"Callout"},noCallout:{display:"BezOdkazu(N)",local:"BezOdkazu",global:"NoCallout"}}},highlight:{firstCorner:"Zadejte první roh zvýraznění",secondCorner:"Zadejte protilehlý roh zvýraznění"},callout:{tip:"Zadejte hrot odkazu (konec šipky)",anchor:"Zadejte umístění textu odkazu",content:"Zadejte text odkazu"},stamp:{kind:"Zadejte identifikátor razítka [approved/rejected/revised/for-review/custom]",imageUrl:"Zadejte URL vlastního obrázku razítka (volitelné)",caption:"Zadejte popisek razítka (volitelné)",point:"Zadejte bod vložení razítka"},import:{chooseFile:"Vyberte sidecar JSON soubor poznámek"}},move:{basePointOrDisplacement:"Zadejte základní bod nebo",secondPointOrDisplacement:"Zadejte druhý bod nebo",displacement:"Zadejte přemístění",keywords:{displacement:{display:"Přemístění(D)",local:"Přemístění",global:"Displacement"}}},offset:{distance:"Zadejte vzdálenost offsetu",selectObject:"Vyberte objekt k offsetu nebo stiskněte Enter pro dokončení",sidePoint:"Zadejte bod na straně pro offset",invalidDistance:"Vzdálenost offsetu musí být větší než 0.",invalidSelection:"Vybraný objekt nelze offsetovat.",offsetFailed:"Nelze vytvořit offsetovou křivku na zadané straně."},mtext:{point:"Zadejte bod vložení víceřádkového textu"},pngout:{boundsFirstCorner:"Zadejte první roh rozsahu",boundsSecondCorner:"Zadejte protilehlý roh",longSidePrompt:"Zadejte velikost delší strany v pixelech"},imageattach:{insertionPoint:"Zadejte bod vložení:",scale:"Zadejte faktor měřítka:",rotation:"Zadejte úhel otočení:",invalidScale:"Faktor měřítka musí být větší než 0.",decodeFailed:"Nepodařilo se načíst vybraný soubor obrázku."},insert:{blockName:"Zadejte název bloku:",insertionPoint:"Zadejte bod vložení:",scale:"Zadejte faktor měřítka:",rotation:"Zadejte úhel otočení:",invalidScale:"Faktor měřítka musí být větší než 0.",invalidBlockName:"Neplatný název bloku.",blockNotFound:"Blok nenalezen",xrefNotAllowed:"Nelze vložit externí referenci pomocí -INSERT."},xattach:{insertionPoint:"Zadejte bod vložení:",scale:"Zadejte faktor měřítka:",rotation:"Zadejte úhel otočení:",invalidScale:"Faktor měřítka musí být větší než 0.",unsupportedFile:"Vyberte soubor DWG nebo DXF.",loading:"Načítám externí referenci...",loadFailed:"Nepodařilo se načíst vybraný soubor výkresu."},point:{point:"Zadejte bod"},polygon:{numberOfSides:"Zadejte počet stran",centerOrEdge:"Zadejte střed mnohoúhelníku nebo",radiusOrType:"Zadejte volby",edgeStart:"Zadejte první koncový bod hrany",edgeEnd:"Zadejte druhý koncový bod hrany",keywords:{edge:{display:"Hrana(E)",local:"Hrana",global:"Edge"},inscribed:{display:"Vepsaný do kružnice(I)",local:"Vepsaný do kružnice",global:"Inscribed"},circumscribed:{display:"Opsaný kolem kružnice(C)",local:"Opsaný kolem kružnice",global:"Circumscribed"}},invalid:{sides:"Neplatný počet stran. Zadejte celé číslo mezi 3 a 1024.",radius:"Neplatný poloměr. Poloměr musí být větší než 0.",edge:"Neplatná hrana. Délka hrany musí být větší než 0."}},polyline:{firstPoint:"Zadejte první bod",nextPoint:"Zadejte další bod (nebo stiskněte Enter pro dokončení)",nextPointWithOptions:"Zadejte další bod nebo",nextPointWithArcOptions:"Zadejte další bod nebo",keywords:{arc:{display:"Oblouk(A)",local:"Oblouk",global:"Arc"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},close:{display:"Uzavřít(C)",local:"Uzavřít",global:"Close"},line:{display:"Úsečka(L)",local:"Úsečka",global:"Line"},angle:{display:"Úhel(A)",local:"Úhel",global:"Angle"},center:{display:"Střed(C)",local:"Střed",global:"Center"},secondPoint:{display:"Druhý bod(P)",local:"Druhý bod",global:"SecondPoint"},radius:{display:"Poloměr(R)",local:"Poloměr",global:"Radius"}},arcAngle:"Zadejte úhel oblouku",arcCenter:"Zadejte středový bod",arcSecondPoint:"Zadejte druhý bod na oblouku",arcEndPoint:"Zadejte koncový bod oblouku",arcRadius:"Zadejte poloměr oblouku"},rect:{firstPoint:"Zadejte první roh",nextPoint:"Zadejte druhý roh",firstPointWithOptions:"Zadejte první roh nebo",otherCornerWithOptions:"Zadejte druhý roh nebo",chamferFirst:"Zadejte první vzdálenost zkosení",chamferSecond:"Zadejte druhou vzdálenost zkosení",filletRadius:"Zadejte poloměr zaoblení",segmentWidth:"Zadejte šířku čáry obdélníku",elevationValue:"Zadejte výšku",thicknessValue:"Zadejte tloušťku",rotationAngle:"Zadejte úhel otočení obdélníku",dimensionLength:"Zadejte délku obdélníku",dimensionWidth:"Zadejte šířku obdélníku",areaValue:"Zadejte plochu obdélníku",areaLengthOrWidth:"Zadejte délku obdélníku",areaSpecifyWidth:"Zadejte šířku obdélníku",invalidPositive:"Neplatný vstup. Zadejte hodnotu větší než 0.",invalidRect:"Nelze vytvořit obdélník. Zadejte platné rohy nebo rozměry.",thicknessNotSupported:"Tloušťka obdélníku se aktuálně nezapisuje do dat entity. Nastavení tloušťky se ignoruje.",keywords:{chamfer:{display:"Zkosení(C)",local:"Zkosení",global:"Chamfer"},elevation:{display:"Výška(E)",local:"Výška",global:"Elevation"},fillet:{display:"Zaoblení(F)",local:"Zaoblení",global:"Fillet"},thickness:{display:"Tloušťka(T)",local:"Tloušťka",global:"Thickness"},width:{display:"Šířka(W)",local:"Šířka",global:"Width"},area:{display:"Plocha(A)",local:"Plocha",global:"Area"},dimensions:{display:"Rozměry(D)",local:"Rozměry",global:"Dimensions"},rotation:{display:"Otočení(R)",local:"Otočení",global:"Rotation"},length:{display:"Délka(L)",local:"Délka",global:"Length"},rectWidth:{display:"Šířka(W)",local:"Šířka",global:"Width"}}},rotate:{basePoint:"Zadejte základní bod",rotationAngleOrOptions:"Zadejte úhel otočení nebo",referenceAngleOrPoints:"Zadejte referenční úhel nebo",firstReferencePoint:"Zadejte první bod referenčního úhlu",secondReferencePoint:"Zadejte druhý bod",newAngle:"Zadejte nový úhel",keywords:{copy:{display:"Kopírovat(C)",local:"Kopírovat",global:"Copy"},reference:{display:"Reference(R)",local:"Reference",global:"Reference"},points:{display:"Body(P)",local:"Body",global:"Points"}},invalid:{referencePoints:"Neplatné referenční body: body musí být různé."}},revcloud:{firstCornerOrOptions:"Zadejte první rohový bod nebo",firstCorner:"Zadejte první rohový bod",oppositeCorner:"Zadejte protilehlý roh",startPoint:"Zadejte počáteční bod",nextPoint:"Zadejte další bod",nextPointOrUndo:"Zadejte další bod nebo",firstPoint:"Zadejte první bod",guideCursor:"Veďte kurzor podél obláčku (Enter dokončí)",arcLength:"Zadejte délku oblouku",selectObject:"Vyberte objekt",style:"Zadejte styl oblouků revizního obláčku",reverseDirection:"Obrátit směr",invalidArcLength:"Délka oblouku musí být větší než 0.",invalidObject:"Vybraný objekt nelze převést na revizní obláček.",keywords:{arcLength:{display:"Délka oblouku(A)",local:"Délka oblouku",global:"ArcLength"},object:{display:"Objekt(O)",local:"Objekt",global:"Object"},rectangular:{display:"Obdélníkový(R)",local:"Obdélníkový",global:"Rectangular"},polygonal:{display:"Mnohoúhelníkový(P)",local:"Mnohoúhelníkový",global:"Polygonal"},freehand:{display:"Od ruky(F)",local:"Od ruky",global:"Freehand"},style:{display:"Styl(S)",local:"Styl",global:"Style"},normal:{display:"Normální(N)",local:"Normální",global:"Normal"},calligraphy:{display:"Kaligrafie(C)",local:"Kaligrafie",global:"Calligraphy"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},yes:{display:"Ano(Y)",local:"Ano",global:"Yes"},no:{display:"Ne(N)",local:"Ne",global:"No"}}},sketch:{specifySketch:"Zadejte skicu nebo",sketching:"Pohybem ukazatele kreslete (kliknutím nebo Enter zastavíte)",type:"Zadejte typ skici",increment:"Zadejte přírůstek skici",tolerance:"Zadejte toleranci splajnu",firstPoint:"Zadejte první bod",nextPoint:"Zadejte koncový bod",keywords:{type:{display:"Typ(T)",local:"Typ",global:"Type"},increment:{display:"Přírůstek(I)",local:"Přírůstek",global:"Increment"},tolerance:{display:"toLerance(L)",local:"toLerance",global:"Tolerance"},line:{display:"Úsečky(L)",local:"Úsečky",global:"Lines"},polyline:{display:"Křivka(P)",local:"Křivka",global:"Polyline"},spline:{display:"Splajn(S)",local:"Splajn",global:"Spline"}}},spline:{firstPoint:"Zadejte první bod",nextPoint:"Zadejte další bod (nebo stiskněte Enter pro dokončení)",firstPointWithOptions:"Zadejte první bod nebo",nextPointWithFitOptions:"Zadejte další bod nebo",nextPointWithCvOptions:"Zadejte další řídicí bod nebo",methodPrompt:"Zadejte metodu vytvoření splajnu",knotsPrompt:"Zadejte parametrizaci uzlů",degreePrompt:"Zadejte stupeň splajnu",keywords:{method:{display:"Metoda(M)",local:"Metoda",global:"Method"},fit:{display:"Přizpůsobit(F)",local:"Přizpůsobit",global:"Fit"},cv:{display:"ŘB(C)",local:"ŘB",global:"CV"},knots:{display:"Uzly(K)",local:"Uzly",global:"Knots"},degree:{display:"Stupeň(D)",local:"Stupeň",global:"Degree"},undo:{display:"Zpět(U)",local:"Zpět",global:"Undo"},close:{display:"Uzavřít(C)",local:"Uzavřít",global:"Close"},chord:{display:"Tětiva(C)",local:"Tětiva",global:"Chord"},sqrtChord:{display:"Odmocnina tětivy(S)",local:"Odmocnina tětivy",global:"SqrtChord"},uniform:{display:"Rovnoměrné(U)",local:"Rovnoměrné",global:"Uniform"}}},sysvar:{prompt:"Zadejte novou hodnotu"},zoom:{mainPrompt:"Zadejte roh okna nebo",firstCorner:"Zadejte první roh",secondCorner:"Zadejte protilehlý roh",centerPoint:"Zadejte středový bod",heightOrScale:"Zadejte výšku nebo faktor měřítka (nX nebo nXP)",scaleFactor:"Zadejte faktor měřítka (nX nebo nXP)",keywords:{all:{display:"Vše(A)",local:"Vše",global:"All"},center:{display:"Střed(C)",local:"Střed",global:"Center"},extents:{display:"Rozsah(E)",local:"Rozsah",global:"Extents"},previous:{display:"Předchozí(P)",local:"Předchozí",global:"Previous"},scale:{display:"Měřítko(S)",local:"Měřítko",global:"Scale"},window:{display:"Okno(W)",local:"Okno",global:"Window"}}},chtml:{exportInvisibleLayers:"Exportovat neviditelné hladiny",exportLayouts:"Exportovat rozvržení",initialView:"Počáteční pohled při otevření HTML",viewerMode:"Režim offline prohlížeče",keywords:{yes:{display:"Ano(Y)",local:"Ano",global:"Yes"},no:{display:"Ne(N)",local:"Ne",global:"No"},extents:{display:"Rozsah(E)",local:"Rozsah",global:"Extents"},current:{display:"Aktuální(C)",local:"Aktuální",global:"Current"},view:{display:"Pohled(V)",local:"Pohled",global:"View"},measure:{display:"Měření a kontrola(M)",local:"Měření a kontrola",global:"Measure"}}}},Ym={document:{untitled:"Bez názvu"},commandLine:{noLast:"(žádný předchozí příkaz)",unknownCommand:"Neznámý příkaz",executed:"Provedený příkaz",showHistory:"Zobrazit historii příkazů",placeholder:"Zadejte příkaz",showMessages:"Zobrazit historii zpráv",canceled:"*Zrušeno*",noHistory:"(žádná historie)",invalidInput:"Neplatný vstup.",close:"Zavřít příkazový řádek"},inputManager:{firstCorner:"Zadejte první roh nebo",secondCorner:"Zadejte druhý roh nebo"},message:{fetchingDrawingFile:"Načítám soubor…",exportingDxf:"Exportuji DXF…",exportingEntityPreview:"Exportuji obrázek…",collectingMemoryProfile:"Analyzuji paměť…",fontCached:"Font úspěšně uložen do mezipaměti",fontCacheFailed:"Uložení fontu do mezipaměti selhalo"},progress:{start:"Zahajuji načítání souboru…",parse:"Načítám soubor…",font:"Stahuji fonty potřebné pro tento výkres…",ltype:"Načítám typy čar…",style:"Načítám textové styly…",dimstyle:"Načítám kótovací styly…",layer:"Načítám hladiny…",vport:"Načítám výřezy…",blockrecord:"Načítám záznamy bloků…",header:"Načítám hlavičku…",block:"Načítám bloky…",entity:"Načítám objekty…",object:"Načítám pojmenované slovníky…",rendering:"Vykreslování výkresu ...",end:"Hotovo!"},about:{title:"O aplikaci",close:"Zavřít",product:"CAD Viewer",tagline:"Vysokovýkonný webový CAD prohlížeč pro výkresy DWG a DXF.",website:"Web",docs:"Dokumentace",repository:"GitHub",copyright:"© {year} mlightcad. Všechna práva vyhrazena.",ok:"OK"},drawStyle:{color:"Barva",lineWeight:"Tloušťka čáry",fontSize:"Výška textu"}},Zm={ACAD:{"-hatch":{description:"Creates hatch fills through command-line options without the ribbon UI"},"-layer":{description:"Manages layers through command-line options"},about:{description:"Displays information about mlightcad"},acadver:{description:"Stores the drawing database version identifier (read-only)"},angbase:{description:"Sets the base angle 0 direction with respect to the current UCS"},angdir:{description:"Sets whether positive angles are measured clockwise or counterclockwise"},arc:{description:"Creates an arc"},aunits:{description:"Sets the display format for angles"},auprec:{description:"Sets the display precision for angles, used together with AUNITS"},cdxf:{description:"Exports current drawing to DXF"},cpdf:{description:"Exports current drawing to PDF"},cecolor:{description:"Sets the current default color for newly created objects"},celtscale:{description:"Controls the linetype scale factor for newly created objects"},celtype:{description:"Sets the linetype for newly created objects"},celweight:{description:"Sets the default lineweight for newly created objects"},cetransparency:{description:"Sets the transparency for newly created objects"},cachefont:{description:"Caches a local font file into IndexedDB for text rendering"},circle:{description:"Creates one circle by center and radius"},clayer:{description:"Sets the current layer for new objects and editing operations"},cmleaderstyle:{description:"Sets the name of the current multileader style"},cmlscale:{description:"Controls the overall width of a multiline"},cmlstyle:{description:"Sets the name of the current multiline style"},colortheme:{description:"Controls the color theme of the user interface (dark or light)"},copy:{description:"Copies selected entities by cloning them to new positions",prompt:"Select entities"},csvg:{description:"Converts current drawing to SVG"},chtml:{description:"Exports current drawing to a standalone offline HTML file"},"-chtml":{description:"Exports current drawing to HTML using command-line options"},dimlinear:{description:"Creates linear dimensions"},dimstyle:{description:"Sets the name of the current dimension style"},dwgname:{description:"Stores the name of the current drawing file (read-only)"},loginname:{description:"Displays the user's login name (read-only)"},dynmode:{description:"Controls Dynamic Input settings at the cursor"},dynprompt:{description:"Controls display of prompts in Dynamic Input tooltips"},ellipse:{description:"Creates an ellipse or elliptical arc by axis endpoints or center"},erase:{description:"Deletes selected entities from the drawing",prompt:"Select entities"},extmax:{description:"Stores the upper-right corner of the model-space drawing extents (read-only)"},extmin:{description:"Stores the lower-left corner of the model-space drawing extents (read-only)"},entout:{description:"Exports a merged preview image for selected entities",prompt:"Select entities"},hideobjects:{description:"Temporarily suppresses the display of selected objects",prompt:"Select objects"},imageattach:{description:"Attaches a raster image as an external reference to the current drawing"},"-insert":{description:"Inserts a block definition into the current drawing (command-line)"},xattach:{description:"Attaches a DWG or DXF drawing as an external reference to the current drawing"},gripcolor:{description:"Sets the color of unselected grips displayed on selected objects"},griphot:{description:"Sets the color of selected (hot) grips"},gripobjlimit:{description:"Suppresses grip display when the selection set exceeds the specified number of objects (0 = no limit)"},grips:{description:"Controls whether grips are displayed on selected objects"},gripsize:{description:"Sets the size of grip boxes in pixels"},hatch:{description:"Fills an enclosed area or selected objects with a hatch pattern"},ipdf:{description:"Imports vector geometry from a PDF file"},hpang:{description:"Sets the default angle, in radians, for newly created hatch patterns"},hpassoc:{description:"Controls whether newly created hatches are associative"},hpbackgroundcolor:{description:"Sets the default background color for newly created hatch patterns"},hpcolor:{description:"Sets the default color for newly created hatches"},hpdouble:{description:"Controls whether user-defined hatch patterns are doubled"},hpislanddetection:{description:"Controls how islands within newly created hatch boundaries are treated"},hplayer:{description:"Sets the default layer for newly created hatches and fills"},hpname:{description:"Sets the default pattern name for newly created hatches in this session"},hpscale:{description:"Sets the default scale factor for newly created hatch patterns"},hpseparate:{description:"Controls whether one or separate hatch objects are created for multiple boundaries"},hptransparency:{description:"Sets the default transparency for newly created hatches and fills"},insunits:{description:"Specifies drawing units for automatic scaling of inserted blocks, images, or xrefs"},laycur:{description:"Changes the layer property of selected objects to the current layer",prompt:"Select objects to be changed to the current layer"},laydel:{description:"Deletes a layer and all objects on that layer"},layerclose:{description:"Closes the Layer Properties Manager"},layerp:{description:"Undoes the last change or set of changes made to layer settings"},layfrz:{description:"Freezes the layer of selected objects",prompt:"Select object on layer to freeze"},layiso:{description:"Isolates the layers of selected objects",prompt:"Select objects on layers to isolate"},laylck:{description:"Locks the layer of selected objects",prompt:"Select object on layer to lock"},layoff:{description:"Turns off the layer of selected objects",prompt:"Select object on layer to turn off"},layon:{description:"Turns on all layers in the drawing"},laythw:{description:"Thaws all frozen layers in the drawing"},layulk:{description:"Unlocks the layer of selected objects",prompt:"Select object on layer to unlock"},layuniso:{description:"Restores layers hidden or locked by LAYISO"},line:{description:"Draws straight line segments between points"},log:{description:"Logs debug information in console"},ltscale:{description:"Sets the global linetype scale factor for the drawing"},lunits:{description:"Sets the display format for coordinates and distances"},luprec:{description:"Sets the display precision for linear units, used together with LUNITS"},lwdisplay:{description:"Controls whether lineweights are displayed in the drawing"},clearmeasurements:{description:"Removes all measurements from the current layout"},measurementvis:{description:"Shows or hides measurements on the current layout"},measurementexport:{description:"Exports measurements to a sidecar JSON file"},measurementimport:{description:"Imports measurements from a sidecar JSON file"},measurearea:{description:"Calculates the area and perimeter of selected objects or points"},measureangle:{description:"Measures the angle between two lines or three points"},measurearc:{description:"Measures the length of an arc segment"},measuredistance:{description:"Measures the distance and delta values between two points"},measurepoint:{description:"Measures the X/Y coordinates of a picked point"},measurement:{description:"Sets whether the drawing uses English (imperial) or metric units"},measurementcolor:{description:"Sets the color used for measurement overlays"},modelbkcolor:{description:"Sets the background color of the model-space drawing area"},mline:{description:"Creates multiple parallel lines as one multiline object"},move:{description:"Moves selected entities by a displacement vector",prompt:"Select entities"},offset:{description:"Creates parallel curves, polylines, or circles at a specified distance"},mtext:{description:"Creates one mtext entity"},open:{description:"Opens an existing drawing file"},openprof:{description:"Controls whether open-file stage timing profiles are logged to the console"},openperf:{description:"Opens the Open Performance palette with timings from the last drawing open"},orthomode:{description:"Constrains cursor movement to the horizontal or vertical axis"},osmode:{description:"Sets running Object Snap modes using a bitcode value"},pan:{description:"Shifts the view without changing the viewing direction or magnification"},paperbkcolor:{description:"Sets the background color of the paper-space (layout) drawing area"},pdmode:{description:"Controls how POINT entities are displayed"},pdsize:{description:"Sets the display size for POINT entities"},pickbox:{description:"Sets the size (in pixels) of the selection box used to pick objects"},pline:{description:"Creates a polyline by specifying multiple points"},pngout:{description:"Exports to PNG"},point:{description:"Creates points"},polaraddang:{description:"Stores additional polar tracking angles as a semicolon-separated list"},polarang:{description:"Sets the polar angle increment for polar tracking"},polarmode:{description:"Controls polar and object snap tracking settings"},polygon:{description:"Creates a regular polygon by center/radius or by one polygon edge"},qnew:{description:"Starts a new drawing"},ray:{description:"Creates a ray that starts at a point and extends to infinity"},rectang:{description:"Creates a rectangle by specifying two opposite corners"},regen:{description:"Redraws the current drawing"},revcloud:{description:"Creates or modifies a revision cloud"},markuptext:{description:"Places a text markup label"},markupline:{description:"Creates a line markup"},markuparrow:{description:"Creates an arrow markup"},markupcloud:{description:"Creates a revision cloud markup"},markuprect:{description:"Creates a rectangle markup"},markupcircle:{description:"Creates a circle markup"},markuphighlight:{description:"Creates a highlight rectangle markup"},markupcallout:{description:"Creates a callout: pick leader tip, place text box, then enter text"},markupstamp:{description:"Places a stamp or custom symbol"},markupvis:{description:"Shows or hides markups"},clearmarkups:{description:"Clears all markups on the current layout"},markupexport:{description:"Exports markups to a sidecar JSON file"},markupimport:{description:"Imports markups from a sidecar JSON file"},markuppanel:{description:"Opens the markup palette"},rotate:{description:"Rotates selected entities around a base point",prompt:"Select entities"},select:{description:"Selects entities"},shortcutmenu:{description:"Controls the availability of shortcut menus in the drawing area"},sketch:{description:"Creates a series of freehand line segments"},spline:{description:"Creates a smooth spline curve by specifying control points"},textstyle:{description:"Sets the name of the current text style"},unitmode:{description:"Controls fractional display of coordinates when LUNITS is Architectural or Fractional"},switchbg:{description:"Toggles the drawing area background between white and black"},unisolateobjects:{description:"Redisplay all objects hidden by HIDEOBJECTS"},undo:{description:"Undoes the last database editing operation",nothingToUndo:"Nothing to undo."},redo:{description:"Redoes the last undone database editing operation",nothingToRedo:"Nothing to redo."},xline:{description:"Creates a construction line that extends infinitely in both directions"},zoom:{description:"Zooms to display the maximum extents of all entities"}},USER:{}},Xm={arc:{startPointOrCenter:"Specify start point of arc or",secondPointOrOptions:"Specify second point of arc or",secondPoint:"Specify second point of arc",startPoint:"Specify start point of arc",centerPoint:"Specify center point of arc",endPoint:"Specify end point of arc",endPointOrOptions:"Specify end point of arc or",centerPointOrOptions:"Specify center point of arc",includedAngle:"Specify included angle",chordLength:"Specify chord length",tangentDirection:"Specify tangent direction for start point of arc",radius:"Specify radius of arc",keywords:{center:{display:"Center(C)",local:"Center",global:"Center"},end:{display:"End(E)",local:"End",global:"End"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},chordLength:{display:"chord Length(L)",local:"Chord Length",global:"ChordLength"},direction:{display:"Direction(D)",local:"Direction",global:"Direction"},radius:{display:"Radius(R)",local:"Radius",global:"Radius"}},invalid:{threePoint:"Invalid 3-point arc: points are collinear or cannot define an arc.",center:"Invalid center input: start and end points must lie on the same circle.",angle:"Invalid angle input: included angle must be greater than 0 and less than 360 degrees.",chordLength:"Invalid chord length: value is out of range for the current radius.",direction:"Invalid direction: cannot construct an arc from this tangent direction.",radius:"Invalid radius: the specified radius cannot connect start and end points."}},circle:{center:"Specify the center of circle",centerOrOptions:"Specify center point of circle or",radius:"Specify the radius of circle",radiusOrDiameter:"Specify radius of circle or",diameter:"Specify diameter of circle",twoPointFirst:"Specify first endpoint of circle diameter",twoPointSecond:"Specify second endpoint of circle diameter",threePointFirst:"Specify first point on circle",threePointSecond:"Specify second point on circle",threePointThird:"Specify third point on circle",keywords:{threeP:{display:"3P(3P)",local:"3P",global:"3P"},twoP:{display:"2P(2P)",local:"2P",global:"2P"},diameter:{display:"Diameter(D)",local:"Diameter",global:"Diameter"}}},copy:{basePointOrOptions:"Specify base point or",displacementOrArray:"Specify displacement or",secondPointOrArray:"Specify second point or",modePrompt:"Enter copy mode option",arrayItemCount:"Enter the number of items in the array including the original",arraySecondPointOrFit:"Specify second point or",arrayFitSecondPoint:"Specify second point",keywords:{displacement:{display:"Displacement(D)",local:"Displacement",global:"Displacement"},mode:{display:"Mode(O)",local:"Mode",global:"Mode"},multiple:{display:"Multiple(M)",local:"Multiple",global:"Multiple"},single:{display:"Single(S)",local:"Single",global:"Single"},array:{display:"Array(A)",local:"Array",global:"Array"},fit:{display:"Fit(F)",local:"Fit",global:"Fit"}}},dimlinear:{xLine1Point:"Specify the first extension line origin",xLine2Point:"Specify the second extension line origin",dimLinePoint:"Specify dimension line location"},ellipse:{axisEndpointOrOptions:"Specify axis endpoint of ellipse or",arcAxisEndpointOrCenter:"Specify axis endpoint of elliptical arc or",center:"Specify center of ellipse",firstAxisEndpoint:"Specify endpoint of axis",secondAxisEndpoint:"Specify other endpoint of axis",otherAxisOrRotation:"Specify distance to other axis or",rotationAngle:"Specify rotation angle around major axis",arcStartAngle:"Specify start angle of elliptical arc",arcEndAngle:"Specify end angle of elliptical arc",keywords:{arc:{display:"Arc(A)",local:"Arc",global:"Arc"},center:{display:"Center(C)",local:"Center",global:"Center"},rotation:{display:"Rotation(R)",local:"Rotation",global:"Rotation"}},invalid:{axis:"Invalid axis input: axis length must be greater than 0.",otherAxis:"Invalid other-axis input: distance must be greater than 0.",rotation:"Invalid rotation input: resulting minor axis must be greater than 0."}},hatch:{prompt:"Select boundary object or",pickPoint:"Specify internal point (or press Enter to finish)",select:"Select objects to hatch",patternName:"Enter hatch pattern name",scale:"Specify hatch pattern scale",angle:"Specify hatch pattern angle",style:"Enter hatch style",associative:"Specify associativity",invalidBoundary:"Selected objects do not form a closed boundary.",keywords:{pick:{display:"Pick points(P)",local:"Pick points",global:"PickPoints"},select:{display:"Select objects(S)",local:"Select objects",global:"SelectObjects"},cancel:{display:"Cancel(C)",local:"Cancel",global:"Cancel"},pattern:{display:"Pattern(P)",local:"Pattern",global:"Pattern"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},style:{display:"Style(T)",local:"Style",global:"HatchStyle"},associative:{display:"Associative(AS)",local:"Associative",global:"AssociativeMode"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},outer:{display:"Outer(O)",local:"Outer",global:"Outer"},ignore:{display:"Ignore(I)",local:"Ignore",global:"Ignore"},yes:{display:"Yes(Y)",local:"Yes",global:"Yes"},no:{display:"No(N)",local:"No",global:"No"}}},hideobjects:{hidden:"object(s) hidden",restored:"object(s) restored",nothingToRestore:"No hidden objects to restore"},entout:{longSidePrompt:"Enter preview long side size in pixels",exported:"object preview(s) exported",skipped:"object(s) skipped",failed:{"no-preview-root":"Unable to build preview geometry for the selection","no-bounds":"Unable to compute preview bounds for the selection","capture-failed":"Unable to render the entity preview image","download-failed":"Preview rendered but the PNG download failed"}},layer:{main:"Enter option",listSummary:"Layer list was printed to browser console",emptyInput:"No layer name was entered.",newPrompt:"Enter name for new layer(s)",makePrompt:"Enter name of layer to make current",setPrompt:"Enter name of layer to set current",onPrompt:"Enter layer name(s) to turn on",offPrompt:"Enter layer name(s) to turn off",freezePrompt:"Enter layer name(s) to freeze",thawPrompt:"Enter layer name(s) to thaw",lockPrompt:"Enter layer name(s) to lock",unlockPrompt:"Enter layer name(s) to unlock",colorLayerPrompt:"Enter layer name(s) to change color",colorValuePrompt:"Enter color (ACI 1-255, RGB like 255,0,0, or CSS color name)",invalidColor:"Invalid color input.",descriptionLayerPrompt:"Enter layer name to edit description",descriptionValuePrompt:"Enter new layer description",created:"Created layer count",alreadyExists:"Layer already exists",notFound:"Layer not found",cannotChangeCurrent:"Cannot turn off or freeze the current layer.",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"Make(M)",local:"Make",global:"Make"},set:{display:"Set(S)",local:"Set",global:"Set"},new:{display:"New(N)",local:"New",global:"New"},on:{display:"On(ON)",local:"On",global:"On"},off:{display:"Off(OF)",local:"Off",global:"Off"},color:{display:"Color(C)",local:"Color",global:"Color"},freeze:{display:"Freeze(F)",local:"Freeze",global:"Freeze"},thaw:{display:"Thaw(T)",local:"Thaw",global:"Thaw"},lock:{display:"Lock(L)",local:"Lock",global:"Lock"},unlock:{display:"Unlock(U)",local:"Unlock",global:"Unlock"},description:{display:"Description(D)",local:"Description",global:"Description"}}},layon:{alreadyOn:"All layers are already on.",turnedOn:"Turned on layers"},laycur:{prompt:"Select objects to be changed to the current layer",currentLayerNotFound:"Current layer not found.",noObjects:"No valid objects were selected.",alreadyCurrent:"Selected objects are already on the current layer.",changed:"Changed objects to current layer"},layfrz:{prompt:"Select object on layer to freeze or",invalidSelection:"Invalid object selected.",settingsPrompt:"Enter LAYFRZ setting to change",viewportPrompt:"Specify viewport freeze behavior",blockSelectionPrompt:"Specify nested block selection behavior",vpfreezeFallback:"Current viewer does not support per-viewport layer freeze; using Freeze behavior instead.",nestedSelectionLimited:"Nested block selection settings are stored, but current picking still resolves the top-level entity layer.",layerNotFound:"Layer not found",cannotFreezeCurrent:"Cannot freeze the current layer.",alreadyFrozen:"Layer is already frozen",frozen:"Frozen layer",restored:"Restored layer",nothingToUndo:"There is no LAYFRZ action to undo.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},viewports:{display:"Viewports(V)",local:"Viewports",global:"Viewports"},blockSelection:{display:"Block selection(B)",local:"Block selection",global:"BlockSelection"},freeze:{display:"Freeze(F)",local:"Freeze",global:"Freeze"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"},block:{display:"Block(B)",local:"Block",global:"Block"},entity:{display:"Entity(E)",local:"Entity",global:"Entity"},none:{display:"None(N)",local:"None",global:"None"}}},layiso:{prompt:"Select objects on the layer(s) to be isolated or",settingsPrompt:"Enter setting for layers not isolated",offModePrompt:"Enter off behavior for layers not isolated",noLayers:"No valid layers were selected.",layerNotFound:"Layer not found",isolated:"Isolated layer(s)",affectedLayers:"affected layers",vpfreezeFallback:"Current viewer does not support per-viewport layer freeze; using Off behavior instead.",lockFadeFallback:"Current viewer does not support layer fade display; non-isolated layers will be locked without fade.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},off:{display:"Off(O)",local:"Off",global:"Off"},lockAndFade:{display:"Lock and fade(L)",local:"Lock and fade",global:"LockAndFade"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"}}},layuniso:{noPrevious:"No previous LAYISO layer state to restore.",layerNotFound:"Layer not found",nothingRestored:"No LAYISO layer changes were restored.",restored:"Restored layers"},laythw:{alreadyThawed:"All layers are already thawed.",thawed:"Thawed layers"},laylck:{prompt:"Select an object on the layer to be locked",invalidSelection:"Invalid object selected.",layerNotFound:"Layer not found",alreadyLocked:"Layer is already locked",locked:"Locked layer"},layulk:{prompt:"Select an object on the layer to be unlocked",invalidSelection:"Invalid object selected.",layerNotFound:"Layer not found",alreadyUnlocked:"Layer is already unlocked",unlocked:"Unlocked layer"},layoff:{prompt:"Select object on layer to turn off or",invalidSelection:"Invalid object selected.",settingsPrompt:"Enter LAYOFF setting to change",viewportPrompt:"Specify viewport behavior",blockSelectionPrompt:"Specify nested block selection behavior",vpfreezeFallback:"Current viewer does not support per-viewport layer off; using Off behavior instead.",nestedSelectionLimited:"Nested block selection settings are stored, but current picking still resolves the top-level entity layer.",layerNotFound:"Layer not found",cannotTurnOffCurrent:"Cannot turn off the current layer.",alreadyOff:"Layer is already off",turnedOff:"Turned off layer",restored:"Restored layer",nothingToUndo:"There is no LAYOFF action to undo.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},viewports:{display:"Viewports(V)",local:"Viewports",global:"Viewports"},blockSelection:{display:"Block selection(B)",local:"Block selection",global:"BlockSelection"},off:{display:"Off(O)",local:"Off",global:"Off"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"},block:{display:"Block(B)",local:"Block",global:"Block"},entity:{display:"Entity(E)",local:"Entity",global:"Entity"},none:{display:"None(N)",local:"None",global:"None"}}},layerp:{restored:"Restored previous layer state.",noPreviousState:"There is no previous layer state to restore."},line:{firstPoint:"Specify the first point",firstPointOrContinue:"Specify first point or",nextPoint:"Specify the next point",nextPointWithOptions:"Specify next point or",keywords:{continue:{display:"Continue(C)",local:"Continue",global:"Continue"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"}}},xline:{firstPointOrOptions:"Specify a point or",secondPoint:"Specify second point",throughPoint:"Specify through point",angle:"Enter angle of xline",invalidDirection:"Invalid direction for XLINE.",keywords:{hor:{display:"Hor(H)",local:"Hor",global:"Hor"},ver:{display:"Ver(V)",local:"Ver",global:"Ver"},ang:{display:"Ang(A)",local:"Ang",global:"Ang"}}},ray:{startPoint:"Specify start point",throughPoint:"Specify through point"},mline:{startPointWithOptions:"Specify start point or",nextPointWithOptions:"Specify next point or",justificationPrompt:"Enter justification type",scalePrompt:"Specify mline scale",stylePrompt:"Enter mline style name or [?] for list",styleNotFound:"Mline style not found",styleListHeader:"Loaded mline styles",styleListEmpty:"No mline style is loaded in current drawing.",keywords:{justification:{display:"Justification(J)",local:"Justification",global:"Justification"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},style:{display:"Style(ST)",local:"Style",global:"Style"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},top:{display:"Top(T)",local:"Top",global:"Top"},zero:{display:"Zero(Z)",local:"Zero",global:"Zero"},bottom:{display:"Bottom(B)",local:"Bottom",global:"Bottom"}}},measureAngle:{vertex:"Specify vertex point",arm1:"Specify point on first arm",arm2:"Specify point on second arm"},measureArc:{startPoint:"Specify arc start point",throughPoint:"Specify a point on the arc",endPoint:"Specify arc end point",lockedEndPoint:"Specify arc end point (Ctrl to switch major/minor arc)",invalidPoints:"The three points are collinear and do not define an arc."},measureArea:{firstPoint:"Specify first point",nextPoint:"Specify next point (or press Enter to finish)"},measureDistance:{firstPoint:"Specify first point",secondPoint:"Specify second point"},measurePoint:{point:"Specify point"},measurement:{import:{chooseFile:"Choose a measurement sidecar JSON file"}},markup:{author:"Specify review author (saved for later)",text:{point:"Specify text markup point",content:"Enter markup text"},line:{firstPoint:"Specify first point of line markup",secondPoint:"Specify second point of line markup"},arrow:{firstPoint:"Specify arrow start point",secondPoint:"Specify arrow tip"},cloud:{firstCorner:"Specify first corner of cloud",secondCorner:"Specify opposite corner of cloud"},rect:{firstCorner:"Specify first corner of rectangle",secondCorner:"Specify opposite corner of rectangle"},circle:{center:"Specify center of circle",radius:"Specify radius of circle"},shape:{calloutOn:"[Callout on]",calloutOff:"[Callout off]",calloutAnchor:"Specify callout text location",keywords:{callout:{display:"Callout(C)",local:"Callout",global:"Callout"},noCallout:{display:"NoCallout(N)",local:"NoCallout",global:"NoCallout"}}},highlight:{firstCorner:"Specify first corner of highlight",secondCorner:"Specify opposite corner of highlight"},callout:{tip:"Specify leader tip (arrow end)",anchor:"Specify callout text location",content:"Enter callout text"},stamp:{kind:"Enter stamp id [approved/rejected/revised/for-review/custom]",imageUrl:"Enter custom stamp image URL (optional)",caption:"Enter stamp caption (optional)",point:"Specify stamp insertion point"},import:{chooseFile:"Choose a markup sidecar JSON file"}},move:{basePointOrDisplacement:"Specify base point or",secondPointOrDisplacement:"Specify second point or",displacement:"Specify displacement",keywords:{displacement:{display:"Displacement(D)",local:"Displacement",global:"Displacement"}}},offset:{distance:"Specify offset distance",selectObject:"Select object to offset or press Enter to finish",sidePoint:"Specify point on side to offset",invalidDistance:"Offset distance must be greater than 0.",invalidSelection:"Selected object cannot be offset.",offsetFailed:"Unable to create an offset curve for the specified side."},mtext:{point:"Specify mtext insertion point"},pngout:{boundsFirstCorner:"Specify first corner of bounds",boundsSecondCorner:"Specify opposite corner",longSidePrompt:"Enter long side size in pixels"},imageattach:{insertionPoint:"Specify insertion point:",scale:"Specify scale factor:",rotation:"Specify rotation angle:",invalidScale:"Scale factor must be greater than 0.",decodeFailed:"Failed to read the selected image file."},insert:{blockName:"Enter block name:",insertionPoint:"Specify insertion point:",scale:"Specify scale factor:",rotation:"Specify rotation angle:",invalidScale:"Scale factor must be greater than 0.",invalidBlockName:"Invalid block name.",blockNotFound:"Block not found",xrefNotAllowed:"Cannot insert an external reference with -INSERT."},xattach:{insertionPoint:"Specify insertion point:",scale:"Specify scale factor:",rotation:"Specify rotation angle:",invalidScale:"Scale factor must be greater than 0.",unsupportedFile:"Please select a DWG or DXF file.",loading:"Loading external reference...",loadFailed:"Failed to read the selected drawing file."},point:{point:"Specify a point"},polygon:{numberOfSides:"Enter number of sides",centerOrEdge:"Specify center of polygon or",radiusOrType:"Enter options",edgeStart:"Specify first endpoint of edge",edgeEnd:"Specify second endpoint of edge",keywords:{edge:{display:"Edge(E)",local:"Edge",global:"Edge"},inscribed:{display:"Inscribed in circle(I)",local:"Inscribed in circle",global:"Inscribed"},circumscribed:{display:"Circumscribed about circle(C)",local:"Circumscribed about circle",global:"Circumscribed"}},invalid:{sides:"Invalid number of sides. Enter an integer between 3 and 1024.",radius:"Invalid radius. Radius must be greater than 0.",edge:"Invalid edge. The edge length must be greater than 0."}},polyline:{firstPoint:"Specify the first point",nextPoint:"Specify the next point (or press Enter to finish)",nextPointWithOptions:"Specify next point or",nextPointWithArcOptions:"Specify next point or",keywords:{arc:{display:"Arc(A)",local:"Arc",global:"Arc"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},line:{display:"Line(L)",local:"Line",global:"Line"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},center:{display:"Center(C)",local:"Center",global:"Center"},secondPoint:{display:"Second point(P)",local:"Second point",global:"SecondPoint"},radius:{display:"Radius(R)",local:"Radius",global:"Radius"}},arcAngle:"Specify arc angle",arcCenter:"Specify center point",arcSecondPoint:"Specify second point on arc",arcEndPoint:"Specify arc end point",arcRadius:"Specify arc radius"},rect:{firstPoint:"Specify first corner point",nextPoint:"Specify other corner point",firstPointWithOptions:"Specify first corner point or",otherCornerWithOptions:"Specify other corner point or",chamferFirst:"Specify first chamfer distance",chamferSecond:"Specify second chamfer distance",filletRadius:"Specify fillet radius",segmentWidth:"Specify rectangle line width",elevationValue:"Specify elevation",thicknessValue:"Specify thickness",rotationAngle:"Specify rectangle rotation angle",dimensionLength:"Specify rectangle length",dimensionWidth:"Specify rectangle width",areaValue:"Specify rectangle area",areaLengthOrWidth:"Specify rectangle length",areaSpecifyWidth:"Specify rectangle width",invalidPositive:"Invalid input. Please enter a value greater than 0.",invalidRect:"Unable to create rectangle. Please specify valid corners or dimensions.",thicknessNotSupported:"Rectangle thickness is currently not written to entity data. The thickness setting is ignored.",keywords:{chamfer:{display:"Chamfer(C)",local:"Chamfer",global:"Chamfer"},elevation:{display:"Elevation(E)",local:"Elevation",global:"Elevation"},fillet:{display:"Fillet(F)",local:"Fillet",global:"Fillet"},thickness:{display:"Thickness(T)",local:"Thickness",global:"Thickness"},width:{display:"Width(W)",local:"Width",global:"Width"},area:{display:"Area(A)",local:"Area",global:"Area"},dimensions:{display:"Dimensions(D)",local:"Dimensions",global:"Dimensions"},rotation:{display:"Rotation(R)",local:"Rotation",global:"Rotation"},length:{display:"Length(L)",local:"Length",global:"Length"},rectWidth:{display:"Width(W)",local:"Width",global:"Width"}}},rotate:{basePoint:"Specify base point",rotationAngleOrOptions:"Specify rotation angle or",referenceAngleOrPoints:"Specify reference angle or",firstReferencePoint:"Specify first point of reference angle",secondReferencePoint:"Specify second point",newAngle:"Specify new angle",keywords:{copy:{display:"Copy(C)",local:"Copy",global:"Copy"},reference:{display:"Reference(R)",local:"Reference",global:"Reference"},points:{display:"Points(P)",local:"Points",global:"Points"}},invalid:{referencePoints:"Invalid reference points: points must be different."}},revcloud:{firstCornerOrOptions:"Specify first corner point or",firstCorner:"Specify first corner point",oppositeCorner:"Specify opposite corner",startPoint:"Specify start point",nextPoint:"Specify next point",nextPointOrUndo:"Specify next point or",firstPoint:"Specify first point",guideCursor:"Guide cursor along cloud path (press Enter to finish)",arcLength:"Specify arc length",selectObject:"Select object",style:"Enter revision cloud arc style",reverseDirection:"Reverse direction",invalidArcLength:"Arc length must be greater than 0.",invalidObject:"Selected object cannot be converted to a revision cloud.",keywords:{arcLength:{display:"Arc length(A)",local:"Arc length",global:"ArcLength"},object:{display:"Object(O)",local:"Object",global:"Object"},rectangular:{display:"Rectangular(R)",local:"Rectangular",global:"Rectangular"},polygonal:{display:"Polygonal(P)",local:"Polygonal",global:"Polygonal"},freehand:{display:"Freehand(F)",local:"Freehand",global:"Freehand"},style:{display:"Style(S)",local:"Style",global:"Style"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},calligraphy:{display:"Calligraphy(C)",local:"Calligraphy",global:"Calligraphy"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},yes:{display:"Yes(Y)",local:"Yes",global:"Yes"},no:{display:"No(N)",local:"No",global:"No"}}},sketch:{specifySketch:"Specify sketch or",sketching:"Move the pointer to sketch (click or press Enter to stop)",type:"Enter sketch type",increment:"Specify sketch increment",tolerance:"Specify spline tolerance",firstPoint:"Specify the first point",nextPoint:"Specify the end point",keywords:{type:{display:"Type(T)",local:"Type",global:"Type"},increment:{display:"Increment(I)",local:"Increment",global:"Increment"},tolerance:{display:"toLerance(L)",local:"toLerance",global:"Tolerance"},line:{display:"Lines(L)",local:"Lines",global:"Lines"},polyline:{display:"Polyline(P)",local:"Polyline",global:"Polyline"},spline:{display:"Spline(S)",local:"Spline",global:"Spline"}}},spline:{firstPoint:"Specify the first point",nextPoint:"Specify the next point (or press Enter to finish)",firstPointWithOptions:"Specify first point or",nextPointWithFitOptions:"Specify next point or",nextPointWithCvOptions:"Specify next control vertex or",methodPrompt:"Enter spline creation method",knotsPrompt:"Enter knot parameterization",degreePrompt:"Specify spline degree",keywords:{method:{display:"Method(M)",local:"Method",global:"Method"},fit:{display:"Fit(F)",local:"Fit",global:"Fit"},cv:{display:"CV(C)",local:"CV",global:"CV"},knots:{display:"Knots(K)",local:"Knots",global:"Knots"},degree:{display:"Degree(D)",local:"Degree",global:"Degree"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},chord:{display:"Chord(C)",local:"Chord",global:"Chord"},sqrtChord:{display:"Sqrt chord(S)",local:"Sqrt chord",global:"SqrtChord"},uniform:{display:"Uniform(U)",local:"Uniform",global:"Uniform"}}},sysvar:{prompt:"Please input new value"},zoom:{mainPrompt:"Specify corner of window or",firstCorner:"Specify first corner",secondCorner:"Specify opposite corner",centerPoint:"Specify center point",heightOrScale:"Enter height or scale factor (nX or nXP)",scaleFactor:"Enter scale factor (nX or nXP)",keywords:{all:{display:"All(A)",local:"All",global:"All"},center:{display:"Center(C)",local:"Center",global:"Center"},extents:{display:"Extents(E)",local:"Extents",global:"Extents"},previous:{display:"Previous(P)",local:"Previous",global:"Previous"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},window:{display:"Window(W)",local:"Window",global:"Window"}}},chtml:{exportInvisibleLayers:"Export invisible layers",exportLayouts:"Export layouts",initialView:"Initial view when opening HTML",viewerMode:"Offline viewer mode",keywords:{yes:{display:"Yes(Y)",local:"Yes",global:"Yes"},no:{display:"No(N)",local:"No",global:"No"},extents:{display:"Extents(E)",local:"Extents",global:"Extents"},current:{display:"Current(C)",local:"Current",global:"Current"},view:{display:"View(V)",local:"View",global:"View"},measure:{display:"Measure & Review(M)",local:"Measure & Review",global:"Measure"}}}},qm={document:{untitled:"Untitled"},commandLine:{noLast:"(no last command)",unknownCommand:"Unknown command",executed:"Executed command",showHistory:"Show command history",placeholder:"Type command",showMessages:"Show message history",canceled:"*Canceled*",noHistory:"(no history)",invalidInput:"Invalid input.",close:"Close command line"},inputManager:{firstCorner:"Specify the first corner or",secondCorner:"Specify the second corner or"},message:{fetchingDrawingFile:"Fetching file ...",exportingDxf:"Exporting DXF ...",exportingEntityPreview:"Exporting image ...",collectingMemoryProfile:"Analyzing memory ...",fontCached:"Font cached successfully",fontCacheFailed:"Failed to cache font"},progress:{start:"Start parsing file ...",parse:"Parsing file ...",font:"Downloading fonts needed by this drawing ...",ltype:"Parsing line types ...",style:"Parsing text syltes ...",dimstyle:"Parsing dimension styles ...",layer:"Parsing layers ...",vport:"Parsing viewports ...",blockrecord:"Parsing block record ...",header:"Parsing header ...",block:"Parsing blocks ...",entity:"Parsing entities ...",object:"Parsing named dictionaries ...",rendering:"Rendering drawing ...",end:"Finished!"},about:{title:"About",close:"Close",product:"CAD Viewer",tagline:"High-performance web CAD viewer for DWG and DXF drawings.",website:"Website",docs:"Documentation",repository:"GitHub",copyright:"© {year} mlightcad. All rights reserved.",ok:"OK"},drawStyle:{color:"Color",lineWeight:"Lineweight",fontSize:"Text height"}},Jm={ACAD:{"-hatch":{description:"Şerit menüsü olmadan komut satırı seçenekleriyle tarama dolgular oluşturur"},"-layer":{description:"Komut satırı seçenekleriyle katmanları yönetir"},about:{description:"mlightcad hakkında bilgi gösterir"},acadver:{description:"Çizim veritabanı sürüm tanımlayıcısını saklar (salt okunur)"},angbase:{description:"Geçerli KKS'ye göre 0 açı temel yönünü ayarlar"},angdir:{description:"Pozitif açıların saat yönünde mi yoksa saat yönünün tersine mi ölçüleceğini ayarlar"},arc:{description:"Bir yay oluşturur"},aunits:{description:"Açılar için görüntüleme biçimini ayarlar"},auprec:{description:"AUNITS ile birlikte kullanılan, açılar için görüntüleme hassasiyetini ayarlar"},cdxf:{description:"Geçerli çizimi DXF olarak dışa aktarır"},cpdf:{description:"Geçerli çizimi PDF olarak dışa aktarır"},cecolor:{description:"Yeni oluşturulan nesneler için geçerli varsayılan rengi ayarlar"},celtscale:{description:"Yeni oluşturulan nesneler için çizgi tipi ölçek faktörünü denetler"},celtype:{description:"Yeni oluşturulan nesneler için çizgi tipini ayarlar"},celweight:{description:"Yeni oluşturulan nesneler için varsayılan çizgi kalınlığını ayarlar"},cetransparency:{description:"Yeni oluşturulan nesneler için saydamlığı ayarlar"},cachefont:{description:"Metin işleme için yerel bir yazı tipi dosyasını IndexedDB'ye önbelleğe alır"},circle:{description:"Merkez ve yarıçapa göre bir daire oluşturur"},clayer:{description:"Yeni nesneler ve düzenleme işlemleri için geçerli katmanı ayarlar"},cmleaderstyle:{description:"Geçerli çoklu lider stilinin adını ayarlar"},cmlscale:{description:"Bir çoklu çizginin genel genişliğini denetler"},cmlstyle:{description:"Geçerli çoklu çizgi stilinin adını ayarlar"},colortheme:{description:"Kullanıcı arayüzünün renk temasını denetler (koyu veya açık)"},copy:{description:"Seçili varlıkları klonlayarak yeni konumlara kopyalar",prompt:"Varlıkları seçin"},csvg:{description:"Geçerli çizimi SVG'ye dönüştürür"},chtml:{description:"Geçerli çizimi bağımsız, çevrimdışı bir HTML dosyasına dışa aktarır"},"-chtml":{description:"Komut satırı seçeneklerini kullanarak geçerli çizimi HTML'e dışa aktarır"},dimlinear:{description:"Doğrusal ölçülendirmeler oluşturur"},dimstyle:{description:"Geçerli ölçülendirme stilinin adını ayarlar"},dwgname:{description:"Geçerli çizim dosyasının adını saklar (salt okunur)"},loginname:{description:"Kullanıcının oturum açma adını görüntüler (salt okunur)"},dynmode:{description:"İmleçteki Dinamik Girdi ayarlarını denetler"},dynprompt:{description:"Dinamik Girdi araç ipuçlarında istemlerin görüntülenmesini denetler"},ellipse:{description:"Eksen uç noktalarına veya merkeze göre bir elips veya eliptik yay oluşturur"},erase:{description:"Seçili varlıkları çizimden siler",prompt:"Varlıkları seçin"},extmax:{description:"Model alanı çizim kapsamının sağ üst köşesini saklar (salt okunur)"},extmin:{description:"Model alanı çizim kapsamının sol alt köşesini saklar (salt okunur)"},entout:{description:"Seçili varlıklar için birleştirilmiş bir önizleme görüntüsü dışa aktarır",prompt:"Varlıkları seçin"},hideobjects:{description:"Seçili nesnelerin görüntülenmesini geçici olarak gizler",prompt:"Nesneleri seçin"},imageattach:{description:"Geçerli çizime harici başvuru olarak bir raster görüntü ekler"},"-insert":{description:"Bir blok tanımını geçerli çizime ekler (komut satırı)"},xattach:{description:"Geçerli çizime harici başvuru olarak bir DWG veya DXF çizimi ekler"},gripcolor:{description:"Seçili nesneler üzerinde görüntülenen seçilmemiş tutamaçların rengini ayarlar"},griphot:{description:"Seçili (sıcak) tutamaçların rengini ayarlar"},gripobjlimit:{description:"Seçim kümesi belirtilen nesne sayısını aştığında tutamaç görüntülenmesini engeller (0 = sınır yok)"},grips:{description:"Seçili nesnelerde tutamaçların görüntülenip görüntülenmeyeceğini denetler"},gripsize:{description:"Tutamaç kutularının piksel cinsinden boyutunu ayarlar"},hatch:{description:"Kapalı bir alanı veya seçili nesneleri bir tarama deseniyle doldurur"},ipdf:{description:"Bir PDF dosyasından vektör geometrisini içe aktarır"},hpang:{description:"Yeni oluşturulan tarama desenleri için varsayılan açıyı radyan cinsinden ayarlar"},hpassoc:{description:"Yeni oluşturulan taramaların ilişkisel olup olmayacağını denetler"},hpbackgroundcolor:{description:"Yeni oluşturulan tarama desenleri için varsayılan arka plan rengini ayarlar"},hpcolor:{description:"Yeni oluşturulan taramalar için varsayılan rengi ayarlar"},hpdouble:{description:"Kullanıcı tanımlı tarama desenlerinin ikiye katlanıp katlanmayacağını denetler"},hpislanddetection:{description:"Yeni oluşturulan tarama sınırları içindeki adaların nasıl işleneceğini denetler"},hplayer:{description:"Yeni oluşturulan taramalar ve dolgular için varsayılan katmanı ayarlar"},hpname:{description:"Bu oturumda yeni oluşturulan taramalar için varsayılan desen adını ayarlar"},hpscale:{description:"Yeni oluşturulan tarama desenleri için varsayılan ölçek faktörünü ayarlar"},hpseparate:{description:"Birden çok sınır için tek mi yoksa ayrı tarama nesneleri mi oluşturulacağını denetler"},hptransparency:{description:"Yeni oluşturulan taramalar ve dolgular için varsayılan saydamlığı ayarlar"},insunits:{description:"Eklenen blokların, görüntülerin veya dış referansların otomatik ölçeklendirilmesi için çizim birimlerini belirtir"},laycur:{description:"Seçili nesnelerin katman özelliğini geçerli katman olarak değiştirir",prompt:"Geçerli katmana değiştirilecek nesneleri seçin"},laydel:{description:"Bir katmanı ve o katmandaki tüm nesneleri siler"},layerclose:{description:"Katman Özellikleri Yöneticisi'ni kapatır"},layerp:{description:"Katman ayarlarında yapılan son değişikliği veya değişiklik kümesini geri alır"},layfrz:{description:"Seçili nesnelerin katmanını dondurur",prompt:"Dondurulacak katmandaki nesneyi seçin"},layiso:{description:"Seçili nesnelerin katmanlarını izole eder",prompt:"İzole edilecek katmanlardaki nesneleri seçin"},laylck:{description:"Seçili nesnelerin katmanını kilitler",prompt:"Kilitlenecek katmandaki nesneyi seçin"},layoff:{description:"Seçili nesnelerin katmanını kapatır",prompt:"Kapatılacak katmandaki nesneyi seçin"},layon:{description:"Çizimdeki tüm katmanları açar"},laythw:{description:"Çizimdeki tüm donmuş katmanları çözer"},layulk:{description:"Seçili nesnelerin katmanının kilidini açar",prompt:"Kilidi açılacak katmandaki nesneyi seçin"},layuniso:{description:"LAYISO tarafından gizlenen veya kilitlenen katmanları geri yükler"},line:{description:"Noktalar arasında düz çizgi parçaları çizer"},log:{description:"Hata ayıklama bilgilerini konsola kaydeder"},ltscale:{description:"Çizim için genel çizgi tipi ölçek faktörünü ayarlar"},lunits:{description:"Koordinatlar ve mesafeler için görüntüleme biçimini ayarlar"},luprec:{description:"LUNITS ile birlikte kullanılan, doğrusal birimler için görüntüleme hassasiyetini ayarlar"},lwdisplay:{description:"Çizgi kalınlıklarının çizimde görüntülenip görüntülenmeyeceğini denetler"},clearmeasurements:{description:"Geçerli yerleşimdeki tüm ölçümleri kaldırır"},measurementvis:{description:"Geçerli yerleşimdeki ölçümleri gösterir veya gizler"},measurementexport:{description:"Ölçümleri sidecar JSON dosyasına dışa aktarır"},measurementimport:{description:"Ölçümleri sidecar JSON dosyasından içe aktarır"},measurearea:{description:"Seçili nesnelerin veya noktaların alanını ve çevresini hesaplar"},measureangle:{description:"İki çizgi veya üç nokta arasındaki açıyı ölçer"},measurearc:{description:"Bir yay parçasının uzunluğunu ölçer"},measuredistance:{description:"İki nokta arasındaki mesafeyi ve delta değerlerini ölçer"},measurepoint:{description:"Seçilen noktanın X/Y koordinatlarını ölçer"},measurement:{description:"Çizimin İngiliz (emperyal) birimlerini mi yoksa metrik birimleri mi kullanacağını ayarlar"},measurementcolor:{description:"Ölçüm katmanları için kullanılan rengi ayarlar"},modelbkcolor:{description:"Model alanı çizim alanının arka plan rengini ayarlar"},mline:{description:"Tek bir çoklu çizgi nesnesi olarak birden çok paralel çizgi oluşturur"},move:{description:"Seçili varlıkları bir yer değiştirme vektörüne göre taşır",prompt:"Varlıkları seçin"},offset:{description:"Belirtilen bir mesafede paralel eğriler, çoklu çizgiler veya daireler oluşturur"},mtext:{description:"Bir çoklu metin varlığı oluşturur"},open:{description:"Mevcut bir çizim dosyasını açar"},openprof:{description:"Dosya açma aşaması zamanlama profillerinin konsola kaydedilip kaydedilmeyeceğini denetler"},openperf:{description:"Son çizim açılışının zamanlamalarını Open Performance paletinde gösterir"},orthomode:{description:"İmleç hareketini yatay veya dikey eksenle sınırlar"},osmode:{description:"Bit kodu değeri kullanarak çalışan Nesne Yakalama modlarını ayarlar"},pan:{description:"Görüntüleme yönünü veya büyütmeyi değiştirmeden görünümü kaydırır"},paperbkcolor:{description:"Kağıt alanı (düzen) çizim alanının arka plan rengini ayarlar"},pdmode:{description:"POINT varlıklarının nasıl görüntüleneceğini denetler"},pdsize:{description:"POINT varlıkları için görüntüleme boyutunu ayarlar"},pickbox:{description:"Nesneleri seçmek için kullanılan seçim kutusunun boyutunu (piksel cinsinden) ayarlar"},pline:{description:"Birden çok nokta belirterek bir çoklu çizgi oluşturur"},pngout:{description:"PNG olarak dışa aktarır"},point:{description:"Noktalar oluşturur"},polaraddang:{description:"Ek kutupsal izleme açılarını noktalı virgülle ayrılmış liste olarak saklar"},polarang:{description:"Kutupsal izleme için kutupsal açı artımını ayarlar"},polarmode:{description:"Kutupsal ve nesne yakalama izleme ayarlarını denetler"},polygon:{description:"Merkez/yarıçapa veya bir çokgen kenarına göre düzgün bir çokgen oluşturur"},qnew:{description:"Yeni bir çizim başlatır"},ray:{description:"Bir noktadan başlayıp sonsuza uzanan bir ışın oluşturur"},rectang:{description:"İki karşıt köşe belirterek bir dikdörtgen oluşturur"},regen:{description:"Geçerli çizimi yeniden çizer"},revcloud:{description:"Revizyon bulutu oluşturur veya değiştirir"},markuptext:{description:"Metin işareti yerleştirir"},markupline:{description:"Çizgi işareti oluşturur"},markuparrow:{description:"Ok işareti oluşturur"},markupcloud:{description:"Revizyon bulutu işareti oluşturur"},markuprect:{description:"Dikdörtgen işareti oluşturur"},markupcircle:{description:"Daire işareti oluşturur"},markuphighlight:{description:"Vurgu dikdörtgeni işareti oluşturur"},markupcallout:{description:"Çağrı notu oluşturur: önce lider ucunu, sonra metin kutusunu belirtin, ardından metni girin"},markupstamp:{description:"Damga veya özel sembol yerleştirir"},markupvis:{description:"İşaretleri gösterir veya gizler"},clearmarkups:{description:"Geçerli yerleşimdeki tüm işaretleri temizler"},markupexport:{description:"İşaretleri sidecar JSON dosyasına dışa aktarır"},markupimport:{description:"İşaretleri sidecar JSON dosyasından içe aktarır"},markuppanel:{description:"İşaret paletini açar"},rotate:{description:"Seçili varlıkları bir taban noktası etrafında döndürür",prompt:"Varlıkları seçin"},select:{description:"Varlıkları seçer"},shortcutmenu:{description:"Çizim alanındaki kısayol menülerinin kullanılabilirliğini denetler"},sketch:{description:"Bir dizi serbest el çizgi parçası oluşturur"},spline:{description:"Kontrol noktaları belirterek düzgün bir spline eğrisi oluşturur"},textstyle:{description:"Geçerli metin stilinin adını ayarlar"},unitmode:{description:"LUNITS Mimari veya Kesirli olduğunda koordinatların kesirli görüntülenmesini denetler"},switchbg:{description:"Çizim alanı arka planını beyaz ve siyah arasında değiştirir"},unisolateobjects:{description:"HIDEOBJECTS tarafından gizlenen tüm nesneleri yeniden görüntüler"},undo:{description:"Son veritabanı düzenleme işlemini geri alır",nothingToUndo:"Geri alınacak işlem yok."},redo:{description:"Geri alınan son veritabanı düzenleme işlemini yineler",nothingToRedo:"Yinelenecek işlem yok."},xline:{description:"Her iki yönde de sonsuza uzanan bir yapı çizgisi oluşturur"},zoom:{description:"Tüm varlıkların maksimum sınırlarını görüntülemek için yakınlaştırır"}},USER:{}},Qm={arc:{startPointOrCenter:"Yayın başlangıç noktasını belirtin veya",secondPointOrOptions:"Yayın ikinci noktasını belirtin veya",secondPoint:"Yayın ikinci noktasını belirtin",startPoint:"Yayın başlangıç noktasını belirtin",centerPoint:"Yayın merkez noktasını belirtin",endPoint:"Yayın bitiş noktasını belirtin",endPointOrOptions:"Yayın bitiş noktasını belirtin veya",centerPointOrOptions:"Yayın merkez noktasını belirtin",includedAngle:"İç açıyı belirtin",chordLength:"Kiriş uzunluğunu belirtin",tangentDirection:"Yayın başlangıç noktası için teğet yönünü belirtin",radius:"Yayın yarıçapını belirtin",keywords:{center:{display:"Merkez(M)",local:"Merkez",global:"Center"},end:{display:"Bitiş(B)",local:"Bitiş",global:"End"},angle:{display:"Açı(A)",local:"Açı",global:"Angle"},chordLength:{display:"kiriş Uzunluğu(U)",local:"Kiriş Uzunluğu",global:"ChordLength"},direction:{display:"Yön(Y)",local:"Yön",global:"Direction"},radius:{display:"Yarıçap(R)",local:"Yarıçap",global:"Radius"}},invalid:{threePoint:"Geçersiz 3 noktalı yay: noktalar aynı doğru üzerinde veya bir yay tanımlayamıyor.",center:"Geçersiz merkez girişi: başlangıç ve bitiş noktaları aynı çember üzerinde olmalıdır.",angle:"Geçersiz açı girişi: iç açı 0 dereceden büyük ve 360 dereceden küçük olmalıdır.",chordLength:"Geçersiz kiriş uzunluğu: değer mevcut yarıçap için geçerli aralığın dışında.",direction:"Geçersiz yön: bu teğet yönünden bir yay oluşturulamıyor.",radius:"Geçersiz yarıçap: belirtilen yarıçap başlangıç ve bitiş noktalarını birleştiremiyor."}},circle:{center:"Çemberin merkezini belirtin",centerOrOptions:"Çemberin merkez noktasını belirtin veya",radius:"Çemberin yarıçapını belirtin",radiusOrDiameter:"Çemberin yarıçapını belirtin veya",diameter:"Çemberin çapını belirtin",twoPointFirst:"Çember çapının ilk uç noktasını belirtin",twoPointSecond:"Çember çapının ikinci uç noktasını belirtin",threePointFirst:"Çember üzerindeki ilk noktayı belirtin",threePointSecond:"Çember üzerindeki ikinci noktayı belirtin",threePointThird:"Çember üzerindeki üçüncü noktayı belirtin",keywords:{threeP:{display:"3N(3N)",local:"3N",global:"3P"},twoP:{display:"2N(2N)",local:"2N",global:"2P"},diameter:{display:"Çap(Ç)",local:"Çap",global:"Diameter"}}},copy:{basePointOrOptions:"Temel noktayı belirtin veya",displacementOrArray:"Yer değiştirmeyi belirtin veya",secondPointOrArray:"İkinci noktayı belirtin veya",modePrompt:"Kopyalama modu seçeneğini girin",arrayItemCount:"Orijinal dahil dizideki öğe sayısını girin",arraySecondPointOrFit:"İkinci noktayı belirtin veya",arrayFitSecondPoint:"İkinci noktayı belirtin",keywords:{displacement:{display:"Yer değiştirme(Y)",local:"Yer değiştirme",global:"Displacement"},mode:{display:"Mod(O)",local:"Mod",global:"Mode"},multiple:{display:"Çoklu(Ç)",local:"Çoklu",global:"Multiple"},single:{display:"Tekli(T)",local:"Tekli",global:"Single"},array:{display:"Dizi(D)",local:"Dizi",global:"Array"},fit:{display:"Uydur(U)",local:"Uydur",global:"Fit"}}},dimlinear:{xLine1Point:"İlk uzatma çizgisinin başlangıç noktasını belirtin",xLine2Point:"İkinci uzatma çizgisinin başlangıç noktasını belirtin",dimLinePoint:"Ölçü çizgisi konumunu belirtin"},ellipse:{axisEndpointOrOptions:"Elipsin eksen uç noktasını belirtin veya",arcAxisEndpointOrCenter:"Eliptik yayın eksen uç noktasını belirtin veya",center:"Elipsin merkezini belirtin",firstAxisEndpoint:"Eksenin uç noktasını belirtin",secondAxisEndpoint:"Eksenin diğer uç noktasını belirtin",otherAxisOrRotation:"Diğer eksene olan mesafeyi belirtin veya",rotationAngle:"Ana eksen etrafındaki döndürme açısını belirtin",arcStartAngle:"Eliptik yayın başlangıç açısını belirtin",arcEndAngle:"Eliptik yayın bitiş açısını belirtin",keywords:{arc:{display:"Yay(Y)",local:"Yay",global:"Arc"},center:{display:"Merkez(M)",local:"Merkez",global:"Center"},rotation:{display:"Döndürme(D)",local:"Döndürme",global:"Rotation"}},invalid:{axis:"Geçersiz eksen girişi: eksen uzunluğu 0'dan büyük olmalıdır.",otherAxis:"Geçersiz diğer eksen girişi: mesafe 0'dan büyük olmalıdır.",rotation:"Geçersiz döndürme girişi: elde edilen küçük eksen 0'dan büyük olmalıdır."}},hatch:{prompt:"Sınır nesnesini seçin veya",pickPoint:"İç noktayı belirtin (bitirmek için Enter'a basın)",select:"Tarama yapılacak nesneleri seçin",patternName:"Tarama deseni adını girin",scale:"Tarama deseni ölçeğini belirtin",angle:"Tarama deseni açısını belirtin",style:"Tarama stilini girin",associative:"İlişkiselliği belirtin",invalidBoundary:"Seçilen nesneler kapalı bir sınır oluşturmuyor.",keywords:{pick:{display:"Nokta seç(N)",local:"Nokta seç",global:"PickPoints"},select:{display:"Nesne seç(S)",local:"Nesne seç",global:"SelectObjects"},cancel:{display:"İptal(İ)",local:"İptal",global:"Cancel"},pattern:{display:"Desen(D)",local:"Desen",global:"Pattern"},scale:{display:"Ölçek(Ö)",local:"Ölçek",global:"Scale"},angle:{display:"Açı(A)",local:"Açı",global:"Angle"},style:{display:"Stil(T)",local:"Stil",global:"HatchStyle"},associative:{display:"İlişkisel(İL)",local:"İlişkisel",global:"AssociativeMode"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},outer:{display:"Dış(D)",local:"Dış",global:"Outer"},ignore:{display:"Yoksay(Y)",local:"Yoksay",global:"Ignore"},yes:{display:"Evet(E)",local:"Evet",global:"Yes"},no:{display:"Hayır(H)",local:"Hayır",global:"No"}}},hideobjects:{hidden:"nesne gizlendi",restored:"nesne geri yüklendi",nothingToRestore:"Geri yüklenecek gizli nesne yok"},entout:{longSidePrompt:"Önizleme uzun kenar boyutunu piksel olarak girin",exported:"nesne önizlemesi dışa aktarıldı",skipped:"nesne atlandı",failed:{"no-preview-root":"Seçim için önizleme geometrisi oluşturulamadı","no-bounds":"Seçim için önizleme sınırları hesaplanamadı","capture-failed":"Nesne önizleme görüntüsü oluşturulamadı","download-failed":"Önizleme oluşturuldu ancak PNG indirmesi başarısız oldu"}},layer:{main:"Seçenek girin",listSummary:"Katman listesi tarayıcı konsoluna yazdırıldı",emptyInput:"Katman adı girilmedi.",newPrompt:"Yeni katman(lar) için ad girin",makePrompt:"Geçerli yapılacak katmanın adını girin",setPrompt:"Geçerli olarak ayarlanacak katmanın adını girin",onPrompt:"Açılacak katman ad(lar)ını girin",offPrompt:"Kapatılacak katman ad(lar)ını girin",freezePrompt:"Dondurulacak katman ad(lar)ını girin",thawPrompt:"Çözülecek katman ad(lar)ını girin",lockPrompt:"Kilitlenecek katman ad(lar)ını girin",unlockPrompt:"Kilidi açılacak katman ad(lar)ını girin",colorLayerPrompt:"Rengi değiştirilecek katman ad(lar)ını girin",colorValuePrompt:"Renk girin (ACI 1-255, 255,0,0 gibi RGB veya CSS renk adı)",invalidColor:"Geçersiz renk girişi.",descriptionLayerPrompt:"Açıklaması düzenlenecek katman adını girin",descriptionValuePrompt:"Yeni katman açıklamasını girin",created:"Oluşturulan katman sayısı",alreadyExists:"Katman zaten mevcut",notFound:"Katman bulunamadı",cannotChangeCurrent:"Geçerli katman kapatılamaz veya dondurulamaz.",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"Yap(Y)",local:"Yap",global:"Make"},set:{display:"Ayarla(A)",local:"Ayarla",global:"Set"},new:{display:"Yeni(Y)",local:"Yeni",global:"New"},on:{display:"Aç(A)",local:"Aç",global:"On"},off:{display:"Kapat(K)",local:"Kapat",global:"Off"},color:{display:"Renk(R)",local:"Renk",global:"Color"},freeze:{display:"Dondur(D)",local:"Dondur",global:"Freeze"},thaw:{display:"Çöz(Ç)",local:"Çöz",global:"Thaw"},lock:{display:"Kilitle(K)",local:"Kilitle",global:"Lock"},unlock:{display:"Kilidi aç(A)",local:"Kilidi aç",global:"Unlock"},description:{display:"Açıklama(A)",local:"Açıklama",global:"Description"}}},layon:{alreadyOn:"Tüm katmanlar zaten açık.",turnedOn:"Açılan katmanlar"},laycur:{prompt:"Geçerli katmana değiştirilecek nesneleri seçin",currentLayerNotFound:"Geçerli katman bulunamadı.",noObjects:"Geçerli nesne seçilmedi.",alreadyCurrent:"Seçilen nesneler zaten geçerli katmanda.",changed:"Geçerli katmana değiştirilen nesneler"},layfrz:{prompt:"Dondurulacak katmandaki nesneyi seçin veya",invalidSelection:"Geçersiz nesne seçildi.",settingsPrompt:"Değiştirilecek LAYFRZ ayarını girin",viewportPrompt:"Görüntü penceresi dondurma davranışını belirtin",blockSelectionPrompt:"İç içe blok seçim davranışını belirtin",vpfreezeFallback:"Mevcut görüntüleyici, görüntü penceresi başına katman dondurmayı desteklemiyor; bunun yerine Dondur davranışı kullanılıyor.",nestedSelectionLimited:"İç içe blok seçim ayarları kaydedildi, ancak mevcut seçim işlemi yine de üst düzey nesnenin katmanını çözümlüyor.",layerNotFound:"Katman bulunamadı",cannotFreezeCurrent:"Geçerli katman dondurulamaz.",alreadyFrozen:"Katman zaten donuk",frozen:"Dondurulan katman",restored:"Geri yüklenen katman",nothingToUndo:"Geri alınacak bir LAYFRZ işlemi yok.",keywords:{settings:{display:"Ayarlar(A)",local:"Ayarlar",global:"Settings"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},viewports:{display:"Görüntü pencereleri(G)",local:"Görüntü pencereleri",global:"Viewports"},blockSelection:{display:"Blok seçimi(B)",local:"Blok seçimi",global:"BlockSelection"},freeze:{display:"Dondur(D)",local:"Dondur",global:"Freeze"},vpfreeze:{display:"Görüntü dondur(V)",local:"Görüntü dondur",global:"Vpfreeze"},block:{display:"Blok(B)",local:"Blok",global:"Block"},entity:{display:"Nesne(N)",local:"Nesne",global:"Entity"},none:{display:"Hiçbiri(H)",local:"Hiçbiri",global:"None"}}},layiso:{prompt:"İzole edilecek katman(lar)daki nesneleri seçin veya",settingsPrompt:"İzole edilmeyen katmanlar için ayarı girin",offModePrompt:"İzole edilmeyen katmanlar için kapatma davranışını girin",noLayers:"Geçerli katman seçilmedi.",layerNotFound:"Katman bulunamadı",isolated:"İzole edilen katman(lar)",affectedLayers:"etkilenen katmanlar",vpfreezeFallback:"Mevcut görüntüleyici, görüntü penceresi başına katman dondurmayı desteklemiyor; bunun yerine Kapat davranışı kullanılıyor.",lockFadeFallback:"Mevcut görüntüleyici katman solma görüntüsünü desteklemiyor; izole edilmeyen katmanlar solma olmadan kilitlenecek.",keywords:{settings:{display:"Ayarlar(A)",local:"Ayarlar",global:"Settings"},off:{display:"Kapat(K)",local:"Kapat",global:"Off"},lockAndFade:{display:"Kilitle ve soldur(K)",local:"Kilitle ve soldur",global:"LockAndFade"},vpfreeze:{display:"Görüntü dondur(V)",local:"Görüntü dondur",global:"Vpfreeze"}}},layuniso:{noPrevious:"Geri yüklenecek önceki LAYISO katman durumu yok.",layerNotFound:"Katman bulunamadı",nothingRestored:"Hiçbir LAYISO katman değişikliği geri yüklenmedi.",restored:"Geri yüklenen katmanlar"},laythw:{alreadyThawed:"Tüm katmanlar zaten çözülmüş.",thawed:"Çözülen katmanlar"},laylck:{prompt:"Kilitlenecek katmandaki bir nesneyi seçin",invalidSelection:"Geçersiz nesne seçildi.",layerNotFound:"Katman bulunamadı",alreadyLocked:"Katman zaten kilitli",locked:"Kilitlenen katman"},layulk:{prompt:"Kilidi açılacak katmandaki bir nesneyi seçin",invalidSelection:"Geçersiz nesne seçildi.",layerNotFound:"Katman bulunamadı",alreadyUnlocked:"Katmanın kilidi zaten açık",unlocked:"Kilidi açılan katman"},layoff:{prompt:"Kapatılacak katmandaki nesneyi seçin veya",invalidSelection:"Geçersiz nesne seçildi.",settingsPrompt:"Değiştirilecek LAYOFF ayarını girin",viewportPrompt:"Görüntü penceresi davranışını belirtin",blockSelectionPrompt:"İç içe blok seçim davranışını belirtin",vpfreezeFallback:"Mevcut görüntüleyici, görüntü penceresi başına katman kapatmayı desteklemiyor; bunun yerine Kapat davranışı kullanılıyor.",nestedSelectionLimited:"İç içe blok seçim ayarları kaydedildi, ancak mevcut seçim işlemi yine de üst düzey nesnenin katmanını çözümlüyor.",layerNotFound:"Katman bulunamadı",cannotTurnOffCurrent:"Geçerli katman kapatılamaz.",alreadyOff:"Katman zaten kapalı",turnedOff:"Kapatılan katman",restored:"Geri yüklenen katman",nothingToUndo:"Geri alınacak bir LAYOFF işlemi yok.",keywords:{settings:{display:"Ayarlar(A)",local:"Ayarlar",global:"Settings"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},viewports:{display:"Görüntü pencereleri(G)",local:"Görüntü pencereleri",global:"Viewports"},blockSelection:{display:"Blok seçimi(B)",local:"Blok seçimi",global:"BlockSelection"},off:{display:"Kapat(K)",local:"Kapat",global:"Off"},vpfreeze:{display:"Görüntü dondur(V)",local:"Görüntü dondur",global:"Vpfreeze"},block:{display:"Blok(B)",local:"Blok",global:"Block"},entity:{display:"Nesne(N)",local:"Nesne",global:"Entity"},none:{display:"Hiçbiri(H)",local:"Hiçbiri",global:"None"}}},layerp:{restored:"Önceki katman durumu geri yüklendi.",noPreviousState:"Geri yüklenecek önceki bir katman durumu yok."},line:{firstPoint:"İlk noktayı belirtin",firstPointOrContinue:"İlk noktayı belirtin veya",nextPoint:"Sonraki noktayı belirtin",nextPointWithOptions:"Sonraki noktayı belirtin veya",keywords:{continue:{display:"Devam et(D)",local:"Devam et",global:"Continue"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},close:{display:"Kapat(K)",local:"Kapat",global:"Close"}}},xline:{firstPointOrOptions:"Bir nokta belirtin veya",secondPoint:"İkinci noktayı belirtin",throughPoint:"Geçiş noktasını belirtin",angle:"Sonsuz doğru açısını girin",invalidDirection:"XLINE için geçersiz yön.",keywords:{hor:{display:"Yatay(Y)",local:"Yatay",global:"Hor"},ver:{display:"Dikey(D)",local:"Dikey",global:"Ver"},ang:{display:"Açı(A)",local:"Açı",global:"Ang"}}},ray:{startPoint:"Başlangıç noktasını belirtin",throughPoint:"Geçiş noktasını belirtin"},mline:{startPointWithOptions:"Başlangıç noktasını belirtin veya",nextPointWithOptions:"Sonraki noktayı belirtin veya",justificationPrompt:"Hizalama türünü girin",scalePrompt:"Çoklu çizgi ölçeğini belirtin",stylePrompt:"Çoklu çizgi stil adını girin veya liste için [?]",styleNotFound:"Çoklu çizgi stili bulunamadı",styleListHeader:"Yüklenen çoklu çizgi stilleri",styleListEmpty:"Mevcut çizimde yüklü çoklu çizgi stili yok.",keywords:{justification:{display:"Hizalama(H)",local:"Hizalama",global:"Justification"},scale:{display:"Ölçek(Ö)",local:"Ölçek",global:"Scale"},style:{display:"Stil(ST)",local:"Stil",global:"Style"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},close:{display:"Kapat(K)",local:"Kapat",global:"Close"},top:{display:"Üst(Ü)",local:"Üst",global:"Top"},zero:{display:"Sıfır(S)",local:"Sıfır",global:"Zero"},bottom:{display:"Alt(A)",local:"Alt",global:"Bottom"}}},measureAngle:{vertex:"Köşe noktasını belirtin",arm1:"Birinci kol üzerindeki noktayı belirtin",arm2:"İkinci kol üzerindeki noktayı belirtin"},measureArc:{startPoint:"Yayın başlangıç noktasını belirtin",throughPoint:"Yay üzerinde bir nokta belirtin",endPoint:"Yayın bitiş noktasını belirtin",lockedEndPoint:"Yayın bitiş noktasını belirtin (Ctrl ile büyük/küçük yay arasında geçiş)",invalidPoints:"Üç nokta doğrusal ve bir yay tanımlamıyor."},measureArea:{firstPoint:"İlk noktayı belirtin",nextPoint:"Sonraki noktayı belirtin (bitirmek için Enter'a basın)"},measureDistance:{firstPoint:"İlk noktayı belirtin",secondPoint:"İkinci noktayı belirtin"},measurePoint:{point:"Noktayı belirtin"},measurement:{import:{chooseFile:"Bir ölçüm sidecar JSON dosyası seçin"}},markup:{author:"İnceleme yazarını belirtin (sonraki kullanımlar için kaydedilir)",text:{point:"Metin işaretinin noktasını belirtin",content:"İşaret metnini girin"},line:{firstPoint:"Çizgi işaretinin ilk noktasını belirtin",secondPoint:"Çizgi işaretinin ikinci noktasını belirtin"},arrow:{firstPoint:"Okun başlangıç noktasını belirtin",secondPoint:"Ok ucunu belirtin"},cloud:{firstCorner:"Bulutun ilk köşesini belirtin",secondCorner:"Bulutun karşı köşesini belirtin"},rect:{firstCorner:"Dikdörtgenin ilk köşesini belirtin",secondCorner:"Dikdörtgenin karşı köşesini belirtin"},circle:{center:"Dairenin merkezini belirtin",radius:"Dairenin yarıçapını belirtin"},shape:{calloutOn:"[Çağrı açık]",calloutOff:"[Çağrı kapalı]",calloutAnchor:"Çağrı metninin konumunu belirtin",keywords:{callout:{display:"Çağrı(C)",local:"Çağrı",global:"Callout"},noCallout:{display:"ÇağrıYok(N)",local:"ÇağrıYok",global:"NoCallout"}}},highlight:{firstCorner:"Vurgu dikdörtgeninin ilk köşesini belirtin",secondCorner:"Vurgu dikdörtgeninin karşı köşesini belirtin"},callout:{tip:"Lider ucunu belirtin (ok ucu)",anchor:"Çağrı metninin konumunu belirtin",content:"Çağrı metnini girin"},stamp:{kind:"Damga kimliğini girin [approved/rejected/revised/for-review/custom]",imageUrl:"Özel damga görüntüsü URL’sini girin (isteğe bağlı)",caption:"Damga açıklamasını girin (isteğe bağlı)",point:"Damga ekleme noktasını belirtin"},import:{chooseFile:"Bir işaret sidecar JSON dosyası seçin"}},move:{basePointOrDisplacement:"Temel noktayı belirtin veya",secondPointOrDisplacement:"İkinci noktayı belirtin veya",displacement:"Yer değiştirmeyi belirtin",keywords:{displacement:{display:"Yer değiştirme(Y)",local:"Yer değiştirme",global:"Displacement"}}},offset:{distance:"Öteleme mesafesini belirtin",selectObject:"Ötelenecek nesneyi seçin veya bitirmek için Enter'a basın",sidePoint:"Ötelenecek tarafta bir nokta belirtin",invalidDistance:"Öteleme mesafesi 0'dan büyük olmalıdır.",invalidSelection:"Seçilen nesne ötelenemez.",offsetFailed:"Belirtilen taraf için bir öteleme eğrisi oluşturulamadı."},mtext:{point:"Çok satırlı metin ekleme noktasını belirtin"},pngout:{boundsFirstCorner:"Sınırların ilk köşesini belirtin",boundsSecondCorner:"Karşı köşeyi belirtin",longSidePrompt:"Uzun kenar boyutunu piksel olarak girin"},imageattach:{insertionPoint:"Ekleme noktasını belirtin:",scale:"Ölçek faktörünü belirtin:",rotation:"Döndürme açısını belirtin:",invalidScale:"Ölçek faktörü 0 dan büyük olmalıdır.",decodeFailed:"Seçilen görüntü dosyası okunamadı."},insert:{blockName:"Blok adını girin:",insertionPoint:"Ekleme noktasını belirtin:",scale:"Ölçek faktörünü belirtin:",rotation:"Döndürme açısını belirtin:",invalidScale:"Ölçek faktörü 0 dan büyük olmalıdır.",invalidBlockName:"Geçersiz blok adı.",blockNotFound:"Blok bulunamadı",xrefNotAllowed:"Harici referans -INSERT ile eklenemez."},xattach:{insertionPoint:"Ekleme noktasını belirtin:",scale:"Ölçek faktörünü belirtin:",rotation:"Döndürme açısını belirtin:",invalidScale:"Ölçek faktörü 0 dan büyük olmalıdır.",unsupportedFile:"Lütfen bir DWG veya DXF dosyası seçin.",loading:"Harici referans yükleniyor...",loadFailed:"Seçilen çizim dosyası okunamadı."},point:{point:"Bir nokta belirtin"},polygon:{numberOfSides:"Kenar sayısını girin",centerOrEdge:"Çokgenin merkezini belirtin veya",radiusOrType:"Seçenekleri girin",edgeStart:"Kenarın ilk uç noktasını belirtin",edgeEnd:"Kenarın ikinci uç noktasını belirtin",keywords:{edge:{display:"Kenar(K)",local:"Kenar",global:"Edge"},inscribed:{display:"Çembere iç teğet(İ)",local:"Çembere iç teğet",global:"Inscribed"},circumscribed:{display:"Çembere dış teğet(D)",local:"Çembere dış teğet",global:"Circumscribed"}},invalid:{sides:"Geçersiz kenar sayısı. 3 ile 1024 arasında bir tam sayı girin.",radius:"Geçersiz yarıçap. Yarıçap 0'dan büyük olmalıdır.",edge:"Geçersiz kenar. Kenar uzunluğu 0'dan büyük olmalıdır."}},polyline:{firstPoint:"İlk noktayı belirtin",nextPoint:"Sonraki noktayı belirtin (bitirmek için Enter'a basın)",nextPointWithOptions:"Sonraki noktayı belirtin veya",nextPointWithArcOptions:"Sonraki noktayı belirtin veya",keywords:{arc:{display:"Yay(Y)",local:"Yay",global:"Arc"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},close:{display:"Kapat(K)",local:"Kapat",global:"Close"},line:{display:"Doğru(D)",local:"Doğru",global:"Line"},angle:{display:"Açı(A)",local:"Açı",global:"Angle"},center:{display:"Merkez(M)",local:"Merkez",global:"Center"},secondPoint:{display:"İkinci nokta(İ)",local:"İkinci nokta",global:"SecondPoint"},radius:{display:"Yarıçap(R)",local:"Yarıçap",global:"Radius"}},arcAngle:"Yay açısını belirtin",arcCenter:"Merkez noktasını belirtin",arcSecondPoint:"Yay üzerinde ikinci noktayı belirtin",arcEndPoint:"Yayın bitiş noktasını belirtin",arcRadius:"Yay yarıçapını belirtin"},rect:{firstPoint:"İlk köşe noktasını belirtin",nextPoint:"Diğer köşe noktasını belirtin",firstPointWithOptions:"İlk köşe noktasını belirtin veya",otherCornerWithOptions:"Diğer köşe noktasını belirtin veya",chamferFirst:"İlk pah mesafesini belirtin",chamferSecond:"İkinci pah mesafesini belirtin",filletRadius:"Yuvarlatma yarıçapını belirtin",segmentWidth:"Dikdörtgen çizgi genişliğini belirtin",elevationValue:"Kotu belirtin",thicknessValue:"Kalınlığı belirtin",rotationAngle:"Dikdörtgen döndürme açısını belirtin",dimensionLength:"Dikdörtgen uzunluğunu belirtin",dimensionWidth:"Dikdörtgen genişliğini belirtin",areaValue:"Dikdörtgen alanını belirtin",areaLengthOrWidth:"Dikdörtgen uzunluğunu belirtin",areaSpecifyWidth:"Dikdörtgen genişliğini belirtin",invalidPositive:"Geçersiz giriş. Lütfen 0'dan büyük bir değer girin.",invalidRect:"Dikdörtgen oluşturulamadı. Lütfen geçerli köşeler veya boyutlar belirtin.",thicknessNotSupported:"Dikdörtgen kalınlığı şu anda nesne verisine yazılmıyor. Kalınlık ayarı yok sayılıyor.",keywords:{chamfer:{display:"Pah(P)",local:"Pah",global:"Chamfer"},elevation:{display:"Kot(K)",local:"Kot",global:"Elevation"},fillet:{display:"Yuvarlatma(Y)",local:"Yuvarlatma",global:"Fillet"},thickness:{display:"Kalınlık(K)",local:"Kalınlık",global:"Thickness"},width:{display:"Genişlik(G)",local:"Genişlik",global:"Width"},area:{display:"Alan(A)",local:"Alan",global:"Area"},dimensions:{display:"Boyutlar(B)",local:"Boyutlar",global:"Dimensions"},rotation:{display:"Döndürme(D)",local:"Döndürme",global:"Rotation"},length:{display:"Uzunluk(U)",local:"Uzunluk",global:"Length"},rectWidth:{display:"Genişlik(G)",local:"Genişlik",global:"Width"}}},rotate:{basePoint:"Temel noktayı belirtin",rotationAngleOrOptions:"Döndürme açısını belirtin veya",referenceAngleOrPoints:"Referans açısını belirtin veya",firstReferencePoint:"Referans açısının ilk noktasını belirtin",secondReferencePoint:"İkinci noktayı belirtin",newAngle:"Yeni açıyı belirtin",keywords:{copy:{display:"Kopyala(K)",local:"Kopyala",global:"Copy"},reference:{display:"Referans(R)",local:"Referans",global:"Reference"},points:{display:"Noktalar(N)",local:"Noktalar",global:"Points"}},invalid:{referencePoints:"Geçersiz referans noktaları: noktalar farklı olmalıdır."}},revcloud:{firstCornerOrOptions:"İlk köşe noktasını belirtin veya",firstCorner:"İlk köşe noktasını belirtin",oppositeCorner:"Karşı köşeyi belirtin",startPoint:"Başlangıç noktasını belirtin",nextPoint:"Sonraki noktayı belirtin",nextPointOrUndo:"Sonraki noktayı belirtin veya",firstPoint:"İlk noktayı belirtin",guideCursor:"İmleci bulut yolu boyunca götürün (bitirmek için Enter)",arcLength:"Yay uzunluğunu belirtin",selectObject:"Nesne seçin",style:"Revizyon bulutu yay stilini girin",reverseDirection:"Yönü ters çevir",invalidArcLength:"Yay uzunluğu 0'dan büyük olmalıdır.",invalidObject:"Seçilen nesne revizyon bulutuna dönüştürülemez.",keywords:{arcLength:{display:"Yay uzunluğu(A)",local:"Yay uzunluğu",global:"ArcLength"},object:{display:"Nesne(O)",local:"Nesne",global:"Object"},rectangular:{display:"Dikdörtgen(R)",local:"Dikdörtgen",global:"Rectangular"},polygonal:{display:"Çokgen(P)",local:"Çokgen",global:"Polygonal"},freehand:{display:"Serbest(F)",local:"Serbest",global:"Freehand"},style:{display:"Stil(S)",local:"Stil",global:"Style"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},calligraphy:{display:"Kaligrafi(C)",local:"Kaligrafi",global:"Calligraphy"},undo:{display:"Geri al(U)",local:"Geri al",global:"Undo"},yes:{display:"Evet(Y)",local:"Evet",global:"Yes"},no:{display:"Hayır(N)",local:"Hayır",global:"No"}}},sketch:{specifySketch:"Eskizi belirtin veya",sketching:"Eskiz için işaretçiyi hareket ettirin (durdurmak için tıklayın veya Enter)",type:"Eskiz türünü girin",increment:"Eskiz artışını belirtin",tolerance:"Spline toleransını belirtin",firstPoint:"İlk noktayı belirtin",nextPoint:"Bitiş noktasını belirtin",keywords:{type:{display:"Tür(T)",local:"Tür",global:"Type"},increment:{display:"Artış(I)",local:"Artış",global:"Increment"},tolerance:{display:"toLerance(L)",local:"toLerance",global:"Tolerance"},line:{display:"Çizgiler(L)",local:"Çizgiler",global:"Lines"},polyline:{display:"Çoklu çizgi(P)",local:"Çoklu çizgi",global:"Polyline"},spline:{display:"Spline(S)",local:"Spline",global:"Spline"}}},spline:{firstPoint:"İlk noktayı belirtin",nextPoint:"Sonraki noktayı belirtin (bitirmek için Enter'a basın)",firstPointWithOptions:"İlk noktayı belirtin veya",nextPointWithFitOptions:"Sonraki noktayı belirtin veya",nextPointWithCvOptions:"Sonraki kontrol noktasını belirtin veya",methodPrompt:"Spline oluşturma yöntemini girin",knotsPrompt:"Düğüm parametrelemesini girin",degreePrompt:"Spline derecesini belirtin",keywords:{method:{display:"Yöntem(Y)",local:"Yöntem",global:"Method"},fit:{display:"Uydur(U)",local:"Uydur",global:"Fit"},cv:{display:"KN(K)",local:"KN",global:"CV"},knots:{display:"Düğümler(D)",local:"Düğümler",global:"Knots"},degree:{display:"Derece(D)",local:"Derece",global:"Degree"},undo:{display:"Geri al(G)",local:"Geri al",global:"Undo"},close:{display:"Kapat(K)",local:"Kapat",global:"Close"},chord:{display:"Kiriş(K)",local:"Kiriş",global:"Chord"},sqrtChord:{display:"Karekök kiriş(K)",local:"Karekök kiriş",global:"SqrtChord"},uniform:{display:"Düzgün(D)",local:"Düzgün",global:"Uniform"}}},sysvar:{prompt:"Lütfen yeni değeri girin"},zoom:{mainPrompt:"Pencerenin köşesini belirtin veya",firstCorner:"İlk köşeyi belirtin",secondCorner:"Karşı köşeyi belirtin",centerPoint:"Merkez noktasını belirtin",heightOrScale:"Yükseklik veya ölçek faktörünü girin (nX veya nXP)",scaleFactor:"Ölçek faktörünü girin (nX veya nXP)",keywords:{all:{display:"Tümü(T)",local:"Tümü",global:"All"},center:{display:"Merkez(M)",local:"Merkez",global:"Center"},extents:{display:"Kapsam(K)",local:"Kapsam",global:"Extents"},previous:{display:"Önceki(Ö)",local:"Önceki",global:"Previous"},scale:{display:"Ölçek(Ö)",local:"Ölçek",global:"Scale"},window:{display:"Pencere(P)",local:"Pencere",global:"Window"}}},chtml:{exportInvisibleLayers:"Görünmez katmanları dışa aktar",exportLayouts:"Yerleşimleri dışa aktar",initialView:"HTML açılırken başlangıç görünümü",viewerMode:"Çevrimdışı görüntüleyici modu",keywords:{yes:{display:"Evet(E)",local:"Evet",global:"Yes"},no:{display:"Hayır(H)",local:"Hayır",global:"No"},extents:{display:"Kapsam(K)",local:"Kapsam",global:"Extents"},current:{display:"Geçerli(G)",local:"Geçerli",global:"Current"},view:{display:"Görünüm(G)",local:"Görünüm",global:"View"},measure:{display:"Ölçüm ve İnceleme(Ö)",local:"Ölçüm ve İnceleme",global:"Measure"}}}},ey={document:{untitled:"Adsız"},commandLine:{noLast:"(önceki komut yok)",unknownCommand:"Bilinmeyen komut",executed:"Komut çalıştırıldı",showHistory:"Komut geçmişini göster",placeholder:"Komut girin",showMessages:"Mesaj geçmişini göster",canceled:"*İptal edildi*",noHistory:"(geçmiş yok)",invalidInput:"Geçersiz giriş.",close:"Komut satırını kapat"},inputManager:{firstCorner:"İlk köşeyi belirtin veya",secondCorner:"İkinci köşeyi belirtin veya"},message:{fetchingDrawingFile:"Dosya alınıyor ...",exportingDxf:"DXF dışa aktarılıyor ...",exportingEntityPreview:"Görüntü dışa aktarılıyor ...",collectingMemoryProfile:"Bellek analiz ediliyor ...",fontCached:"Yazı tipi başarıyla önbelleğe alındı",fontCacheFailed:"Yazı tipi önbelleğe alınamadı"},progress:{start:"Dosya ayrıştırma başlatılıyor ...",parse:"Dosya ayrıştırılıyor ...",font:"Bu çizim için gerekli yazı tipleri indiriliyor ...",ltype:"Çizgi tipleri ayrıştırılıyor ...",style:"Metin stilleri ayrıştırılıyor ...",dimstyle:"Ölçülendirme stilleri ayrıştırılıyor ...",layer:"Katmanlar ayrıştırılıyor ...",vport:"Görüntü portları ayrıştırılıyor ...",blockrecord:"Blok kaydı ayrıştırılıyor ...",header:"Başlık ayrıştırılıyor ...",block:"Bloklar ayrıştırılıyor ...",entity:"Nesneler ayrıştırılıyor ...",object:"Adlandırılmış sözlükler ayrıştırılıyor ...",rendering:"Çizim render ediliyor ...",end:"Tamamlandı!"},about:{title:"Hakkında",close:"Kapat",product:"CAD Viewer",tagline:"DWG ve DXF çizimleri için yüksek performanslı web CAD görüntüleyici.",website:"Web sitesi",docs:"Belgeler",repository:"GitHub",copyright:"© {year} mlightcad. Tüm hakları saklıdır.",ok:"Tamam"},drawStyle:{color:"Renk",lineWeight:"Çizgi kalınlığı",fontSize:"Yazı yüksekliği"}},ty={ACAD:{"-hatch":{description:"通过命令行选项创建填充,不显示 Ribbon 界面"},"-layer":{description:"通过命令行选项管理图层"},about:{description:"显示 mlightcad 产品信息"},acadver:{description:"存储图形数据库版本标识符(只读)"},angbase:{description:"设置当前 UCS 中 0 度的基准角方向"},angdir:{description:"设置正角度的方向为顺时针或逆时针"},arc:{description:"创建圆弧"},aunits:{description:"设置角度显示格式"},auprec:{description:"设置角度显示精度(小数位数),与 AUNITS 配合使用"},cdxf:{description:"导出当前图纸为DXF格式"},cpdf:{description:"导出当前图纸为PDF格式"},cecolor:{description:"设置新创建对象的当前默认颜色"},celtscale:{description:"控制新创建对象的线型比例系数"},celtype:{description:"设置新创建对象的线型"},celweight:{description:"设置新创建对象的默认线宽"},cetransparency:{description:"设置新创建对象的透明度"},cachefont:{description:"将本地字体文件缓存到 IndexedDB 以供文字渲染使用"},circle:{description:"使用圆心和半径创建圆"},clayer:{description:"设置新建对象和编辑操作所使用的当前图层"},cmleaderstyle:{description:"设置当前多重引线样式名称"},cmlscale:{description:"控制多线的整体宽度"},cmlstyle:{description:"设置当前多线样式名称"},colortheme:{description:"控制用户界面的颜色主题(深色或浅色)"},copy:{description:"通过克隆将所选图元复制到新位置",prompt:"选择对象"},csvg:{description:"转换当前图纸为SVG格式"},chtml:{description:"将当前图纸导出为可离线打开的 HTML 文件"},"-chtml":{description:"通过命令行选项将当前图纸导出为 HTML 文件"},dimlinear:{description:"创建线性尺寸标注"},dimstyle:{description:"设置当前标注样式的名称"},dwgname:{description:"存储当前图形文件的名称(只读)"},loginname:{description:"显示当前用户的登录名(只读)"},dynmode:{description:"控制光标处的动态输入设置"},dynprompt:{description:"控制动态输入工具提示中提示的显示"},ellipse:{description:"通过轴端点或中心点创建椭圆或椭圆弧"},erase:{description:"从图纸中删除所选对象",prompt:"选择对象"},extmax:{description:"存储模型空间图形范围的右上角(只读)"},extmin:{description:"存储模型空间图形范围的左下角(只读)"},entout:{description:"导出所选对象的合并预览图",prompt:"选择对象"},hideobjects:{description:"临时隐藏所选对象的显示",prompt:"选择对象"},imageattach:{description:"将光栅图像作为外部参照附着到当前图形"},"-insert":{description:"将块定义插入到当前图形(命令行)"},xattach:{description:"将 DWG 或 DXF 图形作为外部参照附着到当前图形"},gripcolor:{description:"设置所选对象上未选中夹点的颜色"},griphot:{description:"设置所选(热)夹点的颜色"},gripobjlimit:{description:"当选择集中的对象数超过指定值时不显示夹点(0 表示无限制)"},grips:{description:"控制是否在所选对象上显示夹点"},gripsize:{description:"设置夹点框的大小(像素)"},hatch:{description:"用填充图案填充封闭区域或所选对象"},ipdf:{description:"从 PDF 文件导入矢量几何"},hpang:{description:"设置新创建填充图案的默认角度(弧度)"},hpassoc:{description:"控制新创建的填充是否具有关联性"},hpbackgroundcolor:{description:"设置新创建填充图案的默认背景颜色"},hpcolor:{description:"设置新创建填充的默认颜色"},hpdouble:{description:"控制用户定义的填充图案是否加倍"},hpislanddetection:{description:"控制新创建填充边界内孤岛的处理方式"},hplayer:{description:"设置新创建填充和填充区域的默认图层"},hpname:{description:"设置当前会话中新创建填充的默认图案名称"},hpscale:{description:"设置新创建填充图案的默认比例系数"},hpseparate:{description:"控制为多个边界创建单个还是独立的填充对象"},hptransparency:{description:"设置新创建填充和填充区域的默认透明度"},insunits:{description:"指定插入块、图像或外部参照时用于自动缩放的图形单位"},laycur:{description:"将所选对象的图层属性更改为当前图层",prompt:"选择要更改到当前图层的对象"},laydel:{description:"删除图层及该图层上的所有对象"},layerclose:{description:"关闭图层属性管理器"},layerp:{description:"撤销对图层设置的最后一次更改或一组更改"},layfrz:{description:"冻结所选对象所在的图层",prompt:"选择要冻结其图层的对象"},layiso:{description:"隔离所选对象所在的图层",prompt:"选择要隔离其图层的对象"},laylck:{description:"锁定所选对象所在的图层",prompt:"选择要锁定其图层的对象"},layoff:{description:"关闭所选对象所在的图层",prompt:"选择要关闭其图层的对象"},layon:{description:"打开图纸中的所有图层"},laythw:{description:"解冻图纸中的所有冻结图层"},layulk:{description:"解锁所选对象所在的图层",prompt:"选择要解锁其图层的对象"},layuniso:{description:"恢复由 LAYISO 隐藏或锁定的图层"},line:{description:"在指定点之间绘制直线段"},log:{description:"在控制台输出调试信息"},ltscale:{description:"设置图形的全局线型比例系数"},lunits:{description:"设置坐标和距离的显示格式"},luprec:{description:"设置线性单位的显示精度(小数位数),与 LUNITS 配合使用"},lwdisplay:{description:"用于控制是否在图纸中显示线宽效果"},clearmeasurements:{description:"清除当前布局上的所有测量标注"},measurementvis:{description:"显示或隐藏当前布局上的测量标注"},measurementexport:{description:"将测量标注导出为 sidecar JSON 文件"},measurementimport:{description:"从 sidecar JSON 文件导入测量标注"},measurearea:{description:"计算所选对象或点定义区域的面积和周长"},measureangle:{description:"测量两条线或三个点之间的夹角"},measurearc:{description:"测量圆弧段的弧长"},measuredistance:{description:"测量两点之间的距离及坐标增量"},measurepoint:{description:"测量拾取点的 X/Y 坐标"},measurement:{description:"设置图形使用英制或公制单位"},measurementcolor:{description:"设置测量标注覆盖图形使用的颜色"},modelbkcolor:{description:"设置模型空间绘图区域的背景颜色"},mline:{description:"创建由多条平行线组成的多线对象"},move:{description:"通过位移向量移动所选图元",prompt:"选择对象"},offset:{description:"按指定距离创建平行曲线、多段线或圆"},mtext:{description:"创建多行文本"},open:{description:"打开图纸"},openprof:{description:"控制是否在控制台记录文件打开阶段的耗时分析"},openperf:{description:"打开“打开性能”面板,显示最近一次打开图纸的关键耗时"},orthomode:{description:"将光标移动限制为水平或垂直方向"},osmode:{description:"使用位码设置运行中的对象捕捉模式"},pan:{description:"平移视图"},paperbkcolor:{description:"设置图纸空间(布局)绘图区域的背景颜色"},pdmode:{description:"控制点对象的显示样式"},pdsize:{description:"设置点对象的显示大小"},pickbox:{description:"控制用于选择对象的拾取框大小(像素)"},pline:{description:"通过指定多个点创建多段线"},pngout:{description:"导出为 PNG 图片"},point:{description:"连续创建点"},polaraddang:{description:"以分号分隔的列表存储附加极轴追踪角度"},polarang:{description:"设置极轴追踪的极轴角增量"},polarmode:{description:"控制极轴追踪和对象捕捉追踪设置"},polygon:{description:"通过中心和半径或指定一条边创建正多边形"},qnew:{description:"创建新图纸"},ray:{description:"创建从起点向单一方向无限延伸的射线"},rectang:{description:"通过指定两个对角点创建矩形"},regen:{description:"重绘图纸"},revcloud:{description:"创建或修改修订云线"},markuptext:{description:"放置文字批注"},markupline:{description:"创建直线批注"},markuparrow:{description:"创建箭头批注"},markupcloud:{description:"创建修订云线批注"},markuprect:{description:"创建矩形批注"},markupcircle:{description:"创建圆形批注"},markuphighlight:{description:"创建高亮矩形批注"},markupcallout:{description:"创建标注:先指定引线尖端,再放置文字框,最后输入文字"},markupstamp:{description:"放置图章或自定义符号"},markupvis:{description:"显示或隐藏批注"},clearmarkups:{description:"清除当前布局上的所有批注"},markupexport:{description:"将批注导出为 sidecar JSON 文件"},markupimport:{description:"从 sidecar JSON 文件导入批注"},markuppanel:{description:"打开批注面板"},rotate:{description:"绕基点旋转所选图元",prompt:"选择对象"},select:{description:"选择图元"},shortcutmenu:{description:"控制图形区域中快捷菜单的可用性"},sketch:{description:"创建一系列徒手线段"},spline:{description:"通过指定控制点创建平滑的样条曲线"},textstyle:{description:"设置当前文字样式的名称"},unitmode:{description:"当 LUNITS 为建筑或分数格式时,控制坐标的分数显示格式"},switchbg:{description:"切换绘图区域背景颜色,在白色和黑色背景之间切换"},unisolateobjects:{description:"重新显示 HIDEOBJECTS 隐藏的所有对象"},undo:{description:"撤销上一次数据库编辑操作",nothingToUndo:"没有可撤销的操作。"},redo:{description:"重做上一次撤销的操作",nothingToRedo:"没有可重做的操作。"},xline:{description:"创建在两个方向上无限延伸的构造线"},zoom:{description:"缩放以显示所有对象"}},USER:{}},iy={arc:{startPointOrCenter:"指定圆弧的起点或",secondPointOrOptions:"指定圆弧上的第二点或",secondPoint:"指定圆弧上的第二点",startPoint:"指定圆弧的起点",centerPoint:"指定圆弧的圆心",endPoint:"指定圆弧的端点",endPointOrOptions:"指定圆弧的端点或",centerPointOrOptions:"指定圆弧的圆心或",includedAngle:"指定圆弧的夹角",chordLength:"指定圆弧的弦长",tangentDirection:"指定圆弧起点的切线方向",radius:"指定圆弧的半径",keywords:{center:{display:"圆心(C)",local:"圆心",global:"Center"},end:{display:"端点(E)",local:"端点",global:"End"},angle:{display:"角度(A)",local:"角度",global:"Angle"},chordLength:{display:"弦长(L)",local:"弦长",global:"ChordLength"},direction:{display:"方向(D)",local:"方向",global:"Direction"},radius:{display:"半径(R)",local:"半径",global:"Radius"}},invalid:{threePoint:"三点圆弧无效:三点共线或无法确定圆弧。",center:"圆心输入无效:起点与终点必须在同一圆上。",angle:"角度输入无效:夹角必须大于 0 且小于 360 度。",chordLength:"弦长输入无效:该值超出当前半径可用范围。",direction:"方向输入无效:无法根据该切线方向构造圆弧。",radius:"半径输入无效:指定半径无法连接起点与终点。"}},circle:{center:"指定圆的圆心",centerOrOptions:"指定圆的圆心或",radius:"指定圆的半径",radiusOrDiameter:"指定圆的半径或",diameter:"指定圆的直径",twoPointFirst:"指定圆直径的第一个端点",twoPointSecond:"指定圆直径的第二个端点",threePointFirst:"指定圆上的第一个点",threePointSecond:"指定圆上的第二个点",threePointThird:"指定圆上的第三个点",keywords:{threeP:{display:"三点(3P)",local:"三点",global:"3P"},twoP:{display:"两点(2P)",local:"两点",global:"2P"},diameter:{display:"直径(D)",local:"直径",global:"Diameter"}}},copy:{basePointOrOptions:"指定基点或",displacementOrArray:"指定位移或",secondPointOrArray:"指定第二个点或",modePrompt:"输入复制模式选项",arrayItemCount:"输入阵列中的项目数(包括原对象)",arraySecondPointOrFit:"指定第二个点或",arrayFitSecondPoint:"指定第二个点",keywords:{displacement:{display:"位移(D)",local:"位移",global:"Displacement"},mode:{display:"模式(O)",local:"模式",global:"Mode"},multiple:{display:"多个(M)",local:"多个",global:"Multiple"},single:{display:"单个(S)",local:"单个",global:"Single"},array:{display:"阵列(A)",local:"阵列",global:"Array"},fit:{display:"布满(F)",local:"布满",global:"Fit"}}},dimlinear:{xLine1Point:"指定第一条尺寸界限原点",xLine2Point:"指定第二条尺寸界限原点",dimLinePoint:"指定尺寸线位置"},ellipse:{axisEndpointOrOptions:"指定椭圆的轴端点或",arcAxisEndpointOrCenter:"指定椭圆弧的轴端点或",center:"指定椭圆中心点",firstAxisEndpoint:"指定轴的端点",secondAxisEndpoint:"指定轴的另一个端点",otherAxisOrRotation:"指定到另一轴的距离或",rotationAngle:"指定绕长轴的旋转角度",arcStartAngle:"指定椭圆弧起始角",arcEndAngle:"指定椭圆弧终止角",keywords:{arc:{display:"圆弧(A)",local:"圆弧",global:"Arc"},center:{display:"中心点(C)",local:"中心点",global:"Center"},rotation:{display:"旋转(R)",local:"旋转",global:"Rotation"}},invalid:{axis:"轴输入无效:轴长必须大于 0。",otherAxis:"另一轴输入无效:距离必须大于 0。",rotation:"旋转输入无效:计算得到的短轴必须大于 0。"}},hatch:{prompt:"选择边界对象或",pickPoint:"指定内部点(或按 Enter 结束)",select:"选择要填充的对象",patternName:"输入填充图案名称",scale:"指定填充图案比例",angle:"指定填充图案角度",style:"输入填充样式",associative:"指定关联性",invalidBoundary:"所选对象无法构成闭合边界。",keywords:{pick:{display:"拾取点(P)",local:"拾取点",global:"PickPoints"},select:{display:"选择对象(S)",local:"选择对象",global:"SelectObjects"},cancel:{display:"放弃(C)",local:"放弃",global:"Cancel"},pattern:{display:"图案(P)",local:"图案",global:"Pattern"},scale:{display:"比例(S)",local:"比例",global:"Scale"},angle:{display:"角度(A)",local:"角度",global:"Angle"},style:{display:"样式(T)",local:"样式",global:"HatchStyle"},associative:{display:"关联(AS)",local:"关联",global:"AssociativeMode"},normal:{display:"普通(N)",local:"普通",global:"Normal"},outer:{display:"外部(O)",local:"外部",global:"Outer"},ignore:{display:"忽略(I)",local:"忽略",global:"Ignore"},yes:{display:"是(Y)",local:"是",global:"Yes"},no:{display:"否(N)",local:"否",global:"No"}}},hideobjects:{hidden:"个对象已隐藏",restored:"个对象已恢复显示",nothingToRestore:"没有可恢复显示的对象"},entout:{longSidePrompt:"输入预览图长边像素尺寸",exported:"个对象预览已导出",skipped:"个对象已跳过",failed:{"no-preview-root":"无法为所选对象构建预览几何","no-bounds":"无法计算所选对象的预览范围","capture-failed":"无法渲染实体预览图","download-failed":"预览已渲染,但 PNG 下载失败"}},layer:{main:"输入选项",listSummary:"图层列表已输出到浏览器控制台",emptyInput:"未输入图层名。",newPrompt:"输入新建图层名称(可用逗号分隔多个)",makePrompt:"输入要创建并设为当前的图层名",setPrompt:"输入要设为当前的图层名",onPrompt:"输入要打开的图层名",offPrompt:"输入要关闭的图层名",freezePrompt:"输入要冻结的图层名",thawPrompt:"输入要解冻的图层名",lockPrompt:"输入要锁定的图层名",unlockPrompt:"输入要解锁的图层名",colorLayerPrompt:"输入要修改颜色的图层名",colorValuePrompt:"输入颜色(ACI 1-255、RGB 如 255,0,0 或颜色名)",invalidColor:"颜色输入无效。",descriptionLayerPrompt:"输入要修改说明的图层名",descriptionValuePrompt:"输入新的图层说明",created:"已创建图层数量",alreadyExists:"图层已存在",notFound:"未找到图层",cannotChangeCurrent:"不能关闭或冻结当前图层。",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"创建并置为当前(M)",local:"创建并置为当前",global:"Make"},set:{display:"置为当前(S)",local:"置为当前",global:"Set"},new:{display:"新建(N)",local:"新建",global:"New"},on:{display:"打开(ON)",local:"打开",global:"On"},off:{display:"关闭(OF)",local:"关闭",global:"Off"},color:{display:"颜色(C)",local:"颜色",global:"Color"},freeze:{display:"冻结(F)",local:"冻结",global:"Freeze"},thaw:{display:"解冻(T)",local:"解冻",global:"Thaw"},lock:{display:"锁定(L)",local:"锁定",global:"Lock"},unlock:{display:"解锁(U)",local:"解锁",global:"Unlock"},description:{display:"说明(D)",local:"说明",global:"Description"}}},layon:{alreadyOn:"所有图层都已经打开。",turnedOn:"已打开图层数量"},laycur:{prompt:"选择要更改到当前图层的对象",currentLayerNotFound:"未找到当前图层。",noObjects:"没有选择有效对象。",alreadyCurrent:"所选对象已位于当前图层。",changed:"已将对象更改到当前图层"},layfrz:{prompt:"选择要冻结其图层的对象或",invalidSelection:"所选对象无效。",settingsPrompt:"输入要修改的 LAYFRZ 设置",viewportPrompt:"指定视口冻结行为",blockSelectionPrompt:"指定嵌套块选择行为",vpfreezeFallback:"当前 viewer 不支持按视口冻结图层,已退化为普通 Freeze 行为。",nestedSelectionLimited:"嵌套块选择设置会被保存,但当前拾取仍只能解析顶层对象所在图层。",layerNotFound:"未找到图层",cannotFreezeCurrent:"不能冻结当前图层。",alreadyFrozen:"图层已处于冻结状态",frozen:"已冻结图层",restored:"已恢复图层",nothingToUndo:"当前没有可撤销的 LAYFRZ 操作。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},viewports:{display:"视口(V)",local:"视口",global:"Viewports"},blockSelection:{display:"块选择(B)",local:"块选择",global:"BlockSelection"},freeze:{display:"冻结(F)",local:"冻结",global:"Freeze"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"},block:{display:"块(B)",local:"块",global:"Block"},entity:{display:"对象(E)",local:"对象",global:"Entity"},none:{display:"无(N)",local:"无",global:"None"}}},layiso:{prompt:"选择要隔离其图层的对象或",settingsPrompt:"输入未隔离图层的处理设置",offModePrompt:"输入未隔离图层的关闭行为",noLayers:"未选择有效图层。",layerNotFound:"未找到图层",isolated:"已隔离图层",affectedLayers:"受影响图层数",vpfreezeFallback:"当前 viewer 不支持按视口冻结图层,已退化为普通 Off 行为。",lockFadeFallback:"当前 viewer 不支持图层淡显显示,未隔离图层将仅被锁定。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},off:{display:"关闭(O)",local:"关闭",global:"Off"},lockAndFade:{display:"锁定并淡显(L)",local:"锁定并淡显",global:"LockAndFade"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"}}},laythw:{alreadyThawed:"所有图层都已经解冻。",thawed:"已解冻图层数量"},layuniso:{noPrevious:"没有可恢复的上一次 LAYISO 图层状态。",layerNotFound:"未找到图层",nothingRestored:"没有恢复任何 LAYISO 图层改动。",restored:"已恢复图层数量"},laylck:{prompt:"选择要锁定其图层的对象",invalidSelection:"所选对象无效。",layerNotFound:"未找到图层",alreadyLocked:"图层已处于锁定状态",locked:"已锁定图层"},layulk:{prompt:"选择要解锁其图层的对象",invalidSelection:"所选对象无效。",layerNotFound:"未找到图层",alreadyUnlocked:"图层已处于解锁状态",unlocked:"已解锁图层"},layoff:{prompt:"选择要关闭其图层的对象或",invalidSelection:"所选对象无效。",settingsPrompt:"输入要修改的 LAYOFF 设置",viewportPrompt:"指定视口行为",blockSelectionPrompt:"指定嵌套块选择行为",vpfreezeFallback:"当前 viewer 不支持按视口关闭图层,已退化为普通 Off 行为。",nestedSelectionLimited:"嵌套块选择设置会被保存,但当前拾取仍只能解析顶层对象所在图层。",layerNotFound:"未找到图层",cannotTurnOffCurrent:"不能关闭当前图层。",alreadyOff:"图层已处于关闭状态",turnedOff:"已关闭图层",restored:"已恢复图层",nothingToUndo:"当前没有可撤销的 LAYOFF 操作。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},viewports:{display:"视口(V)",local:"视口",global:"Viewports"},blockSelection:{display:"块选择(B)",local:"块选择",global:"BlockSelection"},off:{display:"关闭(O)",local:"关闭",global:"Off"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"},block:{display:"块(B)",local:"块",global:"Block"},entity:{display:"对象(E)",local:"对象",global:"Entity"},none:{display:"无(N)",local:"无",global:"None"}}},layerp:{restored:"恢复了之前的图层状态。",noPreviousState:"没有可恢复的先前图层状态。"},line:{firstPoint:"指定第一个点",firstPointOrContinue:"请指定第一个点或",nextPoint:"指定下一个点",nextPointWithOptions:"请指定下一个点或",keywords:{continue:{display:"继续(C)",local:"继续",global:"Continue"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"}}},xline:{firstPointOrOptions:"指定点或",secondPoint:"指定第二个点",throughPoint:"指定穿过点",angle:"输入构造线角度",invalidDirection:"XLINE 的方向无效。",keywords:{hor:{display:"水平(H)",local:"水平",global:"Hor"},ver:{display:"垂直(V)",local:"垂直",global:"Ver"},ang:{display:"角度(A)",local:"角度",global:"Ang"}}},ray:{startPoint:"指定起点",throughPoint:"指定通过点"},mline:{startPointWithOptions:"指定起点或",nextPointWithOptions:"指定下一点或",justificationPrompt:"输入对正方式",scalePrompt:"指定多线比例",stylePrompt:"输入多线样式名或 [?] 列出样式",styleNotFound:"未找到多线样式",styleListHeader:"已加载的多线样式",styleListEmpty:"当前图纸没有已加载的多线样式。",keywords:{justification:{display:"对正(J)",local:"对正",global:"Justification"},scale:{display:"比例(S)",local:"比例",global:"Scale"},style:{display:"样式(ST)",local:"样式",global:"Style"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},top:{display:"上(T)",local:"上",global:"Top"},zero:{display:"零(Z)",local:"零",global:"Zero"},bottom:{display:"下(B)",local:"下",global:"Bottom"}}},measureArc:{startPoint:"指定弧的起点",throughPoint:"指定弧上的一个点",endPoint:"指定弧的终点",lockedEndPoint:"指定弧的终点(按 Ctrl 在大弧与小弧之间切换)",invalidPoints:"三点共线,无法测量弧长。"},measureAngle:{vertex:"指定顶点",arm1:"指定第一条边上的点",arm2:"指定第二条边上的点"},measureArea:{firstPoint:"指定第一个点",nextPoint:"指定下一个点(或按 Enter 完成)"},measureDistance:{firstPoint:"指定第一个点",secondPoint:"指定第二个点"},measurePoint:{point:"指定点"},measurement:{import:{chooseFile:"选择测量 sidecar JSON 文件"}},markup:{author:"指定批注作者(将保存供以后使用)",text:{point:"指定文字批注点",content:"输入批注文字"},line:{firstPoint:"指定直线批注的第一点",secondPoint:"指定直线批注的第二点"},arrow:{firstPoint:"指定箭头起点",secondPoint:"指定箭头尖端"},cloud:{firstCorner:"指定云线的第一个角点",secondCorner:"指定云线的对角点"},rect:{firstCorner:"指定矩形的第一个角点",secondCorner:"指定矩形的对角点"},circle:{center:"指定圆心",radius:"指定圆的半径"},shape:{calloutOn:"[标注开启]",calloutOff:"[标注关闭]",calloutAnchor:"指定标注文字框位置",keywords:{callout:{display:"标注(C)",local:"标注",global:"Callout"},noCallout:{display:"无标注(N)",local:"无标注",global:"NoCallout"}}},highlight:{firstCorner:"指定高亮的第一个角点",secondCorner:"指定高亮的对角点"},callout:{tip:"指定引线尖端(箭头端)",anchor:"指定标注文字框位置",content:"输入标注文字"},stamp:{kind:"输入图章类型 [approved/rejected/revised/for-review/custom]",imageUrl:"输入自定义图章图片 URL(可选)",caption:"输入图章说明文字(可选)",point:"指定图章插入点"},import:{chooseFile:"选择批注 sidecar JSON 文件"}},move:{basePointOrDisplacement:"指定基点或",secondPointOrDisplacement:"指定第二个点或",displacement:"指定位移",keywords:{displacement:{display:"位移(D)",local:"位移",global:"Displacement"}}},offset:{distance:"指定偏移距离",selectObject:"选择要偏移的对象,或按 Enter 结束",sidePoint:"指定要偏移到的那一侧的点",invalidDistance:"偏移距离必须大于 0。",invalidSelection:"所选对象不能偏移。",offsetFailed:"无法在指定侧创建偏移曲线。"},mtext:{point:"指定多行文本插入点"},pngout:{boundsFirstCorner:"指定边界的第一个角点",boundsSecondCorner:"指定对角点",longSidePrompt:"输入长边像素大小"},imageattach:{insertionPoint:"指定插入点:",scale:"指定比例因子:",rotation:"指定旋转角度:",invalidScale:"比例因子必须大于 0。",decodeFailed:"无法读取所选图像文件。"},insert:{blockName:"输入块名:",insertionPoint:"指定插入点:",scale:"指定比例因子:",rotation:"指定旋转角度:",invalidScale:"比例因子必须大于 0。",invalidBlockName:"无效的块名。",blockNotFound:"未找到块",xrefNotAllowed:"不能使用 -INSERT 插入外部参照。"},xattach:{insertionPoint:"指定插入点:",scale:"指定比例因子:",rotation:"指定旋转角度:",invalidScale:"比例因子必须大于 0。",unsupportedFile:"请选择 DWG 或 DXF 文件。",loading:"正在加载外部参照...",loadFailed:"无法读取所选图形文件。"},point:{point:"指定点"},polygon:{numberOfSides:"输入边数",centerOrEdge:"指定多边形中心点或",radiusOrType:"输入选项",edgeStart:"指定边的第一个端点",edgeEnd:"指定边的第二个端点",keywords:{edge:{display:"边(E)",local:"边",global:"Edge"},inscribed:{display:"内接于圆(I)",local:"内接于圆",global:"Inscribed"},circumscribed:{display:"外切于圆(C)",local:"外切于圆",global:"Circumscribed"}},invalid:{sides:"边数无效:请输入 3 到 1024 之间的整数。",radius:"半径无效:半径必须大于 0。",edge:"边无效:边长必须大于 0。"}},polyline:{firstPoint:"指定第一个点",nextPoint:"指定下一个点(或按 Enter 完成)",nextPointWithOptions:"请指定下一个点或",nextPointWithArcOptions:"请指定下一个点或",keywords:{arc:{display:"圆弧(A)",local:"圆弧",global:"Arc"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},line:{display:"直线(L)",local:"直线",global:"Line"},angle:{display:"角度(A)",local:"角度",global:"Angle"},center:{display:"圆心(C)",local:"圆心",global:"Center"},secondPoint:{display:"第二点(P)",local:"第二点",global:"SecondPoint"},radius:{display:"半径(R)",local:"半径",global:"Radius"}},arcAngle:"指定弧角度",arcCenter:"指定圆心",arcSecondPoint:"指定弧上的第二点",arcEndPoint:"指定弧的终点",arcRadius:"指定弧半径"},rotate:{basePoint:"指定基点",rotationAngleOrOptions:"指定旋转角度或",referenceAngleOrPoints:"指定参考角或",firstReferencePoint:"指定参考角的第一点",secondReferencePoint:"指定第二点",newAngle:"指定新角度",keywords:{copy:{display:"复制(C)",local:"复制",global:"Copy"},reference:{display:"参照(R)",local:"参照",global:"Reference"},points:{display:"点(P)",local:"点",global:"Points"}},invalid:{referencePoints:"参考点输入无效:两点必须不同。"}},rect:{firstPoint:"指定第一个角点",nextPoint:"指定另一个角点",firstPointWithOptions:"指定第一个角点或者",otherCornerWithOptions:"指定另一个角点或者",chamferFirst:"指定第一个倒角距离",chamferSecond:"指定第二个倒角距离",filletRadius:"指定圆角半径",segmentWidth:"指定矩形线宽",elevationValue:"指定标高",thicknessValue:"指定厚度",rotationAngle:"指定矩形旋转角度",dimensionLength:"指定矩形长度",dimensionWidth:"指定矩形宽度",areaValue:"指定矩形面积",areaLengthOrWidth:"指定矩形长度",areaSpecifyWidth:"指定矩形宽度",invalidPositive:"输入无效:请输入大于 0 的数值。",invalidRect:"无法创建矩形:请输入有效的角点或尺寸。",thicknessNotSupported:"当前版本暂不支持将矩形厚度写入图元,已忽略厚度设置。",keywords:{chamfer:{display:"倒角(C)",local:"倒角",global:"Chamfer"},elevation:{display:"标高(E)",local:"标高",global:"Elevation"},fillet:{display:"圆角(F)",local:"圆角",global:"Fillet"},thickness:{display:"厚度(T)",local:"厚度",global:"Thickness"},width:{display:"宽度(W)",local:"宽度",global:"Width"},area:{display:"面积(A)",local:"面积",global:"Area"},dimensions:{display:"尺寸(D)",local:"尺寸",global:"Dimensions"},rotation:{display:"旋转(R)",local:"旋转",global:"Rotation"},length:{display:"长度(L)",local:"长度",global:"Length"},rectWidth:{display:"宽度(W)",local:"宽度",global:"Width"}}},revcloud:{firstCornerOrOptions:"指定第一个角点或",firstCorner:"指定第一个角点",oppositeCorner:"指定对角点",startPoint:"指定起点",nextPoint:"指定下一点",nextPointOrUndo:"指定下一点或",firstPoint:"指定第一个点",guideCursor:"沿云线路径移动光标(按 Enter 结束)",arcLength:"指定圆弧长度",selectObject:"选择对象",style:"输入修订云线圆弧样式",reverseDirection:"反转方向",invalidArcLength:"圆弧长度必须大于 0。",invalidObject:"所选对象无法转换为修订云线。",keywords:{arcLength:{display:"圆弧长度(A)",local:"圆弧长度",global:"ArcLength"},object:{display:"对象(O)",local:"对象",global:"Object"},rectangular:{display:"矩形(R)",local:"矩形",global:"Rectangular"},polygonal:{display:"多边形(P)",local:"多边形",global:"Polygonal"},freehand:{display:"手绘(F)",local:"手绘",global:"Freehand"},style:{display:"样式(S)",local:"样式",global:"Style"},normal:{display:"普通(N)",local:"普通",global:"Normal"},calligraphy:{display:"书法(C)",local:"书法",global:"Calligraphy"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},yes:{display:"是(Y)",local:"是",global:"Yes"},no:{display:"否(N)",local:"否",global:"No"}}},sketch:{specifySketch:"指定草图或",sketching:"移动指针进行草图绘制(单击或按 Enter 停止)",type:"输入草图类型",increment:"指定草图增量",tolerance:"指定样条曲线公差",firstPoint:"指定第一个点",nextPoint:"指定结束点",keywords:{type:{display:"类型(T)",local:"类型",global:"Type"},increment:{display:"增量(I)",local:"增量",global:"Increment"},tolerance:{display:"公差(L)",local:"公差",global:"Tolerance"},line:{display:"直线(L)",local:"直线",global:"Lines"},polyline:{display:"多段线(P)",local:"多段线",global:"Polyline"},spline:{display:"样条曲线(S)",local:"样条曲线",global:"Spline"}}},spline:{firstPoint:"指定第一个点",nextPoint:"指定下一个点(或按 Enter 完成)",firstPointWithOptions:"指定第一个点或",nextPointWithFitOptions:"指定下一个点或",nextPointWithCvOptions:"指定下一个控制顶点或",methodPrompt:"输入样条创建方式",knotsPrompt:"输入节点参数化方式",degreePrompt:"指定样条次数",keywords:{method:{display:"方法(M)",local:"方法",global:"Method"},fit:{display:"拟合(F)",local:"拟合",global:"Fit"},cv:{display:"控制顶点(C)",local:"控制顶点",global:"CV"},knots:{display:"节点(K)",local:"节点",global:"Knots"},degree:{display:"次数(D)",local:"次数",global:"Degree"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},chord:{display:"弦长(C)",local:"弦长",global:"Chord"},sqrtChord:{display:"平方根弦长(S)",local:"平方根弦长",global:"SqrtChord"},uniform:{display:"均匀(U)",local:"均匀",global:"Uniform"}}},sysvar:{prompt:"请输入新的值"},zoom:{mainPrompt:"指定窗口角点或",firstCorner:"指定第一个角点",secondCorner:"指定对角点",centerPoint:"指定缩放中心点",heightOrScale:"输入高度或比例因子(nX 或 nXP)",scaleFactor:"输入比例因子(nX 或 nXP)",keywords:{all:{display:"全部(A)",local:"全部",global:"All"},center:{display:"中心(C)",local:"中心",global:"Center"},extents:{display:"范围(E)",local:"范围",global:"Extents"},previous:{display:"上一个(P)",local:"上一个",global:"Previous"},scale:{display:"比例(S)",local:"比例",global:"Scale"},window:{display:"窗口(W)",local:"窗口",global:"Window"}}},chtml:{exportInvisibleLayers:"是否导出不可见图层",exportLayouts:"是否导出布局",initialView:"打开 HTML 时的初始视图",viewerMode:"离线查看器模式",keywords:{yes:{display:"是(Y)",local:"是",global:"Yes"},no:{display:"否(N)",local:"否",global:"No"},extents:{display:"范围(E)",local:"范围",global:"Extents"},current:{display:"当前(C)",local:"当前",global:"Current"},view:{display:"查看(V)",local:"查看",global:"View"},measure:{display:"测量与批注(M)",local:"测量与批注",global:"Measure"}}}},ny={document:{untitled:"未命名"},commandLine:{noLast:"(无上一次命令)",unknownCommand:"未知命令",executed:"已执行命令",showHistory:"显示命令历史",placeholder:"输入命令",showMessages:"显示消息历史",canceled:"*已取消*",noHistory:"(无历史记录)",invalidInput:"输入无效。",close:"关闭命令行"},inputManager:{firstCorner:"指定第一个角点或",secondCorner:"指定第二个角点或"},message:{fetchingDrawingFile:"正在加载图纸文件...",exportingDxf:"正在导出 DXF ...",exportingEntityPreview:"正在导出图片 ...",collectingMemoryProfile:"正在分析内存 ...",fontCached:"字体已成功缓存",fontCacheFailed:"缓存字体失败"},progress:{start:"开始解析文件...",parse:"正在解析文件 ...",font:"正在下载图纸所需字体...",ltype:"正在解析线形...",style:"正在解析文字样式...",dimstyle:"正在解析标注样式...",layer:"正在解析图层...",vport:"正在解析视口...",blockrecord:"正在解析BTRs...",header:"正在解析文件头...",block:"正在解析块..",entity:"正在解析图元...",object:"正在解析NODs...",rendering:"正在渲染图纸 ...",end:"完成!"},about:{title:"关于",close:"关闭",product:"CAD 查看器",tagline:"面向 DWG/DXF 图纸的高性能 Web CAD 查看器。",website:"官网",docs:"文档",repository:"GitHub",copyright:"© {year} mlightcad。保留所有权利。",ok:"确定"},drawStyle:{color:"颜色",lineWeight:"线宽",fontSize:"字号"}};u.mergeLocaleMessage("en",{command:Zm,jig:Xm,main:qm}),u.mergeLocaleMessage("zh",{command:ty,jig:iy,main:ny}),u.mergeLocaleMessage("tr",{command:Jm,jig:Qm,main:ey}),u.mergeLocaleMessage("cs",{command:Wm,jig:$m,main:Ym});const Lr=(s,e)=>{const t=`command.${s}.${e}`;return u.t(t)},sy=s=>Lr(de.SYSTEMT_COMMAND_GROUP_NAME,s),ry=s=>Lr(de.DEFAUT_COMMAND_GROUP_NAME,s);class Tr{constructor(e){this.options=e}parse(e){const t=e.trim();if(t.length===0)return this.options.allowNone,null;const i=this.options.keywords.findByName(t);return i?i.globalName:this.options.allowArbitraryInput?t:null}parseCommandLine(e,t){return this.parse(e)}}class Hl{start(){return new Promise(e=>{this.resolve=e,this.onStart()})}finish(e){this.cleanup(),this.resolve(e)}}class oy extends Hl{constructor(e,t,i=!0){super(),this.cli=e,this.options=t,this.allowTyping=i,this.handler=new Tr(t)}onStart(){this.cli.clearInput(),this.cli.setInputReadOnly(!this.allowTyping),this.cli.renderKeywordPrompt(this.options,e=>this.finish(e)),this.cli.focusInput()}handleEnter(e){if(!this.allowTyping)return!0;if(!e.trim()){const i=this.options.keywords.default;return i!=null&&i.enabled?(this.finish(i.globalName),!0):this.options.allowNone?(this.finish(""),!0):!1}const t=this.handler.parse(e);return t!==null?(this.finish(t),!0):!1}handleEscape(){this.finish("")}cleanup(){this.cli.setInputReadOnly(!1),this.cli.clear()}}class ay extends Hl{constructor(e,t,i,n,r,o=!0){super(),this.cli=e,this.options=t,this.parseValue=i,this.mode=n,this.allowNone=r,this.allowTyping=o,this.options.keywords.count>0&&(this.keywordHandler=new Tr(this.options))}onStart(){this.cli.clearInput(),this.cli.setInputReadOnly(!this.allowTyping),this.cli.renderKeywordPrompt(this.options,e=>this.finish({kind:"keyword",keyword:e})),this.cli.focusInput()}handleEnter(e){if(!this.allowTyping)return!0;if(!e.trim()){const i=this.options.keywords.default;return i!=null&&i.enabled?(this.finish({kind:"keyword",keyword:i.globalName}),!0):this.allowNone?(this.finish({kind:"none"}),!0):!1}if(this.mode==="keyword")return this.tryResolveKeyword(e);if(this.mode==="string"){if(this.tryResolveKeyword(e))return!0;const i=this.parseValue(e);return i!==null?(this.finish({kind:"value",value:i}),!0):!1}const t=this.parseValue(e);return t!==null?(this.finish({kind:"value",value:t}),!0):this.tryResolveKeyword(e)}handleEscape(){this.finish({kind:"none"})}cleanup(){this.cli.setInputReadOnly(!1),this.cli.clear()}tryResolveKeyword(e){if(!this.keywordHandler)return!1;const t=this.keywordHandler.parse(e);return t===null?!1:(this.finish({kind:"keyword",keyword:t}),!0)}}class Wl{constructor(e=document.body){this.isPromptActive=!1,this.recentMessages=[],this.isCommandLifecycleBound=!1,this.container=e,this.history=[],this.historyIndex=-1,this.lastExecuted=null,this.isCmdPopupOpen=!1,this.isMsgPanelOpen=!1,this.minWidth=420,this.widthRatio=.66,this.autoCompleteIndex=-1,this.injectCSS(),this.createUI(),this.bindEvents(),this.bindCommandLifecycleEvents(),this.resizeHandler(),window.addEventListener("resize",()=>this.resizeHandler()),this.resizeObserver=new ResizeObserver(()=>this.resizeHandler()),this.resizeObserver.observe(this.container),u.events.localeChanged.addEventListener(()=>this.refreshLocale())}get visible(){return this.cliContainer.style.display!=="none"}set visible(e){this.cliContainer.style.display=e?"block":"none"}setPrompt(e){this.isPromptActive=!0;const t=(e==null?void 0:e.trim().replace(/[::]\s*$/,""))??"";this.promptEl.innerHTML=t?`${t}: `:"",this.textInput.placeholder="",this.recordRecentMessage(t?`${t}:`:e)}clear(){this.clearPrompt(),this.clearInput()}clearPrompt(){this.promptEl.innerHTML="",this.isPromptActive=!1}clearInput(){this.textInput.value="",this.textInput.placeholder=this.isPromptActive?"":this.localize("main.commandLine.placeholder")}focusInput(){this.textInput.focus()}setInputReadOnly(e){this.textInput.readOnly=e}showMessage(e,t="info",i){this.appendMessage(e,t,i)}cancelActiveSession(){this.activeSession&&(this.activeSession.handleEscape(),this.activeSession=void 0)}async getKeywords(e,t=!0){const i=new oy(this,e,t);this.activeSession=i;try{return await i.start()}finally{this.activeSession=void 0}}async getPromptInput(e,t,i){const n=new ay(this,e,t,i.mode,i.allowNone,i.allowTyping??!0);this.activeSession=n;try{return await n.start()}finally{this.activeSession=void 0}}localize(e,t){return u.t(e,{fallback:t})}refreshLocale(){Array.from(this.msgPanel.children).forEach(e=>{var n,r,o,a;const t=e,i=t.dataset.msgKey;if(i)if(i==="main.commandLine.executed"){const l=((r=(n=t.textContent)==null?void 0:n.split(":")[1])==null?void 0:r.trim())??"";t.textContent=`${this.localize(i)}: ${l}`}else if(i==="main.commandLine.unknownCommand"){const l=((a=(o=t.textContent)==null?void 0:o.split(":")[1])==null?void 0:a.trim())??"";t.textContent=`${this.localize(i)}: ${l}`}else t.textContent=this.localize(i)}),this.centerEl.setAttribute("data-placeholder",this.localize("main.commandLine.placeholder")),!this.isPromptActive&&!this.textInput.value&&(this.textInput.placeholder=this.localize("main.commandLine.placeholder")),this.downBtn.title=this.localize("main.commandLine.showHistory"),this.upBtn.title=this.localize("main.commandLine.showMessages")}executeCommand(e){if(!e||!e.trim())if(this.lastExecuted)e=this.lastExecuted;else{this.showMessage(this.localize("main.commandLine.noLast","(no last command)"));return}const t=this.resolveCommand(e);if(!t){const n=this.localize("main.commandLine.unknownCommand");this.showMessage(`${n}: ${e}`,"warning");return}this.history.push(t.globalName),this.historyIndex=this.history.length,this.lastExecuted=t.globalName,this.printHistoryLine(e);const i=this.localize("main.commandLine.executed");this.showMessage(`${i}: ${t.localName}`),k.instance.sendStringToExecute(e),this.clearInput()}injectCSS(){const e=document.createElement("style");e.textContent=`
214
264
  .ml-cli-container {
215
265
  position: fixed;
216
266
  bottom: 10px;
@@ -471,7 +521,7 @@
471
521
  background: var(--ml-ui-border, rgba(255, 255, 255, 0.2));
472
522
  border-radius: 6px;
473
523
  }
474
- `,document.head.appendChild(e)}createUI(){this.cliContainer=document.createElement("div"),this.cliContainer.className="ml-cli-container",this.cliContainer.style.position=this.useViewportPositioning()?"fixed":"absolute",this.useViewportPositioning()||getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.wrapper=document.createElement("div"),this.wrapper.className="ml-cli-wrapper",this.cliContainer.appendChild(this.wrapper),this.recentPanel=document.createElement("div"),this.recentPanel.className="ml-cli-recent",this.wrapper.appendChild(this.recentPanel),this.bar=document.createElement("div"),this.bar.className="ml-cli-bar",this.wrapper.appendChild(this.bar),this.leftGroup=document.createElement("div"),this.leftGroup.className="ml-cli-left",this.bar.appendChild(this.leftGroup),this.closeBtn=document.createElement("div"),this.closeBtn.className="ml-cli-close-btn",this.closeBtn.innerHTML="&#10005;",this.leftGroup.appendChild(this.closeBtn),this.downBtn=document.createElement("button"),this.downBtn.className="ml-cli-down",this.downBtn.innerHTML="&#9662;",this.leftGroup.appendChild(this.downBtn),this.centerEl=document.createElement("div"),this.centerEl.className="ml-cli-center",this.bar.appendChild(this.centerEl),this.promptEl=document.createElement("div"),this.promptEl.className="ml-cli-prompt",this.centerEl.appendChild(this.promptEl),this.textInput=document.createElement("input"),this.textInput.className="ml-cli-text",this.textInput.type="text",this.textInput.spellcheck=!1,this.textInput.autocomplete="off",this.textInput.placeholder=this.localize("main.commandLine.placeholder"),this.centerEl.appendChild(this.textInput);const e=document.createElement("div");e.className="ml-cli-right",this.bar.appendChild(e),this.upBtn=document.createElement("button"),this.upBtn.className="ml-cli-up",this.upBtn.innerHTML="&#9662;",e.appendChild(this.upBtn),this.cmdPopup=document.createElement("div"),this.cmdPopup.className="ml-cli-cmd-popup hidden",this.wrapper.appendChild(this.cmdPopup),this.msgPanel=document.createElement("div"),this.msgPanel.className="ml-cli-msg-panel hidden",this.wrapper.appendChild(this.msgPanel),this.container.appendChild(this.cliContainer)}bindEvents(){this.closeBtn.addEventListener("click",e=>{e.stopPropagation(),this.visible=!1,we.instance.isShowCommandLine=!1}),this.downBtn.addEventListener("click",e=>{e.stopPropagation(),this.isCmdPopupOpen=!this.isCmdPopupOpen,this.updatePopups({showCmd:this.isCmdPopupOpen,showMsg:!1}),this.isCmdPopupOpen&&this.showCommandHistoryPopup()}),this.upBtn.addEventListener("click",e=>{e.stopPropagation(),this.isMsgPanelOpen=!this.isMsgPanelOpen,this.updatePopups({showCmd:!1,showMsg:this.isMsgPanelOpen}),this.isMsgPanelOpen&&this.showMessagePanel()}),document.addEventListener("click",e=>{this.cliContainer.contains(e.target)||this.updatePopups({showCmd:!1,showMsg:!1})}),this.textInput.addEventListener("keydown",e=>this.handleKeyDown(e)),this.textInput.addEventListener("input",()=>this.handleInputChange()),this.centerEl.addEventListener("focus",()=>this.updatePopups({showCmd:!1,showMsg:!1})),this.cmdPopup.addEventListener("click",e=>{const t=e.target.closest(".item");t&&(this.setInputText(t.dataset.value||""),this.centerEl.focus(),this.updatePopups({showCmd:!1,showMsg:!1}))})}handleKeyDown(e){if(!e.isComposing)switch(e.key){case"Enter":{if(e.preventDefault(),e.stopImmediatePropagation(),this.activeSession){this.activeSession.handleEnter(this.getInputText())||this.showMessage(this.localize("main.commandLine.invalidInput","Invalid input."),"warning");return}this.executeCommand(this.getInputText()),this.historyIndex=this.history.length,this.updatePopups({showCmd:!1,showMsg:!1});return}case"Escape":{if(e.preventDefault(),e.stopImmediatePropagation(),this.activeSession){this.activeSession.handleEscape(),this.activeSession=void 0;return}this.clear(),this.showMessage(this.localize("main.commandLine.canceled")),this.updatePopups({showCmd:!1,showMsg:!1});return}case"ArrowUp":{e.preventDefault(),this.isCmdPopupOpen?this.navigateAutoComplete(-1):this.navigateHistory(-1);return}case"ArrowDown":{e.preventDefault(),this.isCmdPopupOpen?this.navigateAutoComplete(1):this.navigateHistory(1);return}case"Backspace":case"Delete":{e.stopPropagation(),e.stopImmediatePropagation();return}}}handleInputChange(){const e=this.getInputText();if(!e){this.updatePopups({showCmd:!1});return}const t=k.instance.searchCommandsByPrefix(e);t.length?(this.autoCompleteIndex=-1,this.cmdPopup.innerHTML="",t.forEach((i,n)=>{const r=document.createElement("div");r.className="item",r.dataset.value=i.command.globalName;const o=d.cmdDescription(i.commandGroup,i.command.globalName),a=k.instance.commandManager.getCommandAliases(i.command,i.commandGroup),l=a.length?`(${a.join(", ")})`:"";r.innerHTML=`<strong>${i.command.globalName}${l} - ${o}</strong>`,n===this.autoCompleteIndex&&r.classList.add("selected"),this.cmdPopup.appendChild(r)}),this.updatePopups({showCmd:!0})):this.updatePopups({showCmd:!1})}navigateAutoComplete(e){const t=Array.from(this.cmdPopup.querySelectorAll(".item"));if(!t.length)return;this.autoCompleteIndex+=e,this.autoCompleteIndex<0&&(this.autoCompleteIndex=0),this.autoCompleteIndex>=t.length&&(this.autoCompleteIndex=t.length-1),t.forEach((n,r)=>{n.classList.toggle("selected",r===this.autoCompleteIndex)});const i=t[this.autoCompleteIndex];i&&this.setInputText(i.dataset.value??"")}navigateHistory(e){this.history.length&&(this.historyIndex===-1&&(this.historyIndex=this.history.length),this.historyIndex+=e,this.historyIndex<0&&(this.historyIndex=0),this.historyIndex>this.history.length&&(this.historyIndex=this.history.length),this.historyIndex>=0&&this.historyIndex<this.history.length?this.setInputText(this.history[this.historyIndex]):this.setInputText(""))}getInputText(){return this.textInput.value.trim()}setInputText(e=""){this.textInput.value=e,this.textInput.focus()}renderKeywordPrompt(e,t){var o;if(this.promptEl.innerHTML="",this.isPromptActive=!0,this.textInput.placeholder="",e.message){const a=e.message.trim().replace(/[::]\s*$/,"");this.promptEl.append(a+" ")}const i=e.getKeywordPromptFormat(),n=((o=e.keywords)==null?void 0:o.toArray().filter(a=>a.visible))??[];n.length&&(this.promptEl.append("["),n.forEach((a,l)=>{l>0&&this.promptEl.append("/");const c=document.createElement("span");c.className="ml-cli-option",c.textContent=a.displayName,a.enabled?c.onclick=()=>t(a.globalName):(c.style.opacity="0.45",c.style.pointerEvents="none"),this.promptEl.append(c)}),this.promptEl.append("]"));const r=i.defaultKeyword??e.valueDefaultDisplayText;r&&this.promptEl.append(` <${r}>`),this.promptEl.append(": "),this.recordRecentMessage(this.promptEl.textContent??e.message)}bindCommandLifecycleEvents(){if(this.isCommandLifecycleBound)return;let e;try{e=k.instance.editor.events}catch{setTimeout(()=>this.bindCommandLifecycleEvents(),0);return}e.commandWillStart.addEventListener(()=>{this.cancelRecentAutoHide(),this.showRecentPanel()}),e.commandEnded.addEventListener(()=>{this.scheduleRecentAutoHide()}),this.isCommandLifecycleBound=!0}resolveCommand(e){const i=e.trim().split(/\s+/)[0].toUpperCase();return k.instance.lookupLocalCmd(i)}updatePopups({showCmd:e=!1,showMsg:t=!1}={}){this.isCmdPopupOpen=e,this.isMsgPanelOpen=t,this.cmdPopup.classList.toggle("hidden",!e),this.msgPanel.classList.toggle("hidden",!t),this.recentPanel.classList.toggle("ml-cli-recent-covered",t),e&&this.positionCmdPopup(),t&&this.positionMsgPanel()}showCommandHistoryPopup(){if(this.cmdPopup.innerHTML="",this.history.length)for(let e=this.history.length-1;e>=0;e--){const t=document.createElement("div");t.className="item",t.dataset.value=this.history[e],t.textContent=this.history[e],this.cmdPopup.appendChild(t)}else{const e=document.createElement("div");e.className="item",e.textContent=this.localize("main.commandLine.noHistory"),this.cmdPopup.appendChild(e)}this.positionCmdPopup()}positionCmdPopup(){this.cmdPopup.style.left="0px",this.cmdPopup.style.width=this.bar.offsetWidth+"px"}showMessagePanel(){if(!this.msgPanel.children.length){const e=document.createElement("div");e.className="ml-cli-history-line",e.textContent=this.localize("main.commandLine.noHistory"),e.dataset.msgKey="main.commandLine.noHistory",this.msgPanel.appendChild(e)}this.msgPanel.scrollTop=this.msgPanel.scrollHeight,this.positionMsgPanel()}positionMsgPanel(){this.msgPanel.style.width=this.bar.offsetWidth+"px"}clearNoHistoryPlaceholder(){Array.from(this.msgPanel.children).forEach(e=>{const t=e;t.dataset.msgKey==="main.commandLine.noHistory"&&this.msgPanel.removeChild(t)})}appendMessage(e,t="info",i){this.clearNoHistoryPlaceholder();const n=document.createElement("div");n.className=t==="warning"?"ml-cli-history-line ml-cli-msg-error":"ml-cli-history-line",n.textContent=e,i&&(n.dataset.msgKey=i),this.msgPanel.appendChild(n),this.recordRecentMessage(e),this.showMessagePanel()}printHistoryLine(e){this.clearNoHistoryPlaceholder();const t=document.createElement("div");t.className="ml-cli-history-line",t.textContent="> "+e,t.dataset.msgKey="main.commandLine.executed",this.msgPanel.appendChild(t),this.showMessagePanel()}resizeHandler(){const e=this.useViewportPositioning()?window.innerWidth:this.container.getBoundingClientRect().width;let t=Math.max(this.minWidth,e*this.widthRatio);t=Math.min(t,Math.max(200,e-20)),this.bar.style.width=t+"px",this.recentPanel.style.width=t+"px",this.positionMsgPanel(),this.positionCmdPopup()}recordRecentMessage(e){const t=e==null?void 0:e.replace(/\s+/g," ").trim();t&&(this.recentMessages.push(t),this.recentMessages.length>2&&this.recentMessages.shift(),this.showRecentPanel(),this.renderRecentMessages())}renderRecentMessages(){this.recentPanel.innerHTML="",this.recentMessages.forEach(e=>{const t=document.createElement("div");t.className="ml-cli-recent-line",t.textContent=e,this.recentPanel.appendChild(t)})}scheduleRecentAutoHide(){this.cancelRecentAutoHide(),this.recentHideTimer=setTimeout(()=>{this.hideRecentPanel(),this.recentHideTimer=void 0},2e3)}cancelRecentAutoHide(){this.recentHideTimer&&(clearTimeout(this.recentHideTimer),this.recentHideTimer=void 0)}showRecentPanel(){this.recentPanel.classList.remove("hidden")}hideRecentPanel(){this.recentPanel.classList.add("hidden")}useViewportPositioning(){return this.container===document.body}}class Nm{constructor(e){this.options=e}parse(e){const t=Number(e);return isNaN(t)||!this.options.allowNegative&&t<0||!this.options.allowZero&&t===0?null:t}parseCommandLine(e,t){const i=e.trim();return i?this.parse(i):null}}class Pr{constructor(e){this.options=e}parse(e){const t=Number(e);return isNaN(t)||!this.options.allowNegative&&t<0||!this.options.allowZero&&t===0?null:t}parseCommandLine(e,t){const i=e.trim();return i?this.parse(i):null}}class Rm extends Pr{}class Vm extends Pr{}class Fl extends Pr{constructor(e){super(e)}parse(e){const t=super.parse(e);return t==null?t:!Number.isInteger(t)||this.options.lowerLimit!==void 0&&t<this.options.lowerLimit||this.options.upperLimit!==void 0&&t>this.options.upperLimit?null:t}}const Gm=/^-?(?:\d+\.?\d*|\.\d+)$/;function Km(s){const e=s.trim();if(!e)return;if(e.includes(",")){const i=e.split(",").map(n=>n.trim());return i.length!==2&&i.length!==3||i.length===3&&Number.isNaN(Number(i[2]))?void 0:{x:i[0],y:i[1]}}const t=e.split(/\s+/);if(!(t.length<2))return{x:t[0],y:t[1]}}class xi{constructor(e){this.options=e}parse(e,t){const i=Number(e),n=Number(t);return isNaN(i)||isNaN(n)?null:{x:i,y:n,z:0}}parseCommandLine(e,t){const i=e.trim();if(!i)return null;const n=i.startsWith("@"),r=n?i.slice(1).trim():i;if(!r)return null;const o=(t==null?void 0:t.referencePoint)??void 0,a=r.indexOf("<");if(a>=0){const c=r.slice(0,a).trim(),h=r.slice(a+1).trim(),p=Number(c),m=Number(h);if(Number.isNaN(p)||Number.isNaN(m))return null;const g=m*Math.PI/180,f=p*Math.cos(g),w=p*Math.sin(g);return n?o?this.parse(String(o.x+f),String(o.y+w)):null:this.parse(String(f),String(w))}const l=Km(r);if(l){const c=Number(l.x),h=Number(l.y);return Number.isNaN(c)||Number.isNaN(h)?null:n?o?this.parse(String(o.x+c),String(o.y+h)):null:this.parse(l.x,l.y)}if(Gm.test(r)){const c=Number(r),h=t==null?void 0:t.cursorPoint;if(!o||!h||Number.isNaN(c))return null;const p=h.x-o.x,m=h.y-o.y,f=Math.hypot(p,m)>1e-10?Math.atan2(m,p):0;return this.parse(String(o.x+c*Math.cos(f)),String(o.y+c*Math.sin(f)))}return null}}class Fn{constructor(e){this.options=e}parse(e){return!this.options.allowSpaces&&e.includes(" ")||!this.options.allowEmpty&&e.length===0||this.options.maxLength&&e.length>this.options.maxLength?null:e}parseCommandLine(e,t){return this.parse(e)}}class zl{constructor(e){this.userTyped=!1,this.parent=e,this.input=document.createElement("input"),this.input.type="text",this.boundOnInput=()=>{this.userTyped=!0,this.resetValidation()},this.input.addEventListener("input",this.boundOnInput),this.parent.appendChild(this.input)}markInvalid(){this.input.classList.add("invalid")}markValid(){this.input.classList.remove("invalid")}resetValidation(){this.input.classList.remove("invalid")}get placeholder(){return this.input.placeholder}set placeholder(e){e&&(this.input.placeholder=e)}set value(e){if(e===void 0)return;const t=this.focused&&!this.userTyped;this.input.value=e,t&&this.input.select()}get value(){return this.input.value}get focused(){return document.activeElement===this.input}focus(){this.input.focus(),this.userTyped||this.input.select()}blur(){this.input.blur()}select(){this.input.select()}remove(){this.input.remove()}isEventTarget(e){return e.target===this.input}dispose(){this.input.removeEventListener("input",this.boundOnInput),this.remove()}addEventListener(e,t,i){this.input.addEventListener(e,t,i)}removeEventListener(e,t,i){this.input.removeEventListener(e,t,i)}}class Um{constructor(e){this.parent=e.parent,this.twoInputs=e.twoInputs??!0,this.boundOnInput=()=>this.handleInput(),this.boundOnKeyDown=t=>this.handleKeyDown(t),this.xInput=new zl(this.parent),this.xInput.addEventListener("input",this.boundOnInput),this.xInput.addEventListener("keydown",this.boundOnKeyDown),this.twoInputs&&(this.yInput=new zl(this.parent),this.yInput.addEventListener("input",this.boundOnInput),this.yInput.addEventListener("keydown",this.boundOnKeyDown)),this.validateFn=e.validate,this.onCommit=e.onCommit,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onNone=e.onNone,this.allowNone=e.allowNone??!1,this.useDefaultValue=e.useDefaultValue??!1,this.defaultValue=e.defaultValue,e.autoFocus!==!1&&setTimeout(()=>{this.yInput&&this.yInput.select(),this.xInput.focus(),this.xInput.select()},0)}get userTyped(){var e;return this.xInput.userTyped||!!((e=this.yInput)!=null&&e.userTyped)}get focused(){var e;return this.xInput.focused||((e=this.yInput)==null?void 0:e.focused)}focus(){this.xInput.focus()}blur(){var e;this.xInput.blur(),(e=this.yInput)==null||e.blur()}setValue(e){this.xInput.userTyped||(this.xInput.value=e.x),this.twoInputs&&this.yInput&&!this.yInput.userTyped&&(this.yInput.value=e.y??"")}dispose(){var e;this.xInput.removeEventListener("input",this.boundOnInput),this.xInput.removeEventListener("keydown",this.boundOnKeyDown),this.xInput.dispose(),this.yInput&&(this.yInput.removeEventListener("input",this.boundOnInput),this.yInput.removeEventListener("keydown",this.boundOnKeyDown),(e=this.yInput)==null||e.dispose())}handleInput(){var t;const e=this.validate();(t=this.onChange)==null||t.call(this,e)}handleKeyDown(e){var n,r,o;let t=this.xInput,i=this.yInput;if(this.yInput&&this.yInput.isEventTarget(e)&&(t=this.yInput,i=this.xInput),e.key==="Enter"){if(this.useDefaultValue&&!this.userTyped){!this.onCommit||this.onCommit(this.defaultValue)?t.markValid():t.markInvalid(),e.preventDefault(),e.stopPropagation();return}if(!this.userTyped)this.allowNone?(n=this.onNone)==null||n.call(this):t.markInvalid();else{const a=this.validate();a.isValid&&a.value!=null?((r=this.onCommit)==null||r.call(this,a.value),t.markValid()):t.markInvalid()}e.preventDefault(),e.stopPropagation()}else e.key==="Escape"?((o=this.onCancel)==null||o.call(this),e.preventDefault(),e.stopPropagation()):e.key==="Tab"&&(e.preventDefault(),i&&(i==null||i.focus(),i==null||i.select()))}validate(){const e=this.xInput.value.trim(),t=this.twoInputs&&this.yInput?this.yInput.value.trim():void 0;return this.validateFn({x:e,y:t})}}const Zi=class Zi{constructor(e,t){this.visible=!1,this.disposed=!1,this.isHovering=!1,this.view=e,this.parent=t.parent??this.view.canvas,this.host=this.view.container,getComputedStyle(this.host).position==="static"&&(this.host.style.position="relative"),this.container=document.createElement("div"),this.container.className="ml-floating-input",this.allowPrompt=t.allowPrompt!==!1;const n=t.message??"";this.label=document.createElement("span"),this.label.className="ml-floating-input-label",this.label.textContent=n,n.trim()||(this.label.style.display="none"),this.container.appendChild(this.label),this.host.appendChild(this.container),this.boundOnMouseEnter=r=>this.handleMouseEnter(r),this.boundOnMouseLeave=()=>this.handleMouseLeave(),this.boundOnMouseMove=r=>this.handleMouseMove(r),this.parent.addEventListener("mouseenter",this.boundOnMouseEnter),this.parent.addEventListener("mouseleave",this.boundOnMouseLeave),this.boundOnSysVarChanged=r=>{var a;const o=(a=r.name)==null?void 0:a.toLowerCase();(o===u.AcDbSystemVariables.DYNMODE.toLowerCase()||o===u.AcDbSystemVariables.DYNPROMPT.toLowerCase())&&this.updateDynamicDisplay()},u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.boundOnSysVarChanged),this.updateDynamicDisplay(),this.injectCSS()}injectCSS(){if(Zi.stylesInjected)return;Zi.stylesInjected=!0;const e=document.createElement("style");e.textContent=`
524
+ `,document.head.appendChild(e)}createUI(){this.cliContainer=document.createElement("div"),this.cliContainer.className="ml-cli-container",this.cliContainer.style.position=this.useViewportPositioning()?"fixed":"absolute",this.useViewportPositioning()||getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.wrapper=document.createElement("div"),this.wrapper.className="ml-cli-wrapper",this.cliContainer.appendChild(this.wrapper),this.recentPanel=document.createElement("div"),this.recentPanel.className="ml-cli-recent",this.wrapper.appendChild(this.recentPanel),this.bar=document.createElement("div"),this.bar.className="ml-cli-bar",this.wrapper.appendChild(this.bar),this.leftGroup=document.createElement("div"),this.leftGroup.className="ml-cli-left",this.bar.appendChild(this.leftGroup),this.closeBtn=document.createElement("div"),this.closeBtn.className="ml-cli-close-btn",this.closeBtn.innerHTML="&#10005;",this.leftGroup.appendChild(this.closeBtn),this.downBtn=document.createElement("button"),this.downBtn.className="ml-cli-down",this.downBtn.innerHTML="&#9662;",this.leftGroup.appendChild(this.downBtn),this.centerEl=document.createElement("div"),this.centerEl.className="ml-cli-center",this.bar.appendChild(this.centerEl),this.promptEl=document.createElement("div"),this.promptEl.className="ml-cli-prompt",this.centerEl.appendChild(this.promptEl),this.textInput=document.createElement("input"),this.textInput.className="ml-cli-text",this.textInput.type="text",this.textInput.spellcheck=!1,this.textInput.autocomplete="off",this.textInput.placeholder=this.localize("main.commandLine.placeholder"),this.centerEl.appendChild(this.textInput);const e=document.createElement("div");e.className="ml-cli-right",this.bar.appendChild(e),this.upBtn=document.createElement("button"),this.upBtn.className="ml-cli-up",this.upBtn.innerHTML="&#9662;",e.appendChild(this.upBtn),this.cmdPopup=document.createElement("div"),this.cmdPopup.className="ml-cli-cmd-popup hidden",this.wrapper.appendChild(this.cmdPopup),this.msgPanel=document.createElement("div"),this.msgPanel.className="ml-cli-msg-panel hidden",this.wrapper.appendChild(this.msgPanel),this.container.appendChild(this.cliContainer)}bindEvents(){this.closeBtn.addEventListener("click",e=>{e.stopPropagation(),this.visible=!1,ue.instance.isShowCommandLine=!1}),this.downBtn.addEventListener("click",e=>{e.stopPropagation(),this.isCmdPopupOpen=!this.isCmdPopupOpen,this.updatePopups({showCmd:this.isCmdPopupOpen,showMsg:!1}),this.isCmdPopupOpen&&this.showCommandHistoryPopup()}),this.upBtn.addEventListener("click",e=>{e.stopPropagation(),this.isMsgPanelOpen=!this.isMsgPanelOpen,this.updatePopups({showCmd:!1,showMsg:this.isMsgPanelOpen}),this.isMsgPanelOpen&&this.showMessagePanel()}),document.addEventListener("click",e=>{this.cliContainer.contains(e.target)||this.updatePopups({showCmd:!1,showMsg:!1})}),this.textInput.addEventListener("keydown",e=>this.handleKeyDown(e)),this.textInput.addEventListener("input",()=>this.handleInputChange()),this.centerEl.addEventListener("focus",()=>this.updatePopups({showCmd:!1,showMsg:!1})),this.cmdPopup.addEventListener("click",e=>{const t=e.target.closest(".item");t&&(this.setInputText(t.dataset.value||""),this.centerEl.focus(),this.updatePopups({showCmd:!1,showMsg:!1}))})}handleKeyDown(e){if(!e.isComposing)switch(e.key){case"Enter":{if(e.preventDefault(),e.stopImmediatePropagation(),this.activeSession){this.activeSession.handleEnter(this.getInputText())||this.showMessage(this.localize("main.commandLine.invalidInput","Invalid input."),"warning");return}this.executeCommand(this.getInputText()),this.historyIndex=this.history.length,this.updatePopups({showCmd:!1,showMsg:!1});return}case"Escape":{if(e.preventDefault(),e.stopImmediatePropagation(),this.activeSession){this.activeSession.handleEscape(),this.activeSession=void 0;return}this.clear(),this.showMessage(this.localize("main.commandLine.canceled")),this.updatePopups({showCmd:!1,showMsg:!1});return}case"ArrowUp":{e.preventDefault(),this.isCmdPopupOpen?this.navigateAutoComplete(-1):this.navigateHistory(-1);return}case"ArrowDown":{e.preventDefault(),this.isCmdPopupOpen?this.navigateAutoComplete(1):this.navigateHistory(1);return}case"Backspace":case"Delete":{e.stopPropagation(),e.stopImmediatePropagation();return}}}handleInputChange(){const e=this.getInputText();if(!e){this.updatePopups({showCmd:!1});return}const t=k.instance.searchCommandsByPrefix(e);t.length?(this.autoCompleteIndex=-1,this.cmdPopup.innerHTML="",t.forEach((i,n)=>{const r=document.createElement("div");r.className="item",r.dataset.value=i.command.globalName;const o=u.cmdDescription(i.commandGroup,i.command.globalName),a=k.instance.commandManager.getCommandAliases(i.command,i.commandGroup),l=a.length?`(${a.join(", ")})`:"";r.innerHTML=`<strong>${i.command.globalName}${l} - ${o}</strong>`,n===this.autoCompleteIndex&&r.classList.add("selected"),this.cmdPopup.appendChild(r)}),this.updatePopups({showCmd:!0})):this.updatePopups({showCmd:!1})}navigateAutoComplete(e){const t=Array.from(this.cmdPopup.querySelectorAll(".item"));if(!t.length)return;this.autoCompleteIndex+=e,this.autoCompleteIndex<0&&(this.autoCompleteIndex=0),this.autoCompleteIndex>=t.length&&(this.autoCompleteIndex=t.length-1),t.forEach((n,r)=>{n.classList.toggle("selected",r===this.autoCompleteIndex)});const i=t[this.autoCompleteIndex];i&&this.setInputText(i.dataset.value??"")}navigateHistory(e){this.history.length&&(this.historyIndex===-1&&(this.historyIndex=this.history.length),this.historyIndex+=e,this.historyIndex<0&&(this.historyIndex=0),this.historyIndex>this.history.length&&(this.historyIndex=this.history.length),this.historyIndex>=0&&this.historyIndex<this.history.length?this.setInputText(this.history[this.historyIndex]):this.setInputText(""))}getInputText(){return this.textInput.value.trim()}setInputText(e=""){this.textInput.value=e,this.textInput.focus()}renderKeywordPrompt(e,t){var o;if(this.promptEl.innerHTML="",this.isPromptActive=!0,this.textInput.placeholder="",e.message){const a=e.message.trim().replace(/[::]\s*$/,"");this.promptEl.append(a+" ")}const i=e.getKeywordPromptFormat(),n=((o=e.keywords)==null?void 0:o.toArray().filter(a=>a.visible))??[];n.length&&(this.promptEl.append("["),n.forEach((a,l)=>{l>0&&this.promptEl.append("/");const c=document.createElement("span");c.className="ml-cli-option",c.textContent=a.displayName,a.enabled?c.onclick=()=>t(a.globalName):(c.style.opacity="0.45",c.style.pointerEvents="none"),this.promptEl.append(c)}),this.promptEl.append("]"));const r=i.defaultKeyword??e.valueDefaultDisplayText;r&&this.promptEl.append(` <${r}>`),this.promptEl.append(": "),this.recordRecentMessage(this.promptEl.textContent??e.message)}bindCommandLifecycleEvents(){if(this.isCommandLifecycleBound)return;let e;try{e=k.instance.editor.events}catch{setTimeout(()=>this.bindCommandLifecycleEvents(),0);return}e.commandWillStart.addEventListener(()=>{this.cancelRecentAutoHide(),this.showRecentPanel()}),e.commandEnded.addEventListener(()=>{this.scheduleRecentAutoHide()}),this.isCommandLifecycleBound=!0}resolveCommand(e){const i=e.trim().split(/\s+/)[0].toUpperCase();return k.instance.lookupLocalCmd(i)}updatePopups({showCmd:e=!1,showMsg:t=!1}={}){this.isCmdPopupOpen=e,this.isMsgPanelOpen=t,this.cmdPopup.classList.toggle("hidden",!e),this.msgPanel.classList.toggle("hidden",!t),this.recentPanel.classList.toggle("ml-cli-recent-covered",t),e&&this.positionCmdPopup(),t&&this.positionMsgPanel()}showCommandHistoryPopup(){if(this.cmdPopup.innerHTML="",this.history.length)for(let e=this.history.length-1;e>=0;e--){const t=document.createElement("div");t.className="item",t.dataset.value=this.history[e],t.textContent=this.history[e],this.cmdPopup.appendChild(t)}else{const e=document.createElement("div");e.className="item",e.textContent=this.localize("main.commandLine.noHistory"),this.cmdPopup.appendChild(e)}this.positionCmdPopup()}positionCmdPopup(){this.cmdPopup.style.left="0px",this.cmdPopup.style.width=this.bar.offsetWidth+"px"}showMessagePanel(){if(!this.msgPanel.children.length){const e=document.createElement("div");e.className="ml-cli-history-line",e.textContent=this.localize("main.commandLine.noHistory"),e.dataset.msgKey="main.commandLine.noHistory",this.msgPanel.appendChild(e)}this.msgPanel.scrollTop=this.msgPanel.scrollHeight,this.positionMsgPanel()}positionMsgPanel(){this.msgPanel.style.width=this.bar.offsetWidth+"px"}clearNoHistoryPlaceholder(){Array.from(this.msgPanel.children).forEach(e=>{const t=e;t.dataset.msgKey==="main.commandLine.noHistory"&&this.msgPanel.removeChild(t)})}appendMessage(e,t="info",i){this.clearNoHistoryPlaceholder();const n=document.createElement("div");n.className=t==="warning"?"ml-cli-history-line ml-cli-msg-error":"ml-cli-history-line",n.textContent=e,i&&(n.dataset.msgKey=i),this.msgPanel.appendChild(n),this.recordRecentMessage(e),this.showMessagePanel()}printHistoryLine(e){this.clearNoHistoryPlaceholder();const t=document.createElement("div");t.className="ml-cli-history-line",t.textContent="> "+e,t.dataset.msgKey="main.commandLine.executed",this.msgPanel.appendChild(t),this.showMessagePanel()}resizeHandler(){const e=this.useViewportPositioning()?window.innerWidth:this.container.getBoundingClientRect().width;let t=Math.max(this.minWidth,e*this.widthRatio);t=Math.min(t,Math.max(200,e-20)),this.bar.style.width=t+"px",this.recentPanel.style.width=t+"px",this.positionMsgPanel(),this.positionCmdPopup()}recordRecentMessage(e){const t=e==null?void 0:e.replace(/\s+/g," ").trim();t&&(this.recentMessages.push(t),this.recentMessages.length>2&&this.recentMessages.shift(),this.showRecentPanel(),this.renderRecentMessages())}renderRecentMessages(){this.recentPanel.innerHTML="",this.recentMessages.forEach(e=>{const t=document.createElement("div");t.className="ml-cli-recent-line",t.textContent=e,this.recentPanel.appendChild(t)})}scheduleRecentAutoHide(){this.cancelRecentAutoHide(),this.recentHideTimer=setTimeout(()=>{this.hideRecentPanel(),this.recentHideTimer=void 0},2e3)}cancelRecentAutoHide(){this.recentHideTimer&&(clearTimeout(this.recentHideTimer),this.recentHideTimer=void 0)}showRecentPanel(){this.recentPanel.classList.remove("hidden")}hideRecentPanel(){this.recentPanel.classList.add("hidden")}useViewportPositioning(){return this.container===document.body}}class ly{constructor(e){this.options=e}parse(e){const t=Number(e);return isNaN(t)||!this.options.allowNegative&&t<0||!this.options.allowZero&&t===0?null:t}parseCommandLine(e,t){const i=e.trim();return i?this.parse(i):null}}class Ir{constructor(e){this.options=e}parse(e){const t=Number(e);return isNaN(t)||!this.options.allowNegative&&t<0||!this.options.allowZero&&t===0?null:t}parseCommandLine(e,t){const i=e.trim();return i?this.parse(i):null}}class cy extends Ir{}class dy extends Ir{}class $l extends Ir{constructor(e){super(e)}parse(e){const t=super.parse(e);return t==null?t:!Number.isInteger(t)||this.options.lowerLimit!==void 0&&t<this.options.lowerLimit||this.options.upperLimit!==void 0&&t>this.options.upperLimit?null:t}}const uy=/^-?(?:\d+\.?\d*|\.\d+)$/;function hy(s){const e=s.trim();if(!e)return;if(e.includes(",")){const i=e.split(",").map(n=>n.trim());return i.length!==2&&i.length!==3||i.length===3&&Number.isNaN(Number(i[2]))?void 0:{x:i[0],y:i[1]}}const t=e.split(/\s+/);if(!(t.length<2))return{x:t[0],y:t[1]}}class Si{constructor(e){this.options=e}parse(e,t){const i=Number(e),n=Number(t);return isNaN(i)||isNaN(n)?null:{x:i,y:n,z:0}}parseCommandLine(e,t){const i=e.trim();if(!i)return null;const n=i.startsWith("@"),r=n?i.slice(1).trim():i;if(!r)return null;const o=(t==null?void 0:t.referencePoint)??void 0,a=r.indexOf("<");if(a>=0){const c=r.slice(0,a).trim(),h=r.slice(a+1).trim(),p=Number(c),m=Number(h);if(Number.isNaN(p)||Number.isNaN(m))return null;const g=m*Math.PI/180,f=p*Math.cos(g),w=p*Math.sin(g);return n?o?this.parse(String(o.x+f),String(o.y+w)):null:this.parse(String(f),String(w))}const l=hy(r);if(l){const c=Number(l.x),h=Number(l.y);return Number.isNaN(c)||Number.isNaN(h)?null:n?o?this.parse(String(o.x+c),String(o.y+h)):null:this.parse(l.x,l.y)}if(uy.test(r)){const c=Number(r),h=t==null?void 0:t.cursorPoint;if(!o||!h||Number.isNaN(c))return null;const p=h.x-o.x,m=h.y-o.y,f=Math.hypot(p,m)>1e-10?Math.atan2(m,p):0;return this.parse(String(o.x+c*Math.cos(f)),String(o.y+c*Math.sin(f)))}return null}}class Vn{constructor(e){this.options=e}parse(e){return!this.options.allowSpaces&&e.includes(" ")||!this.options.allowEmpty&&e.length===0||this.options.maxLength&&e.length>this.options.maxLength?null:e}parseCommandLine(e,t){return this.parse(e)}}class Yl{constructor(e){this.userTyped=!1,this.parent=e,this.input=document.createElement("input"),this.input.type="text",this.boundOnInput=()=>{this.userTyped=!0,this.resetValidation()},this.input.addEventListener("input",this.boundOnInput),this.parent.appendChild(this.input)}markInvalid(){this.input.classList.add("invalid")}markValid(){this.input.classList.remove("invalid")}resetValidation(){this.input.classList.remove("invalid")}get placeholder(){return this.input.placeholder}set placeholder(e){e&&(this.input.placeholder=e)}set value(e){if(e===void 0)return;const t=this.focused&&!this.userTyped;this.input.value=e,t&&this.input.select()}get value(){return this.input.value}get focused(){return document.activeElement===this.input}focus(){this.input.focus(),this.userTyped||this.input.select()}blur(){this.input.blur()}select(){this.input.select()}remove(){this.input.remove()}isEventTarget(e){return e.target===this.input}dispose(){this.input.removeEventListener("input",this.boundOnInput),this.remove()}addEventListener(e,t,i){this.input.addEventListener(e,t,i)}removeEventListener(e,t,i){this.input.removeEventListener(e,t,i)}}class py{constructor(e){this.parent=e.parent,this.twoInputs=e.twoInputs??!0,this.boundOnInput=()=>this.handleInput(),this.boundOnKeyDown=t=>this.handleKeyDown(t),this.xInput=new Yl(this.parent),this.xInput.addEventListener("input",this.boundOnInput),this.xInput.addEventListener("keydown",this.boundOnKeyDown),this.twoInputs&&(this.yInput=new Yl(this.parent),this.yInput.addEventListener("input",this.boundOnInput),this.yInput.addEventListener("keydown",this.boundOnKeyDown)),this.validateFn=e.validate,this.onCommit=e.onCommit,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onNone=e.onNone,this.allowNone=e.allowNone??!1,this.useDefaultValue=e.useDefaultValue??!1,this.defaultValue=e.defaultValue,e.autoFocus!==!1&&setTimeout(()=>{this.yInput&&this.yInput.select(),this.xInput.focus(),this.xInput.select()},0)}get userTyped(){var e;return this.xInput.userTyped||!!((e=this.yInput)!=null&&e.userTyped)}get focused(){var e;return this.xInput.focused||((e=this.yInput)==null?void 0:e.focused)}focus(){this.xInput.focus()}blur(){var e;this.xInput.blur(),(e=this.yInput)==null||e.blur()}setValue(e){this.xInput.userTyped||(this.xInput.value=e.x),this.twoInputs&&this.yInput&&!this.yInput.userTyped&&(this.yInput.value=e.y??"")}dispose(){var e;this.xInput.removeEventListener("input",this.boundOnInput),this.xInput.removeEventListener("keydown",this.boundOnKeyDown),this.xInput.dispose(),this.yInput&&(this.yInput.removeEventListener("input",this.boundOnInput),this.yInput.removeEventListener("keydown",this.boundOnKeyDown),(e=this.yInput)==null||e.dispose())}handleInput(){var t;const e=this.validate();(t=this.onChange)==null||t.call(this,e)}handleKeyDown(e){var n,r,o;let t=this.xInput,i=this.yInput;if(this.yInput&&this.yInput.isEventTarget(e)&&(t=this.yInput,i=this.xInput),e.key==="Enter"){if(this.useDefaultValue&&!this.userTyped){!this.onCommit||this.onCommit(this.defaultValue)?t.markValid():t.markInvalid(),e.preventDefault(),e.stopPropagation();return}if(!this.userTyped)this.allowNone?(n=this.onNone)==null||n.call(this):t.markInvalid();else{const a=this.validate();a.isValid&&a.value!=null?((r=this.onCommit)==null||r.call(this,a.value),t.markValid()):t.markInvalid()}e.preventDefault(),e.stopPropagation()}else e.key==="Escape"?((o=this.onCancel)==null||o.call(this),e.preventDefault(),e.stopPropagation()):e.key==="Tab"&&(e.preventDefault(),i&&(i==null||i.focus(),i==null||i.select()))}validate(){const e=this.xInput.value.trim(),t=this.twoInputs&&this.yInput?this.yInput.value.trim():void 0;return this.validateFn({x:e,y:t})}}const Xi=class Xi{constructor(e,t){this.visible=!1,this.disposed=!1,this.isHovering=!1,this.view=e,this.parent=t.parent??this.view.canvas,this.host=this.view.container,getComputedStyle(this.host).position==="static"&&(this.host.style.position="relative"),this.container=document.createElement("div"),this.container.className="ml-floating-input",this.allowPrompt=t.allowPrompt!==!1;const n=t.message??"";this.label=document.createElement("span"),this.label.className="ml-floating-input-label",this.label.textContent=n,n.trim()||(this.label.style.display="none"),this.container.appendChild(this.label),this.host.appendChild(this.container),this.boundOnMouseEnter=r=>this.handleMouseEnter(r),this.boundOnMouseLeave=()=>this.handleMouseLeave(),this.boundOnMouseMove=r=>this.handleMouseMove(r),this.parent.addEventListener("mouseenter",this.boundOnMouseEnter),this.parent.addEventListener("mouseleave",this.boundOnMouseLeave),this.boundOnSysVarChanged=r=>{var a;const o=(a=r.name)==null?void 0:a.toLowerCase();(o===d.AcDbSystemVariables.DYNMODE.toLowerCase()||o===d.AcDbSystemVariables.DYNPROMPT.toLowerCase())&&this.updateDynamicDisplay()},d.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.boundOnSysVarChanged),this.updateDynamicDisplay(),this.injectCSS()}injectCSS(){if(Xi.stylesInjected)return;Xi.stylesInjected=!0;const e=document.createElement("style");e.textContent=`
475
525
  .ml-floating-input {
476
526
  position: absolute;
477
527
  display: flex;
@@ -488,7 +538,7 @@
488
538
  white-space: nowrap;
489
539
  color: var(--ml-ui-text, #fff);
490
540
  }
491
- `,document.head.appendChild(e)}get isVisible(){return this.visible}showAt(e){this.disposed||this.shouldShowPrompt()&&(this.visible=!0,this.container.style.display="flex",this.setPosition(e),this.parent.addEventListener("mousemove",this.boundOnMouseMove))}hide(){this.visible&&(this.visible=!1,this.container.style.display="none",this.parent.removeEventListener("mousemove",this.boundOnMouseMove))}dispose(){this.disposed||(this.disposed=!0,this.hide(),this.parent.removeEventListener("mouseenter",this.boundOnMouseEnter),this.parent.removeEventListener("mouseleave",this.boundOnMouseLeave),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.boundOnSysVarChanged),this.container.remove())}setPosition(e){const t=this.host.getBoundingClientRect(),i=this.container.getBoundingClientRect(),n=this.view.viewportToCanvas(e),r=this.view.viewportToContainer(e);let o=r.x+10,a=r.y+10;return o=Math.min(o,t.width-i.width),a=Math.min(a,t.height-i.height),o=Math.max(o,0),a=Math.max(a,0),this.container.style.left=`${o}px`,this.container.style.top=`${a}px`,n}handleMouseEnter(e){this.isHovering=!0,this.showAt(e)}handleMouseLeave(){this.isHovering=!1,this.hide()}handleMouseMove(e){this.visible&&this.setPosition(e)}getSysVarValue(e){const t=u.acdbHostApplicationServices().workingDatabase;return u.AcDbSysVarManager.instance().getVar(e,t)}isDynamicInputEnabled(){return this.getSysVarValue(u.AcDbSystemVariables.DYNMODE)!==0}isDynamicPromptEnabled(){return!!this.getSysVarValue(u.AcDbSystemVariables.DYNPROMPT)}shouldShowPrompt(){var t;return!(!!!((t=this.label.textContent)!=null&&t.trim())||!this.allowPrompt||!this.isDynamicInputEnabled()||!this.isDynamicPromptEnabled())}updateDynamicDisplay(){if(!this.shouldShowPrompt()){this.hide();return}this.isHovering&&this.showAt(this.view.canvasToViewport(this.view.curMousePos))}};Zi.stylesInjected=!1;let Si=Zi;class Nl{constructor(e){this.container=null,this.baseLine=null,this.perpLineAtBase=null,this.perpLineAtCursor=null,this.connectorLine=null,this.labelEl=null,this.angleLabelEl=null,this.xAxisLine=null,this.angleSvg=null,this.anglePath=null,this.options={},this.view=e}get element(){return this.container}toContainerPoint(e){return this.view.canvasToContainer(this.view.worldToScreen(e))}ensureHostPositioned(){const e=this.view.container;getComputedStyle(e).position==="static"&&(e.style.position="relative")}start(e,t){this.basePoint=new u.AcGePoint3d(e),this.options=t||{};const i=this.options.color||"var(--ml-ui-canvas-line, #0f0)";this.ensureHostPositioned(),this.container=document.createElement("div"),this.container.style.position="absolute",this.container.style.left="0",this.container.style.top="0",this.container.style.width="100%",this.container.style.height="100%",this.container.style.pointerEvents="none",this.container.style.zIndex="1",this.view.container.appendChild(this.container),this.baseLine=document.createElement("div"),this.baseLine.style.position="absolute",this.baseLine.style.borderTop=`1px solid ${i}`,this.container.appendChild(this.baseLine);const n=()=>{const r=document.createElement("div");return r.style.position="absolute",r.style.borderTop=`1px dashed ${i}`,this.container.appendChild(r),r};this.options.showBaseLineOnly||(this.perpLineAtBase=n(),this.perpLineAtCursor=n(),this.connectorLine=n(),this.labelEl=document.createElement("div"),this.labelEl.style.position="absolute",this.labelEl.style.color=i,this.labelEl.style.fontSize="12px",this.labelEl.style.padding="2px 4px",this.labelEl.style.borderRadius="4px",this.container.appendChild(this.labelEl),this.xAxisLine=document.createElement("div"),this.xAxisLine.style.position="absolute",this.xAxisLine.style.borderTop=`1px solid ${i}`,this.container.appendChild(this.xAxisLine),this.angleSvg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.angleSvg.setAttribute("style","position:absolute; overflow:visible; pointer-events:none;"),this.anglePath=document.createElementNS("http://www.w3.org/2000/svg","path"),this.anglePath.setAttribute("fill","none"),this.anglePath.setAttribute("stroke",i),this.anglePath.setAttribute("stroke-width","1"),this.anglePath.setAttribute("stroke-dasharray","4 4"),this.angleSvg.appendChild(this.anglePath),this.container.appendChild(this.angleSvg),this.angleLabelEl=document.createElement("div"),this.angleLabelEl.style.position="absolute",this.angleLabelEl.style.color=i,this.angleLabelEl.style.fontSize="12px",this.angleLabelEl.style.padding="2px 4px",this.angleLabelEl.style.borderRadius="4px",this.container.appendChild(this.angleLabelEl))}update(e){var g,f;if(!this.container||!this.basePoint||!this.baseLine)return;const t=this.toContainerPoint(this.basePoint),i=this.toContainerPoint(e),n=(w,v,x)=>{const S=x.x-v.x,P=x.y-v.y,A=Math.sqrt(S*S+P*P),_=Math.atan2(P,S)*(180/Math.PI);w.style.width=`${A}px`,w.style.transformOrigin="0 0",w.style.transform=`translate(${v.x}px, ${v.y}px) rotate(${_}deg)`};if(n(this.baseLine,t,i),this.options.showBaseLineOnly||!this.perpLineAtBase||!this.perpLineAtCursor||!this.connectorLine)return;const r=i.x-t.x,o=i.y-t.y,a=Math.sqrt(r*r+o*o);if(a===0){this.perpLineAtBase&&(this.perpLineAtBase.style.width="0px"),this.perpLineAtCursor&&(this.perpLineAtCursor.style.width="0px"),this.connectorLine&&(this.connectorLine.style.width="0px"),this.xAxisLine&&(this.xAxisLine.style.width="0px"),this.anglePath&&this.anglePath.setAttribute("d",""),this.angleLabelEl&&(this.angleLabelEl.style.display="none");return}const l=this.options.perpendicularLength??50,c=-o/a,h=r/a,p={x:t.x+c*l,y:t.y+h*l},m={x:i.x+c*l,y:i.y+h*l};if(n(this.perpLineAtBase,t,p),n(this.perpLineAtCursor,i,m),n(this.connectorLine,p,m),this.labelEl){const w=(p.x+m.x)/2,v=(p.y+m.y)/2-24,x=Math.sqrt((e.x-this.basePoint.x)**2+(e.y-this.basePoint.y)**2),S=(g=k.instance.curDocument)==null?void 0:g.database;this.labelEl.textContent=S?S.formatter.formatLength(x):x.toFixed(3),this.labelEl.style.left=`${w-20}px`,this.labelEl.style.top=`${v}px`,this.labelEl.style.display=""}if(this.xAxisLine){const w=(this.options.baseAngle??0)*Math.PI/180,v={x:this.basePoint.x+Math.cos(w),y:this.basePoint.y+Math.sin(w),z:0},x=this.toContainerPoint(v),S=Math.atan2(x.y-t.y,x.x-t.x),P={x:t.x+a*Math.cos(S),y:t.y+a*Math.sin(S)};n(this.xAxisLine,t,P)}if(this.angleSvg&&this.anglePath&&this.angleLabelEl){const w=a,v=t.x,x=t.y,S=(this.options.baseAngle??0)*Math.PI/180,P={x:this.basePoint.x+Math.cos(S),y:this.basePoint.y+Math.sin(S),z:0},A=this.toContainerPoint(P),_=Math.atan2(A.y-t.y,A.x-t.x);let O=Math.atan2(i.y-t.y,i.x-t.x)-_;for(;O<=-Math.PI;)O+=Math.PI*2;for(;O>Math.PI;)O-=Math.PI*2;const j=_+O/2,L=v-w,N=x-w,R=w*2;this.angleSvg.style.left=`${L}px`,this.angleSvg.style.top=`${N}px`,this.angleSvg.setAttribute("width",`${R}`),this.angleSvg.setAttribute("height",`${R}`),this.angleSvg.setAttribute("viewBox",`0 0 ${R} ${R}`);const W=w,X=w,$=W+w*Math.cos(_),J=X+w*Math.sin(_),se=W+w*Math.cos(_+O),re=X+w*Math.sin(_+O),Mt=Math.abs(O)>Math.PI?"1":"0",jo=O>=0?"1":"0",db=`M ${$} ${J} A ${w} ${w} 0 ${Mt} ${jo} ${se} ${re}`;this.anglePath.setAttribute("d",db);const jh=Math.abs(O),Bh=(f=k.instance.curDocument)==null?void 0:f.database,ub=Bh?Bh.formatter.formatAngle(jh,{showUnits:!0,applyAngbaseAngdir:!1}):`${(jh*180/Math.PI).toFixed(1)}°`,hb=v+w*Math.cos(j),pb=x+w*Math.sin(j);this.angleLabelEl.textContent=ub;const mb=40;this.angleLabelEl.style.left=`${hb-mb/2}px`,this.angleLabelEl.style.top=`${pb-12}px`,this.angleLabelEl.style.display=""}}dispose(){this.container&&this.container.remove(),this.container=null,this.baseLine=null,this.perpLineAtBase=null,this.perpLineAtCursor=null,this.connectorLine=null,this.labelEl=null,this.angleLabelEl=null,this.xAxisLine=null,this.angleSvg=null,this.anglePath=null}}const Xi=class Xi extends Si{constructor(e,t){super(e,t),this.lastPoint=null,this.suppressDisplay=!1,this.allowPrompt=t.allowPrompt!==!1,this.suppressDisplay=!this.isDynamicInputEnabled(),this.orthoReferencePoint=t.orthoReferencePoint??t.basePoint??void 0,t.disableOSnap||(this.osnapMarkerManager=new br(e)),t.basePoint&&(this.rubberBand=new Nl(e),this.rubberBand.start(t.basePoint,{color:"var(--ml-ui-canvas-line, #0f0)",showBaseLineOnly:t.showBaseLineOnly,baseAngle:t.baseAngle})),this.validateFn=t.validate,this.getDynamicValue=t.getDynamicValue,this.drawPreview=t.drawPreview,this.onCommit=t.onCommit,this.onChange=t.onChange,this.onCancel=t.onCancel,this.onNone=t.onNone,t.inputCount!==0&&(this.inputs=new Um({parent:this.container,twoInputs:t.inputCount===2,validate:this.validateFn,onCancel:this.onCancel,onNone:this.onNone,onCommit:this.onCommit,onChange:this.onChange,autoFocus:this.isDynamicInputEnabled(),allowNone:t.allowNone,useDefaultValue:t.useDefaultValue,defaultValue:t.defaultValue})),this.boundOnClick=i=>this.handleClick(i),this.parent.addEventListener("click",this.boundOnClick),this.boundOnInputSysVarChanged=i=>{var r;const n=(r=i.name)==null?void 0:r.toLowerCase();n===u.AcDbSystemVariables.DYNMODE.toLowerCase()||n===u.AcDbSystemVariables.DYNPROMPT.toLowerCase()?this.updateDynamicInputDisplay():(n===u.AcDbSystemVariables.ORTHOMODE.toLowerCase()||n===u.AcDbSystemVariables.POLARMODE.toLowerCase()||n===u.AcDbSystemVariables.POLARANG.toLowerCase()||n===u.AcDbSystemVariables.POLARADDANG.toLowerCase())&&this.requestPreviewRefresh()},u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.boundOnInputSysVarChanged),this.boundOnViewChanged=()=>this.requestPreviewRefresh(),this.view.events.viewChanged.addEventListener(this.boundOnViewChanged),this.view.events.viewResize.addEventListener(this.boundOnViewChanged),this.updateDynamicInputDisplay(),this.injectInputCSS()}showAt(e){if(this.disposed)return;if(this.updateDynamicInputDisplay(),!this.suppressDisplay){super.showAt(e);const i=this.view.screenToWorld(this.view.viewportToCanvas(e));this.updateDynamicPreview(i);return}this.visible=!0,this.container.style.display="none",this.setPosition(e),this.parent.addEventListener("mousemove",this.boundOnMouseMove);const t=this.view.screenToWorld(this.view.viewportToCanvas(e));this.updateDynamicPreview(t)}injectInputCSS(){if(Xi.inputStylesInjected)return;Xi.inputStylesInjected=!0;const e=document.createElement("style");e.textContent=`
541
+ `,document.head.appendChild(e)}get isVisible(){return this.visible}showAt(e){this.disposed||this.shouldShowPrompt()&&(this.visible=!0,this.container.style.display="flex",this.setPosition(e),this.parent.addEventListener("mousemove",this.boundOnMouseMove))}hide(){this.visible&&(this.visible=!1,this.container.style.display="none",this.parent.removeEventListener("mousemove",this.boundOnMouseMove))}dispose(){this.disposed||(this.disposed=!0,this.hide(),this.parent.removeEventListener("mouseenter",this.boundOnMouseEnter),this.parent.removeEventListener("mouseleave",this.boundOnMouseLeave),d.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.boundOnSysVarChanged),this.container.remove())}setPosition(e){const t=this.host.getBoundingClientRect(),i=this.container.getBoundingClientRect(),n=this.view.viewportToCanvas(e),r=this.view.viewportToContainer(e);let o=r.x+10,a=r.y+10;return o=Math.min(o,t.width-i.width),a=Math.min(a,t.height-i.height),o=Math.max(o,0),a=Math.max(a,0),this.container.style.left=`${o}px`,this.container.style.top=`${a}px`,n}handleMouseEnter(e){this.isHovering=!0,this.showAt(e)}handleMouseLeave(){this.isHovering=!1,this.hide()}handleMouseMove(e){this.visible&&this.setPosition(e)}getSysVarValue(e){const t=d.acdbHostApplicationServices().workingDatabase;return d.AcDbSysVarManager.instance().getVar(e,t)}isDynamicInputEnabled(){return this.getSysVarValue(d.AcDbSystemVariables.DYNMODE)!==0}isDynamicPromptEnabled(){return!!this.getSysVarValue(d.AcDbSystemVariables.DYNPROMPT)}shouldShowPrompt(){var t;return!(!!!((t=this.label.textContent)!=null&&t.trim())||!this.allowPrompt||!this.isDynamicInputEnabled()||!this.isDynamicPromptEnabled())}updateDynamicDisplay(){if(!this.shouldShowPrompt()){this.hide();return}this.isHovering&&this.showAt(this.view.canvasToViewport(this.view.curMousePos))}};Xi.stylesInjected=!1;let Pi=Xi;class Zl{constructor(e){this.container=null,this.baseLine=null,this.perpLineAtBase=null,this.perpLineAtCursor=null,this.connectorLine=null,this.labelEl=null,this.angleLabelEl=null,this.xAxisLine=null,this.angleSvg=null,this.anglePath=null,this.options={},this.view=e}get element(){return this.container}toContainerPoint(e){return this.view.canvasToContainer(this.view.worldToScreen(e))}ensureHostPositioned(){const e=this.view.container;getComputedStyle(e).position==="static"&&(e.style.position="relative")}start(e,t){this.basePoint=new d.AcGePoint3d(e),this.options=t||{};const i=this.options.color||"var(--ml-ui-canvas-line, #0f0)";this.ensureHostPositioned(),this.container=document.createElement("div"),this.container.style.position="absolute",this.container.style.left="0",this.container.style.top="0",this.container.style.width="100%",this.container.style.height="100%",this.container.style.pointerEvents="none",this.container.style.zIndex="1",this.view.container.appendChild(this.container),this.baseLine=document.createElement("div"),this.baseLine.style.position="absolute",this.baseLine.style.borderTop=`1px solid ${i}`,this.container.appendChild(this.baseLine);const n=()=>{const r=document.createElement("div");return r.style.position="absolute",r.style.borderTop=`1px dashed ${i}`,this.container.appendChild(r),r};this.options.showBaseLineOnly||(this.perpLineAtBase=n(),this.perpLineAtCursor=n(),this.connectorLine=n(),this.labelEl=document.createElement("div"),this.labelEl.style.position="absolute",this.labelEl.style.color=i,this.labelEl.style.fontSize="12px",this.labelEl.style.padding="2px 4px",this.labelEl.style.borderRadius="4px",this.container.appendChild(this.labelEl),this.xAxisLine=document.createElement("div"),this.xAxisLine.style.position="absolute",this.xAxisLine.style.borderTop=`1px solid ${i}`,this.container.appendChild(this.xAxisLine),this.angleSvg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.angleSvg.setAttribute("style","position:absolute; overflow:visible; pointer-events:none;"),this.anglePath=document.createElementNS("http://www.w3.org/2000/svg","path"),this.anglePath.setAttribute("fill","none"),this.anglePath.setAttribute("stroke",i),this.anglePath.setAttribute("stroke-width","1"),this.anglePath.setAttribute("stroke-dasharray","4 4"),this.angleSvg.appendChild(this.anglePath),this.container.appendChild(this.angleSvg),this.angleLabelEl=document.createElement("div"),this.angleLabelEl.style.position="absolute",this.angleLabelEl.style.color=i,this.angleLabelEl.style.fontSize="12px",this.angleLabelEl.style.padding="2px 4px",this.angleLabelEl.style.borderRadius="4px",this.container.appendChild(this.angleLabelEl))}update(e){var g,f;if(!this.container||!this.basePoint||!this.baseLine)return;const t=this.toContainerPoint(this.basePoint),i=this.toContainerPoint(e),n=(w,v,x)=>{const S=x.x-v.x,P=x.y-v.y,A=Math.sqrt(S*S+P*P),_=Math.atan2(P,S)*(180/Math.PI);w.style.width=`${A}px`,w.style.transformOrigin="0 0",w.style.transform=`translate(${v.x}px, ${v.y}px) rotate(${_}deg)`};if(n(this.baseLine,t,i),this.options.showBaseLineOnly||!this.perpLineAtBase||!this.perpLineAtCursor||!this.connectorLine)return;const r=i.x-t.x,o=i.y-t.y,a=Math.sqrt(r*r+o*o);if(a===0){this.perpLineAtBase&&(this.perpLineAtBase.style.width="0px"),this.perpLineAtCursor&&(this.perpLineAtCursor.style.width="0px"),this.connectorLine&&(this.connectorLine.style.width="0px"),this.xAxisLine&&(this.xAxisLine.style.width="0px"),this.anglePath&&this.anglePath.setAttribute("d",""),this.angleLabelEl&&(this.angleLabelEl.style.display="none");return}const l=this.options.perpendicularLength??50,c=-o/a,h=r/a,p={x:t.x+c*l,y:t.y+h*l},m={x:i.x+c*l,y:i.y+h*l};if(n(this.perpLineAtBase,t,p),n(this.perpLineAtCursor,i,m),n(this.connectorLine,p,m),this.labelEl){const w=(p.x+m.x)/2,v=(p.y+m.y)/2-24,x=Math.sqrt((e.x-this.basePoint.x)**2+(e.y-this.basePoint.y)**2),S=(g=k.instance.curDocument)==null?void 0:g.database;this.labelEl.textContent=S?S.formatter.formatLength(x):x.toFixed(3),this.labelEl.style.left=`${w-20}px`,this.labelEl.style.top=`${v}px`,this.labelEl.style.display=""}if(this.xAxisLine){const w=(this.options.baseAngle??0)*Math.PI/180,v={x:this.basePoint.x+Math.cos(w),y:this.basePoint.y+Math.sin(w),z:0},x=this.toContainerPoint(v),S=Math.atan2(x.y-t.y,x.x-t.x),P={x:t.x+a*Math.cos(S),y:t.y+a*Math.sin(S)};n(this.xAxisLine,t,P)}if(this.angleSvg&&this.anglePath&&this.angleLabelEl){const w=a,v=t.x,x=t.y,S=(this.options.baseAngle??0)*Math.PI/180,P={x:this.basePoint.x+Math.cos(S),y:this.basePoint.y+Math.sin(S),z:0},A=this.toContainerPoint(P),_=Math.atan2(A.y-t.y,A.x-t.x);let O=Math.atan2(i.y-t.y,i.x-t.x)-_;for(;O<=-Math.PI;)O+=Math.PI*2;for(;O>Math.PI;)O-=Math.PI*2;const B=_+O/2,I=v-w,N=x-w,G=w*2;this.angleSvg.style.left=`${I}px`,this.angleSvg.style.top=`${N}px`,this.angleSvg.setAttribute("width",`${G}`),this.angleSvg.setAttribute("height",`${G}`),this.angleSvg.setAttribute("viewBox",`0 0 ${G} ${G}`);const $=w,X=w,Y=$+w*Math.cos(_),Q=X+w*Math.sin(_),se=$+w*Math.cos(_+O),re=X+w*Math.sin(_+O),Ot=Math.abs(O)>Math.PI?"1":"0",Go=O>=0?"1":"0",Vb=`M ${Y} ${Q} A ${w} ${w} 0 ${Ot} ${Go} ${se} ${re}`;this.anglePath.setAttribute("d",Vb);const Zh=Math.abs(O),Xh=(f=k.instance.curDocument)==null?void 0:f.database,Gb=Xh?Xh.formatter.formatAngle(Zh,{showUnits:!0,applyAngbaseAngdir:!1}):`${(Zh*180/Math.PI).toFixed(1)}°`,Kb=v+w*Math.cos(B),Ub=x+w*Math.sin(B);this.angleLabelEl.textContent=Gb;const Hb=40;this.angleLabelEl.style.left=`${Kb-Hb/2}px`,this.angleLabelEl.style.top=`${Ub-12}px`,this.angleLabelEl.style.display=""}}dispose(){this.container&&this.container.remove(),this.container=null,this.baseLine=null,this.perpLineAtBase=null,this.perpLineAtCursor=null,this.connectorLine=null,this.labelEl=null,this.angleLabelEl=null,this.xAxisLine=null,this.angleSvg=null,this.anglePath=null}}const qi=class qi extends Pi{constructor(e,t){super(e,t),this.lastPoint=null,this.suppressDisplay=!1,this.allowPrompt=t.allowPrompt!==!1,this.suppressDisplay=!this.isDynamicInputEnabled(),this.orthoReferencePoint=t.orthoReferencePoint??t.basePoint??void 0,t.disableOSnap||(this.osnapMarkerManager=new Ar(e)),t.basePoint&&(this.rubberBand=new Zl(e),this.rubberBand.start(t.basePoint,{color:"var(--ml-ui-canvas-line, #0f0)",showBaseLineOnly:t.showBaseLineOnly,baseAngle:t.baseAngle})),this.validateFn=t.validate,this.getDynamicValue=t.getDynamicValue,this.drawPreview=t.drawPreview,this.onCommit=t.onCommit,this.onChange=t.onChange,this.onCancel=t.onCancel,this.onNone=t.onNone,t.inputCount!==0&&(this.inputs=new py({parent:this.container,twoInputs:t.inputCount===2,validate:this.validateFn,onCancel:this.onCancel,onNone:this.onNone,onCommit:this.onCommit,onChange:this.onChange,autoFocus:this.isDynamicInputEnabled(),allowNone:t.allowNone,useDefaultValue:t.useDefaultValue,defaultValue:t.defaultValue})),this.boundOnClick=i=>this.handleClick(i),this.parent.addEventListener("click",this.boundOnClick),this.boundOnInputSysVarChanged=i=>{var r;const n=(r=i.name)==null?void 0:r.toLowerCase();n===d.AcDbSystemVariables.DYNMODE.toLowerCase()||n===d.AcDbSystemVariables.DYNPROMPT.toLowerCase()?this.updateDynamicInputDisplay():(n===d.AcDbSystemVariables.ORTHOMODE.toLowerCase()||n===d.AcDbSystemVariables.POLARMODE.toLowerCase()||n===d.AcDbSystemVariables.POLARANG.toLowerCase()||n===d.AcDbSystemVariables.POLARADDANG.toLowerCase())&&this.requestPreviewRefresh()},d.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.boundOnInputSysVarChanged),this.boundOnViewChanged=()=>this.requestPreviewRefresh(),this.view.events.viewChanged.addEventListener(this.boundOnViewChanged),this.view.events.viewResize.addEventListener(this.boundOnViewChanged),this.updateDynamicInputDisplay(),this.injectInputCSS()}showAt(e){if(this.disposed)return;if(this.updateDynamicInputDisplay(),!this.suppressDisplay){super.showAt(e);const i=this.view.screenToWorld(this.view.viewportToCanvas(e));this.updateDynamicPreview(i);return}this.visible=!0,this.container.style.display="none",this.setPosition(e),this.parent.addEventListener("mousemove",this.boundOnMouseMove);const t=this.view.screenToWorld(this.view.viewportToCanvas(e));this.updateDynamicPreview(t)}injectInputCSS(){if(qi.inputStylesInjected)return;qi.inputStylesInjected=!0;const e=document.createElement("style");e.textContent=`
492
542
  .ml-floating-input input {
493
543
  font-size: 12px;
494
544
  padding: 2px 4px;
@@ -505,7 +555,7 @@
505
555
  border-color: var(--ml-ui-danger, red);
506
556
  color: var(--ml-ui-danger, red);
507
557
  }
508
- `,document.head.appendChild(e)}dispose(){var e,t,i;this.disposed||(super.dispose(),this.parent.removeEventListener("click",this.boundOnClick),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.boundOnInputSysVarChanged),this.view.events.viewChanged.removeEventListener(this.boundOnViewChanged),this.view.events.viewResize.removeEventListener(this.boundOnViewChanged),(e=this.inputs)==null||e.dispose(),(t=this.rubberBand)==null||t.dispose(),(i=this.osnapMarkerManager)==null||i.clear())}handleMouseMove(e){if(!this.visible)return;const t=this.getPosition(e);this.updateDynamicPreview(t)}requestPreviewRefresh(){!this.visible||!this.lastDynamicPoint||(this.updateDynamicPreview(this.lastDynamicPoint),this.osnapMarkerManager&&this.lastOsnapPoint&&this.osnapMarkerManager.repositionTop(this.lastOsnapPoint),!this.suppressDisplay&&this.view.curMousePos&&this.setPosition(this.view.canvasToViewport(this.view.curMousePos)))}handleClick(e){var r;if(!this.visible)return;const t=this.getPosition(e),i=this.getDynamicValue(t);(((r=this.onCommit)==null?void 0:r.call(this,i.value,t))??!0)&&(this.lastPoint=t)}setBasePoint(e,t){this.disposed||this.rubberBand||(this.rubberBand=new Nl(this.view),this.rubberBand.start(e,{color:(t==null?void 0:t.color)??"var(--ml-ui-canvas-line, #0f0)",showBaseLineOnly:t==null?void 0:t.showBaseLineOnly,baseAngle:t==null?void 0:t.baseAngle}),this.orthoReferencePoint=e,this.requestPreviewRefresh())}updateDynamicPreview(e){var i,n,r;this.lastDynamicPoint={x:e.x,y:e.y};const t=this.getDynamicValue(e);(i=this.inputs)==null||i.setValue(t.raw),this.inputs&&!this.inputs.focused&&!this.suppressDisplay&&this.inputs.focus(),(n=this.rubberBand)==null||n.update(e),(r=this.drawPreview)==null||r.call(this,e)}getPosition(e){const t=super.setPosition(e),i=this.view.screenToWorld(t);if(this.osnapMarkerManager&&(this.osnapMarkerManager.hideMarker(),this.lastOsnapPoint=this.view.osnapResolver.resolve({cursorWcs:i,lastPoint:this.lastPoint?{x:this.lastPoint.x,y:this.lastPoint.y,z:0}:void 0}),this.lastOsnapPoint&&(i.x=this.lastOsnapPoint.x,i.y=this.lastOsnapPoint.y,this.osnapMarkerManager.showMarker(this.lastOsnapPoint,Ut.osnapModeToMarkerType(this.lastOsnapPoint.type)))),this.orthoReferencePoint){const n=Il(i,this.orthoReferencePoint);i.x=n.x,i.y=n.y}return i}updateDynamicInputDisplay(){const e=this.isDynamicInputEnabled(),t=this.isDynamicPromptEnabled();this.setSuppressDisplay(!e),this.setPromptVisible(this.allowPrompt&&e&&t)}setSuppressDisplay(e){var t;this.suppressDisplay!==e&&(this.suppressDisplay=e,this.visible&&(this.suppressDisplay?(this.container.style.display="none",(t=this.inputs)==null||t.blur()):(this.container.style.display="flex",this.inputs&&!this.inputs.focused&&this.inputs.focus())))}setPromptVisible(e){var i;if(!!!((i=this.label.textContent)!=null&&i.trim())){this.label.style.display="none";return}this.label.style.display=e?"inline":"none"}};Xi.inputStylesInjected=!1;let Ar=Xi;class Pi extends Error{constructor(e){super("keyword"),this.keyword=e}}class Ai extends Error{constructor(){super("none")}}const qi=class qi{constructor(e){this.lastPoint=null,this._scriptInputs=[],this._modifierState={ctrlKey:!1,shiftKey:!1,altKey:!1,metaKey:!1},this._ctrlArcFlip=!1,this.active=!1,this.entitySelectionActive=!1,this._activeRejector=null,this.view=e,this.injectCSS(),getComputedStyle(this.view.container).position==="static"&&(this.view.container.style.position="relative");const i=new Bl(this.view.container);this._commandLine=i,i.visible=we.instance.isShowCommandLine,we.instance.events.modified.addEventListener(()=>{i.visible=we.instance.isShowCommandLine})}get isActive(){return this.active}get isEntitySelectionActive(){return this.entitySelectionActive}get modifiers(){return this._modifierState}get toggles(){return{ctrlArcFlip:this._ctrlArcFlip}}resetToggles(){this._ctrlArcFlip=!1}cancelActiveInput(){const e=this._activeRejector;e&&(this._activeRejector=null,e())}enqueueScriptInputs(e){e.length&&this._scriptInputs.push(...e)}clearScriptInputs(){this._scriptInputs.length=0}hasScriptInputs(){return this._scriptInputs.length>0}drainScriptInputs(){return this._scriptInputs.length?this._scriptInputs.splice(0,this._scriptInputs.length):[]}showMessage(e,t="info",i){this._commandLine.showMessage(e,t,i)}peekScriptInput(){return this._scriptInputs[0]}consumeScriptInput(){return this.dequeueScriptInput()}injectCSS(){if(qi.stylesInjected)return;qi.stylesInjected=!0;const e=document.createElement("style");e.textContent=`
558
+ `,document.head.appendChild(e)}dispose(){var e,t,i;this.disposed||(super.dispose(),this.parent.removeEventListener("click",this.boundOnClick),d.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.boundOnInputSysVarChanged),this.view.events.viewChanged.removeEventListener(this.boundOnViewChanged),this.view.events.viewResize.removeEventListener(this.boundOnViewChanged),(e=this.inputs)==null||e.dispose(),(t=this.rubberBand)==null||t.dispose(),(i=this.osnapMarkerManager)==null||i.clear(),this.view.osnapResolver.clearAcquiredCenters())}handleMouseMove(e){if(!this.visible)return;const t=this.getPosition(e);this.updateDynamicPreview(t)}requestPreviewRefresh(){var e;!this.visible||!this.lastDynamicPoint||(this.updateDynamicPreview(this.lastDynamicPoint),this.osnapMarkerManager&&this.lastOsnapPoint&&this.osnapMarkerManager.repositionTop(this.lastOsnapPoint),(e=this.osnapMarkerManager)==null||e.repositionHints(),!this.suppressDisplay&&this.view.curMousePos&&this.setPosition(this.view.canvasToViewport(this.view.curMousePos)))}handleClick(e){var r;if(!this.visible)return;const t=this.getPosition(e),i=this.getDynamicValue(t);(((r=this.onCommit)==null?void 0:r.call(this,i.value,t))??!0)&&(this.lastPoint=t)}setBasePoint(e,t){this.disposed||this.rubberBand||(this.rubberBand=new Zl(this.view),this.rubberBand.start(e,{color:(t==null?void 0:t.color)??"var(--ml-ui-canvas-line, #0f0)",showBaseLineOnly:t==null?void 0:t.showBaseLineOnly,baseAngle:t==null?void 0:t.baseAngle}),this.orthoReferencePoint=e,this.requestPreviewRefresh())}updateDynamicPreview(e){var i,n,r;this.lastDynamicPoint={x:e.x,y:e.y};const t=this.getDynamicValue(e);(i=this.inputs)==null||i.setValue(t.raw),this.inputs&&!this.inputs.focused&&!this.suppressDisplay&&this.inputs.focus(),(n=this.rubberBand)==null||n.update(e),(r=this.drawPreview)==null||r.call(this,e)}getPosition(e){const t=super.setPosition(e),i=this.view.screenToWorld(t);if(this.osnapMarkerManager&&(this.osnapMarkerManager.hideMarker(),this.lastOsnapPoint=this.view.osnapResolver.resolve({cursorWcs:i,lastPoint:this.lastPoint?{x:this.lastPoint.x,y:this.lastPoint.y,z:0}:void 0}),this.osnapMarkerManager.setHintMarkers(ft.displayCenterMarks(this.view.osnapResolver.acquiredCenterMarks,this.lastOsnapPoint)),this.lastOsnapPoint&&(i.x=this.lastOsnapPoint.x,i.y=this.lastOsnapPoint.y,this.osnapMarkerManager.showMarker(this.lastOsnapPoint,ft.osnapModeToMarkerType(this.lastOsnapPoint.type)))),this.orthoReferencePoint){const n=Vl(i,this.orthoReferencePoint);i.x=n.x,i.y=n.y}return i}updateDynamicInputDisplay(){const e=this.isDynamicInputEnabled(),t=this.isDynamicPromptEnabled();this.setSuppressDisplay(!e),this.setPromptVisible(this.allowPrompt&&e&&t)}setSuppressDisplay(e){var t;this.suppressDisplay!==e&&(this.suppressDisplay=e,this.visible&&(this.suppressDisplay?(this.container.style.display="none",(t=this.inputs)==null||t.blur()):(this.container.style.display="flex",this.inputs&&!this.inputs.focused&&this.inputs.focus())))}setPromptVisible(e){var i;if(!!!((i=this.label.textContent)!=null&&i.trim())){this.label.style.display="none";return}this.label.style.display=e?"inline":"none"}};qi.inputStylesInjected=!1;let Mr=qi;class Ai extends Error{constructor(e){super("keyword"),this.keyword=e}}class Ci extends Error{constructor(){super("none")}}const Ji=class Ji{constructor(e){this.lastPoint=null,this._scriptInputs=[],this._modifierState={ctrlKey:!1,shiftKey:!1,altKey:!1,metaKey:!1},this._ctrlArcFlip=!1,this.active=!1,this.entitySelectionActive=!1,this._activeRejector=null,this.view=e,this.injectCSS(),getComputedStyle(this.view.container).position==="static"&&(this.view.container.style.position="relative");const i=new Wl(this.view.container);this._commandLine=i,i.visible=ue.instance.isShowCommandLine,ue.instance.events.modified.addEventListener(()=>{i.visible=ue.instance.isShowCommandLine})}get isActive(){return this.active}get isEntitySelectionActive(){return this.entitySelectionActive}get modifiers(){return this._modifierState}get toggles(){return{ctrlArcFlip:this._ctrlArcFlip}}resetToggles(){this._ctrlArcFlip=!1}cancelActiveInput(){const e=this._activeRejector;e&&(this._activeRejector=null,e())}enqueueScriptInputs(e){e.length&&this._scriptInputs.push(...e)}clearScriptInputs(){this._scriptInputs.length=0}hasScriptInputs(){return this._scriptInputs.length>0}drainScriptInputs(){return this._scriptInputs.length?this._scriptInputs.splice(0,this._scriptInputs.length):[]}showMessage(e,t="info",i){this._commandLine.showMessage(e,t,i)}peekScriptInput(){return this._scriptInputs[0]}consumeScriptInput(){return this.dequeueScriptInput()}injectCSS(){if(Ji.stylesInjected)return;Ji.stylesInjected=!0;const e=document.createElement("style");e.textContent=`
509
559
  .ml-jig-preview-rect {
510
560
  position: absolute;
511
561
  border: 1px dashed var(--line-color, var(--ml-ui-canvas-line, #0f0));
@@ -521,8 +571,8 @@
521
571
  pointer-events: none;
522
572
  z-index: 1;
523
573
  }
524
- `,document.head.appendChild(e)}formatNumber(e,t){var n;const i=(n=k.instance.curDocument)==null?void 0:n.database;if(!i)switch(t){case"angle":return e.toFixed(2);case"distance":case"point":default:return e.toFixed(3)}switch(t){case"angle":return i.formatter.formatAngle(e*Math.PI/180,{applyAngbaseAngdir:!1});case"distance":case"point":default:return i.formatter.formatLength(e)}}hasKeywords(e){var i;return(((i=e.keywords)==null?void 0:i.toArray())??[]).length>0}buildKeywordOptions(e){var n;const t=new ne(e.message);return t.appendKeywordsToMessage=e.appendKeywordsToMessage,t.valueDefaultDisplayText=e.getDefaultValueDisplayText(),(((n=e.keywords)==null?void 0:n.toArray())??[]).forEach(r=>{const o=t.keywords.add(r.displayName,r.globalName,r.localName,r.enabled,r.visible);e.keywords.default===r&&(t.keywords.default=o)}),t}copyKeywords(e,t){var n;t.appendKeywordsToMessage=e.appendKeywordsToMessage,(((n=e.keywords)==null?void 0:n.toArray())??[]).forEach(r=>{const o=t.keywords.add(r.displayName,r.globalName,r.localName,r.enabled,r.visible);e.keywords.default===r&&(t.keywords.default=o)})}getEntityById(e){return k.instance.curDocument.database.tables.blockTable.getEntityById(e)}isEntityOnLockedLayer(e){var i;const t=e.layer;return t?!!((i=k.instance.curDocument.database.tables.layerTable.getAt(t))!=null&&i.isLocked):!1}isEntityClassAllowed(e,t){var r;const i=new Set;e.type&&i.add(e.type);const n=(r=e.constructor)==null?void 0:r.name;n&&i.add(n);for(const o of i)if(t.isClassAllowed(o))return!0;return!1}startKeywordSession(e,t){if(!this.hasKeywords(e))return;const i=this.buildKeywordOptions(e);return{promise:this._commandLine.getKeywords(i,t),cancel:()=>this._commandLine.cancelActiveSession()}}startPromptInputSession(e,t,i,n){const r=this.buildKeywordOptions(e),o="allowNone"in e?e.allowNone:!1;return{promise:this._commandLine.getPromptInput(r,a=>this.parseCommandLineInput(a,t,i,e),{mode:this.resolvePromptInputMode(t),allowNone:o,allowTyping:n}),cancel:()=>this._commandLine.cancelActiveSession()}}resolvePromptInputMode(e){return e instanceof Fn?"string":"geometric"}resolvePointInputContext(e){const t=this.resolvePromptDefaults(e);return{referencePoint:t.useBasePoint&&t.basePoint?t.basePoint:this.lastPoint??void 0,cursorPoint:this.view.screenToWorld(this.view.viewportToCanvas(this.view.curMousePos))}}parseCommandLineInput(e,t,i,n){const r=e.trim();if(!r)return null;const o=t instanceof xi||i===2?this.resolvePointInputContext(n):void 0;return t.parseCommandLine(r,o)}isPromptKeyword(e){return e instanceof Pi}mapPromptError(e,t){if(t.none&&this.isPromptNone(e))return t.none();if(t.cancel&&this.isPromptCancelled(e))return t.cancel();if(t.keyword&&this.isPromptKeyword(e))return t.keyword(e.keyword)}withKeywordResult(e,t){return e.stringResult=t,e}mapPromptErrorToResult(e,t,i){const n=(i==null?void 0:i.none)??!0,r=(i==null?void 0:i.cancel)??!0,o=(i==null?void 0:i.keyword)??!0;return this.mapPromptError(e,{none:n?()=>t(b.None):void 0,cancel:r?()=>t(b.Cancel):void 0,keyword:o?a=>this.withKeywordResult(t(b.Keyword),a):void 0})}async executePrompt(e,t,i,n){try{const r=await e();return t(r)}catch(r){const o=this.mapPromptErrorToResult(r,i,n);if(o)return o;throw r}}resolvePromptDefaultValue(e){return"useDefaultValue"in e&&"defaultValue"in e&&e.useDefaultValue?{useDefaultValue:!0,defaultValue:e.defaultValue}:{useDefaultValue:!1}}async getPoint(e){return this.executePrompt(()=>this.getPointInternal(e),t=>new Bn(b.OK,t),t=>new Bn(t))}getNumberTyped(e,t){const i=()=>({value:0,raw:{x:""}});return this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:i})}resolveDistanceBasePoint(e){if(e.useBasePoint&&e.basePoint)return{x:e.basePoint.x,y:e.basePoint.y}}createDistanceDynamicValue(e){return t=>{const i=t.x-e.x,n=t.y-e.y,r=Math.sqrt(i*i+n*n);return{value:r,raw:{x:this.formatNumber(r,"distance")}}}}async getDistanceTwoPoint(e,t){let i,n;const r=o=>i?this.createDistanceDynamicValue(i)(o):{value:0,raw:{x:""}};return await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:r,onFloatingInputCreated:o=>{n=o},onCommit:(o,a)=>i?!0:a?(i={x:a.x,y:a.y},n==null||n.setBasePoint(i,{showBaseLineOnly:!e.useDashedLine}),!1):!0})}async getDistance(e){const t=new Rm(e),i=this.tryGetScriptedNumber(t,e);if(i!=null)return new Se(b.OK,i);const n=this.resolveDistanceBasePoint(e);return this.executePrompt(async()=>n?await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:this.createDistanceDynamicValue(n)}):await this.getDistanceTwoPoint(e,t),r=>new Se(b.OK,r),r=>new Se(r))}async getAngle(e){const t=new Nm(e),i=this.tryGetScriptedNumber(t,e);if(i!=null)return new Se(b.OK,i);const n=e.useBasePoint&&e.basePoint?e.basePoint:this.lastPoint;if(!n)return this.executePrompt(()=>this.getNumberTyped(e,t),o=>new Se(b.OK,o),o=>new Se(o));const r=o=>{const a=o.x-n.x,l=o.y-n.y,c=Math.atan2(l,a),h=e.baseAngle*Math.PI/180;let p=c-h;for(;p<=-Math.PI;)p+=Math.PI*2;for(;p>Math.PI;)p-=Math.PI*2;const m=p*180/Math.PI;return{value:m,raw:{x:this.formatNumber(m,"angle")}}};return this.executePrompt(()=>this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:r}),o=>new Se(b.OK,o),o=>new Se(o))}async getDouble(e){const t=new Vm(e),i=this.tryGetScriptedNumber(t,e);return i!=null?new Se(b.OK,i):this.executePrompt(()=>this.getNumberTyped(e,t),n=>new Se(b.OK,n),n=>new Se(n))}async getInteger(e){const t=this.tryGetScriptedNumber(new Fl(e),e);return t!=null?new jn(b.OK,t):this.executePrompt(()=>this.getNumberTyped(e,new Fl(e)),i=>new jn(b.OK,i),i=>new jn(i))}async getString(e){const t=this.tryGetScriptedValue(new Fn(e),e);return t!=null?new Ie(b.OK,t):this.executePrompt(async()=>{const i=()=>({value:"",raw:{x:""}}),n=new Fn(e);return await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:n,getDynamicValue:i})},i=>new Ie(b.OK,i),i=>new Ie(i))}async getKeywords(e){return this.executePrompt(async()=>{const t=this.tryGetScriptedValue(new Sr(e),e);return t??new Promise((i,n)=>{const r=o=>{this._activeRejector===r&&(this._activeRejector=null),this._commandLine.cancelActiveSession(),n(o??new Error("cancelled"))};this._activeRejector=r,this._commandLine.getKeywords(e,!0).then(o=>{if(this._activeRejector===r&&(this._activeRejector=null),!o){n(e.allowNone?new Ai:new Error("cancelled"));return}i(o)},o=>{this._activeRejector===r&&(this._activeRejector=null),n(o)})})},t=>new Ie(b.OK,t),t=>new Ie(t),{keyword:!1})}async getSelection(e){return this.executePrompt(()=>new Promise((t,i)=>{this.active=!0,this.entitySelectionActive=!0;const n=this.startKeywordSession(e,!0);n||this._commandLine.setPrompt(e.message);const r=new Si(this.view,{parent:this.view.canvas,message:e.message}),o=new Set;let a=null,l=null,c=null,h=null;const p=_=>{if(!a||!c||!l)return;const C=this.view.screenToWorld(this.view.viewportToCanvas({x:_.clientX,y:_.clientY})),O=this.view.viewportToCanvas({x:_.clientX,y:_.clientY}),j=this.view.worldToScreen(a),L=this.view.worldToScreen(C),N=Math.min(j.x,L.x),R=Math.min(j.y,L.y),W=Math.abs(j.x-L.x),X=Math.abs(j.y-L.y),$=this.view.getSelectionMode(l,O),J=this.view.getSelectionActionFromEvent(_,"add"),se=this.view.getSelectionPreviewStyle($,J);Object.assign(c.style,{left:`${N}px`,top:`${R}px`,width:`${W}px`,height:`${X}px`,borderStyle:se.borderStyle,background:se.background}),c.style.setProperty("--line-color",se.lineColor)},m=()=>{h&&p(h)};let g=!1;const f=_=>{w(),i(_??new Error("cancelled"))},w=()=>{g||(g=!0,this.active=!1,this.entitySelectionActive=!1,this._activeRejector===f&&(this._activeRejector=null),r==null||r.dispose(),c==null||c.remove(),n==null||n.cancel(),this._commandLine.clear(),document.removeEventListener("keydown",v),this.view.canvas.removeEventListener("mousedown",S),this.view.canvas.removeEventListener("mousemove",P),this.view.canvas.removeEventListener("mouseup",A),this.view.canvas.removeEventListener("contextmenu",x),this.view.events.viewChanged.removeEventListener(m),this.view.events.viewResize.removeEventListener(m))};this._activeRejector=f,n==null||n.promise.then(_=>{if(!g){if(!_){f();return}f(new Pi(_))}});const v=_=>{if(_.key==="Escape"){f();return}_.key==="Enter"&&(w(),t([...o]))},x=_=>{this.shouldUseRightClickEnter()&&_.preventDefault()},S=_=>{if(_.button===2){this.shouldUseRightClickEnter()&&(_.preventDefault(),w(),t([...o]));return}_.button===0&&(l=this.view.viewportToCanvas({x:_.clientX,y:_.clientY}),a=this.view.screenToWorld(l),c=document.createElement("div"),c.className="ml-jig-preview-rect",this.view.container.appendChild(c))},P=_=>{_.buttons===1&&(!a||!c||!l||(h=_,p(_)))},A=_=>{if(_.button!==0||!a||!l)return;const C=this.view.screenToWorld(this.view.viewportToCanvas({x:_.clientX,y:_.clientY})),O=this.view.viewportToCanvas({x:_.clientX,y:_.clientY});c==null||c.remove(),c=null,h=null;const j=this.view.getSelectionActionFromEvent(_,"add");if(this.view.isSelectionClick(l,O)){const L=this.view.pick(C);L.length>0?this.view.applySelection([L[0].id],j):j==="replace"&&this.view.selectionSet.clear()}else{const L=new u.AcGeBox2d().expandByPoint(a).expandByPoint(C),N=this.view.getSelectionMode(l,O);this.view.selectByBoxWithMode(L,N,j)}o.clear();for(const L of this.view.selectionSet.ids)o.add(L);e.singleOnly&&j!=="remove"&&o.size>0&&(w(),t([...o])),a=null,l=null};document.addEventListener("keydown",v),this.view.canvas.addEventListener("mousedown",S),this.view.canvas.addEventListener("mousemove",P),this.view.canvas.addEventListener("mouseup",A),this.view.canvas.addEventListener("contextmenu",x),this.view.events.viewChanged.addEventListener(m),this.view.events.viewResize.addEventListener(m)}),t=>new ki(b.OK,new Tn(t)),t=>new ki(t),{none:!1})}async getEntity(e){let t;return this.executePrompt(()=>new Promise((i,n)=>{this.active=!0,this.entitySelectionActive=!0;const r=this.startKeywordSession(e,!0),o=new Si(this.view,{parent:this.view.canvas,message:e.message});r||this._commandLine.setPrompt(e.message);let a=!1;const l=f=>{c(),n(f??new Error("cancelled"))},c=()=>{var f;a||(a=!0,this.active=!1,this.entitySelectionActive=!1,this._activeRejector===l&&(this._activeRejector=null),(f=e.jig)==null||f.end(),document.removeEventListener("keydown",m),this.view.canvas.removeEventListener("mousedown",h),this.view.canvas.removeEventListener("click",p),this.view.canvas.removeEventListener("contextmenu",g),o==null||o.dispose(),r==null||r.cancel(),this._commandLine.clear())};this._activeRejector=l,r==null||r.promise.then(f=>{if(!a){if(!f){l();return}l(new Pi(f))}});const h=f=>{if(f.button===2){this.shouldUseRightClickEnter()&&e.allowNone&&(f.preventDefault(),c(),i(null));return}},p=f=>{if(f.button!==0)return;const w=this.view.screenToWorld(this.view.viewportToCanvas({x:f.clientX,y:f.clientY})),v=this.view.pick(w,void 0,!0);if(v.length==0){this._commandLine.showMessage(e.rejectMessage,"warning");return}const x=this.getEntityById(v[0].id);if(!x){this._commandLine.showMessage(e.rejectMessage,"warning");return}if(!e.allowObjectOnLockedLayer&&this.isEntityOnLockedLayer(x)){this._commandLine.showMessage(e.rejectMessage,"warning");return}if(!this.isEntityClassAllowed(x,e)){this._commandLine.showMessage(e.rejectMessage,"warning");return}t={x:w.x,y:w.y,z:0},c(),i(v[0].id)},m=f=>{if(f.key==="Escape"){l();return}f.key==="Enter"&&e.allowNone&&(c(),i(null))},g=f=>{this.shouldUseRightClickEnter()&&f.preventDefault()};document.addEventListener("keydown",m),this.view.canvas.addEventListener("mousedown",h),this.view.canvas.addEventListener("click",p),this.view.canvas.addEventListener("contextmenu",g)}),i=>new On(b.OK,i||void 0,t),i=>new On(i),{none:!1})}async getBox(e){return this.executePrompt(async()=>{const t=e.firstCornerMessage||d.t("main.inputManager.firstCorner"),i=new I(t);this.copyKeywords(e,i),i.useDashedLine=e.useDashedLine,i.useBasePoint=e.useBasePoint,i.disableOSnap=e.disableOSnap,i.allowNone=e.allowNone;const n=await this.getPoint(i);if(n.status!==b.OK)return new Mn(n.status,void 0,n.stringResult);const r=n.value,o=this.view.worldToScreen(r),a=document.createElement("div");a.className="ml-jig-preview-rect",this.view.container.appendChild(a);const l=()=>{a.remove()},c=f=>{const w=this.view.worldToScreen(f),v=Math.min(w.x,o.x),x=Math.min(w.y,o.y),S=Math.abs(w.x-o.x),P=Math.abs(w.y-o.y);Object.assign(a.style,{left:`${v}px`,top:`${x}px`,width:`${S}px`,height:`${P}px`})},h=e.secondCornerMessage||d.t("main.inputManager.secondCorner"),p=new I(h);this.copyKeywords(e,p),p.useDashedLine=e.useDashedLine,p.useBasePoint=e.useBasePoint,p.disableOSnap=e.disableOSnap;const m=await this.getPointInternal(p,l,c),g=new u.AcGeBox2d().expandByPoint(r).expandByPoint(m);return new Mn(b.OK,g)},t=>t,t=>new Mn(t))}async getPointInternal(e,t,i){const n=this.tryGetScriptedPoint(e);if(n!=null)return t==null||t(),Promise.resolve(n);const r=a=>({value:{x:a.x,y:a.y,z:0},raw:{x:this.formatNumber(a.x,"point"),y:this.formatNumber(a.y,"point")}}),o=new xi(e);return this.makeFloatingInputPromise({inputCount:2,promptOptions:e,disableOSnap:e.disableOSnap,cleanup:t,handler:o,getDynamicValue:r,drawPreview:i})}tryGetScriptedPoint(e){const t=this.dequeueScriptInput();if(t===void 0)return;const i=t.trim();if(!i&&e.allowNone)throw new Ai;const r=new xi(e).parseCommandLine(t,this.resolvePointInputContext(e));if(r!=null)return this.lastPoint={x:r.x,y:r.y},r;throw this.tryResolveScriptedKeyword(i,e),new Error(`Invalid point input '${t}'`)}tryResolveScriptedKeyword(e,t){if(!e||!(t!=null&&t.keywords))return;const i=t.keywords.findByName(e);if(i)throw new Pi(i.globalName)}tryGetScriptedValue(e,t){const i=this.dequeueScriptInput();if(i===void 0)return;const n=i.trim();if(!n&&t&&"allowNone"in t&&t.allowNone)throw new Ai;if(e instanceof Fn){this.tryResolveScriptedKeyword(n,t);const o=e.parse(i);if(o!=null)return o;throw new Error(`Invalid scripted input '${i}'`)}const r=this.parseCommandLineInput(i,e,e instanceof xi?2:1,t??new Ue(""));if(r!=null)return r;throw this.tryResolveScriptedKeyword(n,t),new Error(`Invalid scripted input '${i}'`)}tryGetScriptedNumber(e,t){return this.tryGetScriptedValue(e,t)}dequeueScriptInput(){if(this._scriptInputs.length)return this._scriptInputs.shift()}isPromptCancelled(e){return e instanceof Error&&e.message==="cancelled"}isPromptNone(e){return e instanceof Ai}getShortcutMenuMode(){const e=u.acdbHostApplicationServices().workingDatabase,t=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.SHORTCUTMENU,e),i=Math.trunc(Number(t));return Number.isNaN(i)?0:i&3}shouldUseRightClickEnter(){const e=this.getShortcutMenuMode();return e===0?!0:e===1?this.active:!1}updateModifierStateFromEvent(e){const t={ctrlKey:!!e.ctrlKey,shiftKey:!!e.shiftKey,altKey:!!e.altKey,metaKey:!!e.metaKey},i=this._modifierState,n=i.ctrlKey!==t.ctrlKey||i.shiftKey!==t.shiftKey||i.altKey!==t.altKey||i.metaKey!==t.metaKey;return n&&(this._modifierState=t),n}handleCtrlToggleKey(e){return e.key!=="Control"||e.repeat||e.type!=="keydown"?!1:(this._ctrlArcFlip=!this._ctrlArcFlip,!0)}resolvePromptDefaults(e){const t="basePoint"in e,i="useBasePoint"in e,n="useDashedLine"in e,r="baseAngle"in e,o=t&&e.basePoint?e.basePoint:void 0,a=i?e.useBasePoint:!1,l=n?!e.useDashedLine:!1,c=r?e.baseAngle:void 0;return{message:e.getDisplayMessage(),jig:e.jig,basePoint:o,useBasePoint:a,showBaseLineOnly:l,baseAngle:c}}async makeFloatingInputPromise(e){return new Promise((t,i)=>{var _;this.active=!0,this.entitySelectionActive=!1;let n=!1;const r=C=>{const O=e.handler.parse(C.x,C.y);return{isValid:O!=null,value:O??void 0}},o=this.resolvePromptDefaults(e.promptOptions),a=this.startPromptInputSession(e.promptOptions,e.handler,e.inputCount??1,!0);let l;o.useBasePoint&&o.basePoint&&(l=o.basePoint);const c=o.useBasePoint&&o.basePoint?o.basePoint:this.lastPoint??void 0,h="allowNone"in e.promptOptions?e.promptOptions.allowNone:!1,p=this.resolvePromptDefaultValue(e.promptOptions),m=new Ar(this.view,{parent:this.view.canvas,inputCount:e.inputCount,message:o.message,disableOSnap:e.disableOSnap,showBaseLineOnly:o.showBaseLineOnly,basePoint:l,orthoReferencePoint:c,baseAngle:o.baseAngle,allowPrompt:e.allowPrompt!==!1,allowNone:h,useDefaultValue:p.useDefaultValue,defaultValue:p.defaultValue,validate:r,getDynamicValue:e.getDynamicValue,drawPreview:C=>{var O;if(o.jig){const j=e.getDynamicValue(C);o.jig.update(j.value),o.jig.render()}(O=e.drawPreview)==null||O.call(e,C)},onCommit:(C,O)=>{let j=!1;return(!e.onCommit||e.onCommit(C,O))&&(f(C),j=!0),j&&m.lastPoint&&(this.lastPoint={x:m.lastPoint.x,y:m.lastPoint.y}),j},onCancel:()=>w(),onNone:()=>v()});(_=e.onFloatingInputCreated)==null||_.call(e,m);const g=()=>{var C,O;n||(n=!0,this.active=!1,this.entitySelectionActive=!1,this._activeRejector===w&&(this._activeRejector=null),(C=e.cleanup)==null||C.call(e),(O=o.jig)==null||O.end(),document.removeEventListener("keydown",S),document.removeEventListener("keydown",P),document.removeEventListener("keyup",P),this.view.canvas.removeEventListener("contextmenu",A),m.dispose(),a.cancel(),this._commandLine.clear())},f=C=>{g(),t(C)},w=C=>{g(),i(C??new Error("cancelled"))};this._activeRejector=w;const v=()=>{w(new Ai)},x=C=>{w(new Pi(C))},S=C=>{C.key==="Escape"&&w()},P=C=>{const O=this.handleCtrlToggleKey(C),j=this.updateModifierStateFromEvent(C);(O||j)&&m.requestPreviewRefresh()},A=C=>{this.shouldUseRightClickEnter()&&(C.preventDefault(),v())};document.addEventListener("keydown",S),document.addEventListener("keydown",P),document.addEventListener("keyup",P),this.view.canvas.addEventListener("contextmenu",A),m.showAt(this.view.canvasToViewport(this.view.curMousePos)),a.promise.then(C=>{if(!n)switch(C.kind){case"value":if(e.handler instanceof xi){const O=C.value;O&&Number.isFinite(O.x)&&Number.isFinite(O.y)&&(this.lastPoint={x:O.x,y:O.y})}f(C.value);break;case"keyword":x(C.keyword);break;case"none":h?v():w();break}})})}};qi.stylesInjected=!1;let zn=qi;class Rl{constructor(e){this.events={sysVarChanged:new u.AcCmEventManager,commandWillStart:new u.AcCmEventManager,commandEnded:new u.AcCmEventManager},this._view=e,this._cursorManager=new xl(e),this._inputManager=new zn(e)}get isActive(){return this._inputManager.isActive}get isEntitySelectionActive(){return this._inputManager.isEntitySelectionActive}getInputModifiers(){return this._inputManager.modifiers}getInputToggles(){return this._inputManager.toggles}resetInputToggles(){this._inputManager.resetToggles()}cancelActiveInput(){this._inputManager.cancelActiveInput()}enqueueScriptInputs(e){this._inputManager.enqueueScriptInputs(e)}clearScriptInputs(){this._inputManager.clearScriptInputs()}hasScriptInputs(){return this._inputManager.hasScriptInputs()}drainScriptInputs(){return this._inputManager.drainScriptInputs()}showMessage(e,t="info",i){this._inputManager.showMessage(e,t,i)}peekScriptInput(){return this._inputManager.peekScriptInput()}consumeScriptInput(){return this._inputManager.consumeScriptInput()}get currentCursor(){return this._currentCursor}restoreCursor(){this._previousCursor!=null&&this.setCursor(this._previousCursor)}setCursor(e){this._cursorManager.setCursor(e),this._previousCursor=this._currentCursor,this._currentCursor=e}async withCursor(e,t){const i=this._currentCursor;this.setCursor(e);try{return await Promise.resolve(t())}finally{i!==void 0?this.setCursor(i):this.restoreCursor()}}setCursorColor(e){this._cursorManager.setCursorColor(e)}syncCursorBackground(e){this._cursorManager.syncBackgroundColor(e)}async getPoint(e){return await this._inputManager.getPoint(e)}async getAngle(e){return await this._inputManager.getAngle(e)}async getDistance(e){return await this._inputManager.getDistance(e)}async getDouble(e){return await this._inputManager.getDouble(e)}async getInteger(e){return await this._inputManager.getInteger(e)}async getString(e){return await this._inputManager.getString(e)}async getKeywords(e){return await this._inputManager.getKeywords(e)}async getEntity(e){return await this._inputManager.getEntity(e)}async getSelection(e){return await this._inputManager.getSelection(e)}async getBox(e){return await this._inputManager.getBox(e)}selectAll(e){try{const t=k.instance.curDocument.database.tables.blockTable.modelSpace,i=[];for(const n of t.newIterator())(!e||e.matches(n))&&i.push(n.objectId);return new ki(b.OK,new Tn(i))}catch{return new ki(b.Error)}}}class Cr{constructor(e,t,i=1){if(this._handleIds=[],this.copyCount=Math.max(0,i),this.copyCount===0||t.length===0){this.useBatchPreview=!1;return}for(let n=0;n<this.copyCount;n++){const r=e.createEntityPreview(t);if(!r){this._handleIds.forEach(o=>e.removeEntityPreview(o)),this._handleIds.length=0,this.useBatchPreview=!1;return}this._handleIds.push(r),e.updateEntityPreview(r,new u.AcGeMatrix3d)}this.useBatchPreview=this._handleIds.length===this.copyCount}updateMatrix(e,t){!this.useBatchPreview||this._handleIds.length!==1||e.updateEntityPreview(this._handleIds[0],t)}updatePlacements(e,t,i){this.useBatchPreview&&this._handleIds.forEach((n,r)=>{const o=r+1,a=Nn(t,o,this.copyCount,i);e.updateEntityPreview(n,new u.AcGeMatrix3d().makeTranslation(a.x,a.y,a.z))})}dispose(e){this._handleIds.forEach(t=>e.removeEntityPreview(t)),this._handleIds.length=0}}function Nn(s,e,t,i){const n=i&&t>0?e/t:e;return new u.AcGePoint3d(s.x*n,s.y*n,s.z*n)}class Vl extends G{constructor(e,t){super(e),this._transientsPublished=!1,this._view=e,this.batchPreview=new Cr(e,t.map(i=>i.objectId)),this.previewEntities=this.batchPreview.useBatchPreview?[]:t.map(i=>i.clone()).filter(i=>!!i)}update(e){}render(){this.batchPreview.useBatchPreview||this.previewEntities.length!==0&&(this._transientsPublished||(this._view.addTransientEntity(this.previewEntities),this._transientsPublished=!0))}end(){this.batchPreview.dispose(this._view),this.previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}}class Wt extends G{constructor(e,t,i=1){super(e),this._transientsPublished=!1,this._lastTransforms=[],this._view=e,this.copyCount=i,this.batchPreview=new Cr(e,t.map(n=>n.objectId),i),this.previewEntries=this.batchPreview.useBatchPreview?[]:Wt.createPreviewEntries(t,i)}get previewEntities(){return this.previewEntries.map(e=>e.entity)}update(e){const t=this.buildTransforms(e);if(this.batchPreview.useBatchPreview){this.copyCount===1&&t.length>0&&this.batchPreview.updateMatrix(this._view,t[0].matrix);return}this._lastTransforms=t}render(){this.batchPreview.useBatchPreview||this.previewEntries.length!==0&&(this._transientsPublished||(this._view.addTransientEntity(this.previewEntities),this._transientsPublished=!0),this._lastTransforms.length>0&&this._view.updateTransientPreviewTransforms(this._lastTransforms))}end(){this.batchPreview.dispose(this._view),this.previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}static createPreviewEntries(e,t){const i=[];for(let n=1;n<=t;n++)e.map(r=>r.clone()).filter(r=>!!r).forEach(r=>{i.push({entity:r,copyFactor:n})});return i}}class We{constructor(e){this.state=e}setState(e){this.state=e}async run(e){for(;this.state;)try{const t=this.state.buildPrompt(),i=await e(t);if(await this.state.handleResult(i)==="finish")break}catch{break}}}class Hm{constructor(e=[]){this._typedValues=[...e]}get typedValues(){return[...this._typedValues]}matches(e){if(this._typedValues.length===0)return!0;let t="equals";for(const i of this._typedValues){if(i.code===u.AcDbDxfCode.Operator){t=this.parseOperator(i.value);continue}if(!this.matchTypedValue(e,i,t))return!1;t="equals"}return!0}parseOperator(e){switch(String(e??"").trim()){case"!=":case"<>":return"notEquals";case">":return"greaterThan";case">=":return"greaterThanOrEqual";case"<":return"lessThan";case"<=":return"lessThanOrEqual";case"=":case"==":default:return"equals"}}matchTypedValue(e,t,i){const n=this.resolveEntityValue(e,t.code);return n==null?!1:this.compare(n,t.value,i)}resolveEntityValue(e,t){var i;switch(t){case u.AcDbDxfCode.Start:return e.dxfTypeName||e.type;case u.AcDbDxfCode.LayerName:return e.layer;case u.AcDbDxfCode.ColorName:return(i=e.color)==null?void 0:i.toString();case u.AcDbDxfCode.LinetypeName:return e.lineType;case u.AcDbDxfCode.LineWeight:return Number(e.lineWeight);default:return}}compare(e,t,i){const n=Number(e),r=Number(t);if(Number.isFinite(n)&&Number.isFinite(r)&&`${e}`.trim()!==""&&`${t}`.trim()!=="")switch(i){case"equals":return n===r;case"notEquals":return n!==r;case"greaterThan":return n>r;case"greaterThanOrEqual":return n>=r;case"lessThan":return n<r;case"lessThanOrEqual":return n<=r}const a=String(e).toLowerCase(),l=String(t).toLowerCase();switch(i){case"equals":return a===l;case"notEquals":return a!==l;case"greaterThan":return a>l;case"greaterThanOrEqual":return a>=l;case"lessThan":return a<l;case"lessThanOrEqual":return a<=l}}}class Gl{constructor(e,t,i,n=500,r=500){this.host=e,this.hoverEvent=t,this.unhoverEvent=i,this.hoverDelay=n,this.pauseDelay=r,this.hoverTimer=null,this.pauseTimer=null,this.hoveredId=null}handleMouseMove(e,t){if(this.clearHoverTimer(),this.hoveredId){this.hoverAt(e,t);return}this.hoverTimer=setTimeout(()=>{this.hoverAt(e,t)},this.hoverDelay)}clear(){this.setHoveredId(null),this.clearHoverTimer(),this.clearPauseTimer()}dispose(){this.clearHoverTimer(),this.clearPauseTimer()}hoverAt(e,t){const i=this.host.pick({x:e,y:t});i.length>0?this.setHoveredId(i[0].id):this.clear()}setHoveredId(e){this.hoveredId!==e&&(this.hoveredId&&(this.unhoverEvent.dispatch({id:this.hoveredId,x:this.host.curMousePos.x,y:this.host.curMousePos.y}),this.host.onUnhover(this.hoveredId)),this.hoveredId=e,e&&(this.startPauseTimer(e),this.host.onHover(e)))}startPauseTimer(e){this.clearPauseTimer(),this.pauseTimer=setTimeout(()=>{this.hoverEvent.dispatch({id:e,x:this.host.curMousePos.x,y:this.host.curMousePos.y})},this.pauseDelay)}clearHoverTimer(){this.hoverTimer&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}clearPauseTimer(){this.pauseTimer&&(clearTimeout(this.pauseTimer),this.pauseTimer=null)}}function _r(s,e="replace"){return s.shiftKey?"remove":s.ctrlKey||s.metaKey?"add":e}function Kl(s){return _r(s,"add")}var me=(s=>(s[s.SELECTION=0]="SELECTION",s[s.PAN=1]="PAN",s))(me||{});class Ul{constructor(e,t){this.events={mouseMove:new u.AcCmEventManager,viewResize:new u.AcCmEventManager,viewChanged:new u.AcCmEventManager,hover:new u.AcCmEventManager,unhover:new u.AcCmEventManager,renderFrame:new u.AcCmEventManager},this._container=t,this._canvas=e;const i=e.getBoundingClientRect();this._bbox=new u.AcGeBox3d,this._width=i.width,this._height=i.height,this._curPos=new u.AcGePoint2d,this._curMousePos=new u.AcGePoint2d,this._selectionSet=new Tn,this._editor=new Rl(this),this._osnapResolver=new Ut(this),this._canvas.addEventListener("mousemove",a=>this.onMouseMove(a)),this._canvas.addEventListener("mousedown",a=>{a.button===1&&this._editor.setCursor(Ce.Grab)}),this._canvas.addEventListener("mouseup",a=>{a.button===1&&this._editor.restoreCursor()});const n=Bo.debounce(()=>this.onWindowResize(),0,{leading:!1,trailing:!0}),r=new ResizeObserver(n);r.observe(this._container);const o=this._container.parentElement;o&&r.observe(o),this._selectionBoxSize=4,this._hoverController=new Gl(this,this.events.hover,this.events.unhover)}get editor(){return this._editor}get selectionBoxSize(){return this._selectionBoxSize}set selectionBoxSize(e){this._selectionBoxSize=e}hasEntity(e){return!1}updateEntityVisibility(e){return!1}setEntitySceneVisible(e,t){return!1}getEntityVisible(e){}async withMode(e,t){const i=this.mode;this.mode=e;try{return await Promise.resolve(t())}finally{this.mode=i}}setCursor(e){this._editor.setCursor(e)}getSelectionMode(e,t){return t.x>=e.x?"window":"crossing"}getSelectionActionFromEvent(e,t="replace"){return _r(e,t)}isSelectionClick(e,t,i=2){const n=t.x-e.x,r=t.y-e.y;return Math.hypot(n,r)<i}getSelectionPreviewStyle(e,t){return{borderStyle:e==="window"?"solid":"dashed",lineColor:t==="remove"?"var(--ml-ui-danger, #ff4d4f)":e==="window"?"var(--ml-ui-canvas-line, #00ff5a)":"var(--ml-ui-accent-alt, #00d1ff)",background:"var(--ml-ui-canvas-fill-mix, var(--ml-ui-canvas-fill, rgba(64, 158, 255, 0.12)))"}}applySelection(e,t){if(t==="replace"){this.selectionSet.clear();const i=e.filter(n=>!this.selectionSet.has(n));i.length>0&&this.selectionSet.add(i);return}if(e.length!==0)if(t==="add"){const i=e.filter(n=>!this.selectionSet.has(n));i.length>0&&this.selectionSet.add(i)}else{const i=e.filter(n=>this.selectionSet.has(n));i.length>0&&this.selectionSet.delete(i)}}selectByBoxWithMode(e,t,i="add"){const n=this.collectSelectionIdsByBox(e,t);this.applySelection(n,i)}collectSelectionIdsByBox(e,t){const i=this.search(e,{selectionMode:t}),n=[];return i.forEach(r=>{xn(r)&&n.push(r.id)}),n}setCalculateSizeCallback(e){this._calculateSizeCallback=e}get width(){return this._width}set width(e){this._width=e}get height(){return this._height}set height(e){this._height=e}get bbox(){return this._bbox}get canvas(){return this._canvas}get container(){return this._container}viewportToCanvas(e){const t=this._canvas.getBoundingClientRect();return new u.AcGePoint2d(e.x-t.left,e.y-t.top)}canvasToViewport(e){const t=this._canvas.getBoundingClientRect();return new u.AcGePoint2d(e.x+t.left,e.y+t.top)}canvasToContainer(e){const t=this._canvas.getBoundingClientRect(),i=this._container.getBoundingClientRect();return new u.AcGePoint2d(e.x+(t.left-i.left),e.y+(t.top-i.top))}viewportToContainer(e){const t=this._container.getBoundingClientRect();return new u.AcGePoint2d(e.x-t.left,e.y-t.top)}get aspect(){return this._width/this._height}get curPos(){return this._curPos}get curMousePos(){return this._curMousePos}get selectionSet(){return this._selectionSet}get osnapResolver(){return this._osnapResolver}onWindowResize(){if(this._calculateSizeCallback){const{width:e,height:t}=this._calculateSizeCallback();this._width=Math.max(1,Math.floor(e)),this._height=Math.max(1,Math.floor(t))}else this._width=Math.max(1,Math.floor(this._canvas.clientWidth)),this._height=Math.max(1,Math.floor(this._canvas.clientHeight));this.events.viewResize.dispatch({width:this._width,height:this._height})}clearHover(){this._hoverController.clear()}onMouseMove(e){this._curMousePos=this.viewportToCanvas({x:e.clientX,y:e.clientY});const t=this.screenToWorld(this._curMousePos);this._curPos.copy(t),this.events.mouseMove.dispatch({x:t.x,y:t.y}),this.mode==0&&(this._editor.isActive||this._hoverController.handleMouseMove(t.x,t.y))}}function $t(s,e){return new u.AcGeMatrix3d().makeTranslation(s.x,s.y,s.z).multiply(new u.AcGeMatrix3d().makeRotationZ(e)).multiply(new u.AcGeMatrix3d().makeTranslation(-s.x,-s.y,-s.z))}const Er=new Set;function Hl(s,e="drawing"){const t=s==null?void 0:s.trim();return t&&(t.split(/[\\/]/).pop()??t).replace(/\.[^.]+$/,"").trim()||e}function Lr(s,e,t="drawing"){const i=Hl(s,t),n=e.startsWith(".")?e:`.${e}`;let r=0,o=`${i}${n}`;for(;Er.has(o);)r+=1,o=`${i}-${r+1}${n}`;return Er.add(o),o}function Wm(){Er.clear()}const $m=64,Ne=class Ne{static clearCache(){this._cache.clear(),this._cacheDocId=void 0}static bindDocListener(){this._docListenerBound||(this._docListenerBound=!0,k.instance.events.documentActivated.addEventListener(()=>{this.clearCache()}))}capture(e,t=$m){Ne.bindDocListener();const i=e.trim();if(!i)return;const n=k.instance.curDocument,r=n==null?void 0:n.database,o=k.instance.curView;if(!r||!o)return;const a=n.database.tables.blockTable.modelSpace.objectId;Ne._cacheDocId!==a&&(Ne._cache.clear(),Ne._cacheDocId=a);const l=r.tables.blockTable.getAt(i);if(!l||l.isXref)return;const c=`${a}\0${l.objectId}\0${t}`,h=Ne._cache.get(c);if(h)return h;const p=this.fromStoredIcon(l);if(p)return Ne._cache.set(c,p),p;const m=this.fromGeometry(l,o,t);return m&&Ne._cache.set(c,m),m}fromStoredIcon(e){var t;if((t=e.previewIcon)!=null&&t.length)return u.acdbPreviewIconToDataUrl(e.previewIcon)}fromGeometry(e,t,i){const n=t.renderer;let r=null;try{const o=new u.AcDbBlockReference(e.name);o.database=e.database;const a=o.worldDraw(n);if(a)r=a;else{const c=new u.AcCmColor;c.setForeground(),r=u.AcDbRenderingCache.instance.draw(n,e,c,[],!1)}if(!r)return;r.syncDraw();const l=n.renderEntityPreview(r,{width:i,height:i,margin:1.15,localLineResolutionOnly:!0,viewportSize:{width:t.width,height:t.height},onRestored:()=>{t.isDirty=!0}});return l?l.canvas.toDataURL("image/png"):void 0}catch(o){console.warn("[BlockPreview] Failed to capture",e.name,o);return}finally{r==null||r.dispose()}}};Ne._cache=new Map,Ne._docListenerBound=!1;let Tr=Ne;class Wl{convert(){const e=k.instance.curDocument,t=e.database.dxfOut(void 0,6),i=this.getBaseName(e.fileName||e.docTitle);this.createFileAndDownloadIt(t,`${i}.dxf`)}createFileAndDownloadIt(e,t){const i=typeof e=="string"?e:new Uint8Array(e),n=new Blob([i],{type:"application/dxf;charset=utf-8"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}getBaseName(e){return((e==null?void 0:e.trim())||"drawing").replace(/\.[^.]+$/,"")||"drawing"}}class $l extends z{async execute(e){await this.withBusyIndicator(()=>{new Wl().convert()},d.t("main.message.exportingDxf"))}}class Yl{async convert(e,t){const i=k.instance.curView;await i.waitUntilIdle()||console.warn("[PNGOUT] Timed out waiting for scene idle; exporting current geometry");const r=i.activeLayoutView,o=i.renderer,a=o.internalRenderer,l=i.internalScene,c=i.internalCamera;if(!l||!c||!r){console.error("[PNGOUT] Scene or camera not available");return}const h=i.width/Math.max(i.height,1),p=e?this.getBoundsAspect(e):h;let m=Math.max(1,Math.round(i.width)),g=Math.max(1,Math.round(i.height));if(t&&t>0){const W=this.resolveOutputSize(t,p);m=W.width,g=W.height}const f=e?{width:m,height:g}:this.resolveRenderSizeForCenterCrop(m,g,h),w=f.width,v=f.height,x=!e&&(w!==m||v!==g),S=c.zoom,P=c.position.clone(),A=c.left,_=c.right,C=c.top,O=c.bottom,j=a.getScissorTest(),L=a.getPixelRatio(),N=a.getRenderTarget();let R;try{e&&r.applyExportCamera(e,w,v),a.setPixelRatio(1),o.updateLineResolution(w,v),R=new T.WebGLRenderTarget(w,v,{minFilter:T.LinearFilter,magFilter:T.LinearFilter,format:T.RGBAFormat,type:T.UnsignedByteType}),a.setRenderTarget(R),a.setViewport(0,0,w,v),a.setScissorTest(!1),r.renderObject(l);const W=new Uint8Array(w*v*4);a.readRenderTargetPixels(R,0,0,w,v,W);const X=this.flipPixelsVertically(W,w,v),$=x?this.cropPixelsCentered(X,w,v,m,g):X,J=this.createCanvasFromPixels($,m,g);this.createFileAndDownloadIt(J)}finally{a.setRenderTarget(N),R==null||R.dispose(),c.zoom=S,c.position.copy(P),c.left=A,c.right=_,c.top=C,c.bottom=O,c.updateProjectionMatrix(),a.setPixelRatio(L),o.setSize(i.width,i.height),a.setScissorTest(j),o.syncCameraZoom(S),r.render(i.cadScene),i.isDirty=!0}}resolveOutputSize(e,t){const i=Math.max(1,Math.round(e)),n=Number.isFinite(t)&&t>Number.EPSILON?t:1;return n>=1?{width:i,height:Math.max(1,Math.round(i/n))}:{width:Math.max(1,Math.round(i*n)),height:i}}resolveRenderSizeForCenterCrop(e,t,i){const n=Number.isFinite(i)&&i>Number.EPSILON?i:1,r=e/Math.max(t,1);return Math.abs(r-n)<1e-6?{width:e,height:t}:n>r?{width:Math.max(e,Math.ceil(t*n)),height:t}:{width:e,height:Math.max(t,Math.ceil(e/n))}}cropPixelsCentered(e,t,i,n,r){if(t===n&&i===r)return e;const o=Math.floor((t-n)/2),a=Math.floor((i-r)/2),l=new Uint8Array(n*r*4);for(let c=0;c<r;c++){const h=((c+a)*t+o)*4,p=h+n*4,m=c*n*4;l.set(e.subarray(h,p),m)}return l}getBoundsAspect(e){const t=new u.AcGeVector2d;e.getSize(t);const i=Math.max(Math.abs(t.x),Number.EPSILON),n=Math.max(Math.abs(t.y),Number.EPSILON);return i/n}flipPixelsVertically(e,t,i){const n=new Uint8Array(t*i*4);for(let r=0;r<i;r++){const o=(i-1-r)*t*4,a=r*t*4;for(let l=0;l<t*4;l++)n[a+l]=e[o+l]}return n}createCanvasFromPixels(e,t,i){const n=document.createElement("canvas");n.width=t,n.height=i;const r=n.getContext("2d"),o=r.createImageData(t,i);return o.data.set(e),r.putImageData(o,0,0),n}createFileAndDownloadIt(e){const t=k.instance.curDocument,i=Lr(t.fileName||t.docTitle,"png"),n=e.toDataURL("image/png"),r=document.createElement("a");r.href=n,r.download=i,document.body.appendChild(r),r.click(),document.body.removeChild(r)}}const Zl=1024;class Xl extends z{async execute(e){const t=new Yl,i=k.instance.curView;this.syncActiveLayoutViewSize(i);const n=new In(d.t("jig.pngout.boundsFirstCorner"),d.t("jig.pngout.boundsSecondCorner"));n.disableOSnap=!0,n.allowNone=!0;const r=await k.instance.editor.getBox(n);let o;if(r.status===b.OK&&r.value)o=r.value;else if(r.status===b.None)o=this.getCurrentDrawingBounds();else return;const a=new ie(d.t("jig.pngout.longSidePrompt"));a.allowNone=!0,a.allowNegative=!1,a.allowZero=!1,a.defaultValue=Zl,a.useDefaultValue=!0;const l=await k.instance.editor.getDouble(a);if(l.status===b.Cancel||l.status===b.Error)return;const c=l.status===b.OK&&l.value!==void 0?l.value:Zl;await t.convert(o,c)}getCurrentDrawingBounds(){const t=k.instance.curDocument.database.extents;return new u.AcGeBox2d(new u.AcGePoint2d(t.min.x,t.min.y),new u.AcGePoint2d(t.max.x,t.max.y))}syncActiveLayoutViewSize(e){const t=e.activeLayoutView;t&&t.resize(e.width,e.height)}}class ql{export(e,t){const i=this.capture(e,t);return i.ok?this.downloadDataUrl(i.dataUrl)?{ok:!0,exportedCount:i.exportedCount,skippedCount:i.skippedCount}:{ok:!1,reason:"download-failed"}:i.reason==="no-entities"?{ok:!1,reason:"no-bounds"}:i.reason==="download-failed"?{ok:!1,reason:"capture-failed"}:{ok:!1,reason:i.reason}}capture(e,t){if(e.length===0)return{ok:!1,reason:"no-entities"};const i=k.instance.curView,n=i.cadScene,o=n.findPreviewableEntityIds(e,"all").length,a=e.length-o,l=n.computeEntityPreviewBounds2d(e,1.1,"all")??null;if(!l)return console.warn("[ENTPREVIEW] Failed to compute preview bounds",e),{ok:!1,reason:"no-bounds"};const c=this.resolveOutputSize(t,this.getBoundsAspect(l)),h=c.width,p=c.height,m=n.createEntityPreviewRoot(e,{scope:"all"});if(!m)return console.warn("[ENTPREVIEW] Failed to build preview geometry",`${e.length} requested entity ids`),{ok:!1,reason:"no-preview-root"};const g=i.renderer;try{const f=g.renderEntityPreview(m,{width:h,height:p,bounds:l,margin:1,viewportSize:{width:i.width,height:i.height},localLineResolutionOnly:!0,onRestored:()=>{i.isDirty=!0}});return f?{ok:!0,dataUrl:f.canvas.toDataURL("image/png"),exportedCount:o,skippedCount:a}:{ok:!1,reason:"capture-failed"}}catch(f){return console.error("[ENTPREVIEW] Failed to render preview image",f),{ok:!1,reason:"capture-failed"}}finally{M.disposePreviewSubset(m)}}resolveOutputSize(e,t){const i=Math.max(1,Math.round(e)),n=Number.isFinite(t)&&t>Number.EPSILON?t:1;return n>=1?{width:i,height:Math.max(1,Math.round(i/n))}:{width:Math.max(1,Math.round(i*n)),height:i}}getBoundsAspect(e){const t=new u.AcGeVector2d;e.getSize(t);const i=Math.max(Math.abs(t.x),Number.EPSILON),n=Math.max(Math.abs(t.y),Number.EPSILON);return i/n}downloadDataUrl(e){try{const t=k.instance.curDocument,i=Lr(t.fileName||t.docTitle,"png","entity-preview"),n=document.createElement("a");return n.href=e,n.download=i,document.body.appendChild(n),n.click(),document.body.removeChild(n),!0}catch(t){return console.error("[ENTPREVIEW] Failed to download preview PNG",t),!1}}}const Jl=512;class Ql extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.selectionSet;let i=t.count>0?t.ids:[];if(i.length===0){const c=new xt(d.sysCmdPrompt("entout")),h=await k.instance.editor.getSelection(c);if(h.status!==b.OK||!h.value||h.value.count===0)return;i=h.value.ids}const n=new ie(d.t("jig.entout.longSidePrompt"));n.allowNone=!0,n.allowNegative=!1,n.allowZero=!1,n.defaultValue=Jl,n.useDefaultValue=!0;const r=await k.instance.editor.getDouble(n);if(r.status===b.Cancel||r.status===b.Error)return;const o=r.status===b.OK&&r.value!==void 0?r.value:Jl,a=k.instance.curView;this.syncActiveLayoutViewSize(a);const l=await this.withBusyIndicator(()=>new ql().export(i,o),d.t("main.message.exportingEntityPreview"));if(l.ok){let c=`${l.exportedCount} ${d.t("jig.entout.exported")}`;l.skippedCount>0&&(c+=`, ${l.skippedCount} ${d.t("jig.entout.skipped")}`),this.showMessage(c,"success");return}this.showMessage(d.t(`jig.entout.failed.${l.reason}`),"error")}syncActiveLayoutViewSize(e){const t=e.activeLayoutView;t&&t.resize(e.width,e.height)}}class ec{constructor(e){this.events={changed:new u.AcCmEventManager},this.layers=[],this.currentLayerName="",this.handleLayerAppended=t=>{this.upsertLayerInfo(t.layer)},this.handleLayerErased=t=>{this.removeLayerInfo(t.layer.name)},this.handleLayerModified=t=>{const i=this.findLayerInfo(t.layer.name);if(!i){this.upsertLayerInfo(t.layer);return}Object.assign(i,this.toLayerInfo(t.layer)),this.notify()},this.handleSysVarChanged=t=>{t.database===this.database&&t.name.toUpperCase()==="CLAYER"&&this.syncCurrentLayerName()},this.document=e,this.database=e.database,u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.handleSysVarChanged),this.bindDatabase()}destroy(){u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.handleSysVarChanged),this.unbindDatabase(),this.layers=[],this.currentLayerName=""}getLayers(){return[...this.layers]}getCurrentLayerName(){return this.currentLayerName}setLayerOn(e,t){return this.getLayerService().setLayerOn(e,t,{switchCurrentLayer:!0})}setAllLayersOn(){return this.getLayerService().setAllLayersOn()>0}setAllLayersOffExceptCurrent(){return this.getLayerService().setAllLayersOffExceptCurrent()>0}setLayerColor(e,t){return this.getLayerService().setLayerColor(e,t)}setCurrentLayer(e){const t=this.getLayerService().setCurrentLayer(e);return t&&this.syncCurrentLayerName(),t}setLayerFrozen(e,t){return this.getLayerService().setLayerFrozen(e,t,{switchCurrentLayer:!0})}setLayerLocked(e,t){return this.getLayerService().setLayerLocked(e,t)}setLayerLineWeight(e,t){return this.getLayerService().setLayerLineWeight(e,t)}setLayerPlottable(e,t){return this.getLayerService().setLayerPlottable(e,t)}setLayerLinetype(e,t){return this.getLayerService().setLayerLinetype(e,t)}setLayerTransparency(e,t){return this.getLayerService().setLayerTransparency(e,t)}setLayerDescription(e,t){return this.getLayerService().setLayerDescription(e,t)}isolateSingleLayer(e){return this.getLayerService().isolateSingleLayer(e)}getLayerService(){return this.document.layerService}toLayerInfo(e){return{name:e.name,color:e.color.toString(),cssColor:e.color.cssColor||"#FFFFFF",isOn:!e.isOff,isFrozen:e.isFrozen,isLocked:te.isLayerLocked(e)}}rebuildLayerCache(){this.layers=[];for(const e of this.database.tables.layerTable.newIterator())this.layers.push(this.toLayerInfo(e))}findLayerInfo(e){return this.layers.find(t=>t.name===e)}removeLayerInfo(e){const t=this.layers.findIndex(i=>i.name===e);t!==-1&&(this.layers.splice(t,1),this.notify())}upsertLayerInfo(e){const t=this.findLayerInfo(e.name),i=this.toLayerInfo(e);t?Object.assign(t,i):this.layers.push(i),this.notify()}syncCurrentLayerName(e=!0){const t=this.database.clayer||"";this.currentLayerName!==t&&(this.currentLayerName=t,e&&this.notify())}notify(){this.events.changed.dispatch({layers:this.getLayers(),currentLayerName:this.currentLayerName})}bindDatabase(){this.rebuildLayerCache(),this.currentLayerName=this.database.clayer||"",this.notify(),this.database.events.layerAppended.addEventListener(this.handleLayerAppended),this.database.events.layerErased.addEventListener(this.handleLayerErased),this.database.events.layerModified.addEventListener(this.handleLayerModified)}unbindDatabase(){this.database.events.layerAppended.removeEventListener(this.handleLayerAppended),this.database.events.layerErased.removeEventListener(this.handleLayerErased),this.database.events.layerModified.removeEventListener(this.handleLayerModified)}}class Ir{constructor(e){this.db=e}getEntitiesByIds(e){return e.map(t=>this.db.tables.blockTable.getEntityById(t)).filter(t=>!!t)}transformEntities(e,t){let i=0;return e.forEach(n=>{const r=this.db.openEntityForWrite(n);r&&(r.transformBy(t),i++)}),i}translateEntities(e,t){const i=new u.AcGeMatrix3d().makeTranslation(t.x,t.y,t.z);return this.transformEntities(e,i)}rotateEntities(e,t,i){const n=$t(t,i);return this.transformEntities(e,n)}cloneAndTransform(e,t,i={}){const n=i.append??!0,r=e.map(o=>o.clone()).filter(o=>!!o);return r.forEach(o=>o.transformBy(t)),n&&r.length>0&&this.db.tables.blockTable.modelSpace.appendEntity(r),r}eraseEntities(e){let t=0;return e.forEach(i=>{const n=this.db.openEntityForWrite(i);n&&(n.erase(),t++)}),t}moveEntitiesToCurrentLayer(e){var a;const t=(a=this.db.clayer)==null?void 0:a.trim(),i=t?this.db.tables.layerTable.getAt(t):void 0;if(!i)return{changedCount:0,alreadyCurrent:0,missing:0,currentLayerMissing:!0};let n=0,r=0,o=0;return new Set(e).forEach(l=>{const c=this.db.tables.blockTable.getEntityById(l);if(!c){o++;return}if(c.layer===i.name){r++;return}const h=this.db.openEntityForWrite(l);if(!h){o++;return}h.layer=i.name,n++}),{changedCount:n,alreadyCurrent:r,missing:o,currentLayerMissing:!1}}static copyDisplayTraits(e,t){t.layer=e.layer,t.color=e.color.clone(),t.lineType=e.lineType,t.lineWeight=e.lineWeight,t.linetypeScale=e.linetypeScale,t.transparency=e.transparency,t.visibility=e.visibility}runEdit(e,t){K(this.db,e,t)}runEntityEdit(e){K(this.db,Ja,e)}}async function tc(s){const e=await k.instance.editor.getSelection(new xt(d.sysCmdPrompt(s)));if(!(e.status!==b.OK||!e.value||e.value.count===0))return e.value.ids}async function Rn(s,e={}){const t=s.view.selectionSet,i=s.doc.database.tables.blockTable,n=e.clearOnEmpty??!0;let r;if(t.count>0?r=t.ids:e.promptKey&&(r=await tc(e.promptKey)),!r||r.length===0)return;const o=[],a=[];for(const l of r){const c=i.getEntityById(l);c&&(o.push(c),a.push(l))}if(o.length===0){n&&t.clear();return}return{entities:o,ids:a}}async function ic(s,e){const t=s.view.selectionSet;if(t.count>0)return t.ids;const i=await tc(e);return i&&i.length>0?i:void 0}const Ym="layerp";class _e extends z{shouldRecordUndoStack(e){return this.recordsUndoStack}onCommandWillStart(e){this.globalName.toLowerCase()!==Ym&&e.doc.captureLayerPreviousState()}}class nc extends _e{constructor(){super(),this._history=[],this.mode=F.Write}async execute(e){for(this._history=[];;){const t=await this.promptMainAction();if(!t)return;if(t.type==="keyword"){t.keyword==="Name"?await this.runNameBranch(e):this.runUndo(e);continue}this.deleteLayerByEntity(e,t.objectId)}}addKeyword(e,t){e.keywords.add(d.t(`jig.laydel.keywords.${t}.display`),d.t(`jig.laydel.keywords.${t}.global`),d.t(`jig.laydel.keywords.${t}.local`))}async promptMainAction(){const e=new He(d.t("jig.laydel.selectPrompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(d.t("jig.laydel.invalidSelection")),this.addKeyword(e,"name"),this.addKeyword(e,"undo");const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===b.Keyword&&(t.stringResult==="Name"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runNameBranch(e){for(;;){const t=await this.promptLayerNameAction();if(!t)return;if(t.type==="keyword"){t.keyword==="?"?this.listLayers(e):this.runUndo(e);continue}this.deleteLayerByName(e,t.layerName)}}async promptLayerNameAction(){const e=new le(d.t("jig.laydel.namePrompt"));e.allowSpaces=!0,e.allowEmpty=!0,this.addKeyword(e,"list"),this.addKeyword(e,"undo");const t=await k.instance.editor.getString(e);if(t.status===b.Keyword&&(t.stringResult==="?"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult};if(t.status!==b.OK)return;const i=(t.stringResult??"").trim();if(i)return{type:"name",layerName:i}}listLayers(e){const t=new te(e.doc.database).getLayerSummaries();console.table(t),this.showMessage(d.t("jig.laydel.layerListSummary"),"info")}deleteLayerByEntity(e,t){var r;const i=e.doc.database.tables.blockTable.getEntityById(t),n=(r=i==null?void 0:i.layer)==null?void 0:r.trim();if(!n){this.showMessage(d.t("jig.laydel.invalidSelection"),"warning");return}this.deleteLayerByName(e,n)}deleteLayerByName(e,t){const i=new te(e.doc.database).deleteLayer(t);if(!i.ok)switch(i.reason){case"not_found":this.showMessage(`${d.t("jig.laydel.layerNotFound")}: ${t}`);return;case"layer_0":this.showMessage(d.t("jig.laydel.cannotDeleteZeroLayer"),"warning");return;case"current_layer":this.showMessage(d.t("jig.laydel.cannotDeleteCurrent"),"warning");return}this._history.push({layer:i.layer,entities:i.entities}),e.view.selectionSet.clear(),k.instance.regen(),this.showMessage(`${d.t("jig.laydel.deleted")}: ${i.layerName}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.showMessage(d.t("jig.laydel.nothingToUndo"),"warning");return}new te(e.doc.database).restoreDeletedLayer(t.layer,t.entities),e.view.selectionSet.clear(),k.instance.regen(),this.showMessage(`${d.t("jig.laydel.restored")}: ${t.layer.name}`,"success")}}class sc extends _e{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.view.selectionSet,i=t.count>0?t.ids:await this.promptSelection();if(!i||i.length===0)return;const n=e.doc.entityService.moveEntitiesToCurrentLayer(i);if(n.currentLayerMissing){this.showMessage(d.t("jig.laycur.currentLayerNotFound"),"warning");return}if(n.changedCount===0){this.showMessage(n.alreadyCurrent>0?d.t("jig.laycur.alreadyCurrent"):d.t("jig.laycur.noObjects"),n.alreadyCurrent>0&&n.missing===0?"info":"warning");return}e.view.selectionSet.clear(),k.instance.regen(),this.showMessage(`${d.t("jig.laycur.changed")}: ${n.changedCount} (${e.doc.database.clayer})`,"success")}async promptSelection(){var i;const e=new xt(d.t("jig.laycur.prompt")),t=await k.instance.editor.getSelection(e);if(t.status===b.OK)return((i=t.value)==null?void 0:i.ids)??[]}}const Zm={viewportMode:"Freeze",blockSelectionMode:"None"},Xe=class Xe extends _e{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=F.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=Xe._settings.viewportMode!=="Vpfreeze";;){const t=await this.promptSelection();if(!t)return;if(t.type==="keyword"){t.keyword==="Settings"?await this.runSettings():this.runUndo(e);continue}this.freezeEntityLayer(e,t.objectId)}}addKeyword(e,t){e.keywords.add(d.t(`jig.layfrz.keywords.${t}.display`),d.t(`jig.layfrz.keywords.${t}.global`),d.t(`jig.layfrz.keywords.${t}.local`))}async promptSelection(){const e=new He(d.t("jig.layfrz.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(d.t("jig.layfrz.invalidSelection")),this.addKeyword(e,"settings"),this.addKeyword(e,"undo");const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===b.Keyword&&(t.stringResult==="Settings"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runSettings(){for(;;){const e=new ne(d.t("jig.layfrz.settingsPrompt"));e.allowNone=!0,this.addKeyword(e,"viewports"),this.addKeyword(e,"blockSelection");const t=await k.instance.editor.getKeywords(e);if(t.status!==b.OK)return;const i=t.stringResult;if(!i)return;i==="Viewports"?await this.promptViewportMode():await this.promptBlockSelectionMode()}}async promptViewportMode(){const e=new ne(d.t("jig.layfrz.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(d.t("jig.layfrz.keywords.freeze.display"),d.t("jig.layfrz.keywords.freeze.global"),d.t("jig.layfrz.keywords.freeze.local")),i=e.keywords.add(d.t("jig.layfrz.keywords.vpfreeze.display"),d.t("jig.layfrz.keywords.vpfreeze.global"),d.t("jig.layfrz.keywords.vpfreeze.local"));e.keywords.default=Xe._settings.viewportMode==="Vpfreeze"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;r&&(Xe._settings.viewportMode=r,r==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.showMessage(d.t("jig.layfrz.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new ne(d.t("jig.layfrz.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(d.t("jig.layfrz.keywords.block.display"),d.t("jig.layfrz.keywords.block.global"),d.t("jig.layfrz.keywords.block.local")),i=e.keywords.add(d.t("jig.layfrz.keywords.entity.display"),d.t("jig.layfrz.keywords.entity.global"),d.t("jig.layfrz.keywords.entity.local")),n=e.keywords.add(d.t("jig.layfrz.keywords.none.display"),d.t("jig.layfrz.keywords.none.global"),d.t("jig.layfrz.keywords.none.local"));e.keywords.default=Xe._settings.blockSelectionMode==="Block"?t:Xe._settings.blockSelectionMode==="Entity"?i:n;const r=await k.instance.editor.getKeywords(e);if(r.status!==b.OK)return;const o=r.stringResult;o&&(Xe._settings.blockSelectionMode=o,this.showMessage(d.t("jig.layfrz.nestedSelectionLimited")))}freezeEntityLayer(e,t){const n=new te(e.doc.database).freezeLayerByEntity(t);if(!n.ok){switch(n.reason){case"invalid_selection":this.showMessage(d.t("jig.layfrz.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${d.t("jig.layfrz.layerNotFound")}: ${n.layerName}`,"warning");return;case"cannot_change_current":this.showMessage(d.t("jig.layfrz.cannotFreezeCurrent"),"warning");return;case"already_frozen":this.showMessage(`${d.t("jig.layfrz.alreadyFrozen")}: ${n.layerName}`,"info");return}return}Xe._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.showMessage(d.t("jig.layfrz.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:n.layerName,wasFrozen:n.previousFrozen??!1}),e.view.selectionSet.clear(),this.showMessage(`${d.t("jig.layfrz.frozen")}: ${n.layerName}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.showMessage(d.t("jig.layfrz.nothingToUndo"),"warning");return}if(!new te(e.doc.database).setLayerFrozenByName(t.layerName,t.wasFrozen)){this.showMessage(`${d.t("jig.layfrz.layerNotFound")}: ${t.layerName}`,"warning");return}e.view.selectionSet.clear(),this.showMessage(`${d.t("jig.layfrz.restored")}: ${t.layerName}`,"success")}};Xe._settings={...Zm};let Vn=Xe;const Xm={isolationMode:"Off",offMode:"Off"},Ae=class Ae extends _e{constructor(){super(),this._vpfreezeHintShown=!1,this._lockFadeHintShown=!1,this.mode=F.Write}async execute(e){this._vpfreezeHintShown=Ae._settings.offMode!=="Vpfreeze",this._lockFadeHintShown=Ae._settings.isolationMode!=="LockAndFade";const t=e.view.selectionSet.ids;if(t.length>0){this.isolateSelectedObjectLayers(e,t);return}for(;;){const i=await this.promptSelection();if(!i)return;if(i.type==="keyword"){await this.runSettings();continue}this.isolateSelectedObjectLayers(e,i.objectIds);return}}addKeyword(e,t){e.keywords.add(d.t(`jig.layiso.keywords.${t}.display`),d.t(`jig.layiso.keywords.${t}.global`),d.t(`jig.layiso.keywords.${t}.local`))}async promptSelection(){var i;const e=new xt(d.t("jig.layiso.prompt"));this.addKeyword(e,"settings");const t=await k.instance.editor.getSelection(e);if(t.status===b.OK)return{type:"selection",objectIds:((i=t.value)==null?void 0:i.ids)??[]};if(t.status===b.Keyword&&t.stringResult==="Settings")return{type:"keyword",keyword:t.stringResult}}async runSettings(){const e=new ne(d.t("jig.layiso.settingsPrompt"));e.allowNone=!0;const t=e.keywords.add(d.t("jig.layiso.keywords.off.display"),d.t("jig.layiso.keywords.off.global"),d.t("jig.layiso.keywords.off.local")),i=e.keywords.add(d.t("jig.layiso.keywords.lockAndFade.display"),d.t("jig.layiso.keywords.lockAndFade.global"),d.t("jig.layiso.keywords.lockAndFade.local"));e.keywords.default=Ae._settings.isolationMode==="LockAndFade"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;if(r){if(Ae._settings.isolationMode=r,r==="Off"){await this.promptOffMode();return}this._lockFadeHintShown=!0,this.showMessage(d.t("jig.layiso.lockFadeFallback"))}}async promptOffMode(){const e=new ne(d.t("jig.layiso.offModePrompt"));e.allowNone=!0;const t=e.keywords.add(d.t("jig.layiso.keywords.off.display"),d.t("jig.layiso.keywords.off.global"),d.t("jig.layiso.keywords.off.local")),i=e.keywords.add(d.t("jig.layiso.keywords.vpfreeze.display"),d.t("jig.layiso.keywords.vpfreeze.global"),d.t("jig.layiso.keywords.vpfreeze.local"));e.keywords.default=Ae._settings.offMode==="Vpfreeze"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;r&&(Ae._settings.offMode=r,r==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.showMessage(d.t("jig.layiso.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}isolateSelectedObjectLayers(e,t){const i=new te(e.doc.database),{layerNames:n,missingLayerNames:r}=i.collectLayerNamesFromEntities(t);if(r.length>0&&this.showMessage(`${d.t("jig.layiso.layerNotFound")}: ${r.join(", ")}`,"warning"),n.length===0){this.showMessage(d.t("jig.layiso.noLayers"),"warning");return}const o=e.doc.isolateLayers(n,Ae._settings.isolationMode);if(!o){this.showMessage(d.t("jig.layiso.noLayers"),"warning");return}Ae._settings.isolationMode==="Off"&&Ae._settings.offMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.showMessage(d.t("jig.layiso.vpfreezeFallback")),this._vpfreezeHintShown=!0),Ae._settings.isolationMode==="LockAndFade"&&!this._lockFadeHintShown&&(this.showMessage(d.t("jig.layiso.lockFadeFallback")),this._lockFadeHintShown=!0),e.view.selectionSet.clear(),this.showMessage(`${d.t("jig.layiso.isolated")}: ${n.join(", ")} (${d.t("jig.layiso.affectedLayers")}: ${o.affectedLayerCount})`,"success")}};Ae._settings={...Xm};let Gn=Ae;class rc extends _e{constructor(){super(),this.mode=F.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.lockEntityLayer(e,t)}}async promptSelection(){const e=new He(d.t("jig.laylck.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(d.t("jig.laylck.invalidSelection"));const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return t.objectId}lockEntityLayer(e,t){const i=new te(e.doc.database).lockLayerByEntity(t);if(!i.ok)switch(i.reason){case"invalid_selection":this.showMessage(d.t("jig.laylck.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${d.t("jig.laylck.layerNotFound")}: ${i.layerName}`,"warning");return;case"already_locked":this.showMessage(`${d.t("jig.laylck.alreadyLocked")}: ${i.layerName}`,"info");return}e.view.selectionSet.clear(),this.showMessage(`${d.t("jig.laylck.locked")}: ${i.layerName}`,"success")}}class oc extends _e{constructor(){super(),this.mode=F.Write}async execute(e){const t=new te(e.doc.database).setAllLayersOn();if(e.view.selectionSet.clear(),t===0){this.showMessage(d.t("jig.layon.alreadyOn"));return}this.showMessage(`${d.t("jig.layon.turnedOn")}: ${t}`,"success")}}const qm={viewportMode:"Off",blockSelectionMode:"None"},qe=class qe extends _e{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=F.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=qe._settings.viewportMode!=="Vpfreeze";;){const t=await this.promptSelection();if(!t)return;if(t.type==="keyword"){t.keyword==="Settings"?await this.runSettings():this.runUndo(e);continue}this.turnOffEntityLayer(e,t.objectId)}}addKeyword(e,t){e.keywords.add(d.t(`jig.layoff.keywords.${t}.display`),d.t(`jig.layoff.keywords.${t}.global`),d.t(`jig.layoff.keywords.${t}.local`))}async promptSelection(){const e=new He(d.t("jig.layoff.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(d.t("jig.layoff.invalidSelection")),this.addKeyword(e,"settings"),this.addKeyword(e,"undo");const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===b.Keyword&&(t.stringResult==="Settings"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runSettings(){for(;;){const e=new ne(d.t("jig.layoff.settingsPrompt"));e.allowNone=!0,this.addKeyword(e,"viewports"),this.addKeyword(e,"blockSelection");const t=await k.instance.editor.getKeywords(e);if(t.status!==b.OK)return;const i=t.stringResult;if(!i)return;i==="Viewports"?await this.promptViewportMode():await this.promptBlockSelectionMode()}}async promptViewportMode(){const e=new ne(d.t("jig.layoff.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(d.t("jig.layoff.keywords.off.display"),d.t("jig.layoff.keywords.off.global"),d.t("jig.layoff.keywords.off.local")),i=e.keywords.add(d.t("jig.layoff.keywords.vpfreeze.display"),d.t("jig.layoff.keywords.vpfreeze.global"),d.t("jig.layoff.keywords.vpfreeze.local"));e.keywords.default=qe._settings.viewportMode==="Vpfreeze"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;r&&(qe._settings.viewportMode=r,r==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.showMessage(d.t("jig.layoff.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new ne(d.t("jig.layoff.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(d.t("jig.layoff.keywords.block.display"),d.t("jig.layoff.keywords.block.global"),d.t("jig.layoff.keywords.block.local")),i=e.keywords.add(d.t("jig.layoff.keywords.entity.display"),d.t("jig.layoff.keywords.entity.global"),d.t("jig.layoff.keywords.entity.local")),n=e.keywords.add(d.t("jig.layoff.keywords.none.display"),d.t("jig.layoff.keywords.none.global"),d.t("jig.layoff.keywords.none.local"));e.keywords.default=qe._settings.blockSelectionMode==="Block"?t:qe._settings.blockSelectionMode==="Entity"?i:n;const r=await k.instance.editor.getKeywords(e);if(r.status!==b.OK)return;const o=r.stringResult;o&&(qe._settings.blockSelectionMode=o,this.showMessage(d.t("jig.layoff.nestedSelectionLimited")))}turnOffEntityLayer(e,t){const n=new te(e.doc.database).turnOffLayerByEntity(t);if(!n.ok){switch(n.reason){case"invalid_selection":this.showMessage(d.t("jig.layoff.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${d.t("jig.layoff.layerNotFound")}: ${n.layerName}`,"warning");return;case"cannot_change_current":this.showMessage(d.t("jig.layoff.cannotTurnOffCurrent"),"warning");return;case"already_off":this.showMessage(`${d.t("jig.layoff.alreadyOff")}: ${n.layerName}`,"info");return}return}qe._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.showMessage(d.t("jig.layoff.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:n.layerName,wasOff:n.previousOff??!1}),e.view.selectionSet.clear(),this.showMessage(`${d.t("jig.layoff.turnedOff")}: ${n.layerName}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.showMessage(d.t("jig.layoff.nothingToUndo"),"warning");return}if(!new te(e.doc.database).setLayerOffByName(t.layerName,t.wasOff)){this.showMessage(`${d.t("jig.layoff.layerNotFound")}: ${t.layerName}`,"warning");return}e.view.selectionSet.clear(),this.showMessage(`${d.t("jig.layoff.restored")}: ${t.layerName}`,"success")}};qe._settings={...qm};let Kn=qe;class ac extends _e{constructor(){super(),this.mode=F.Write}async execute(e){e.doc.restoreLayerPreviousState()?this.showMessage(d.t("jig.layerp.restored"),"success"):this.showMessage(d.t("jig.layerp.noPreviousState")),e.view.selectionSet.clear()}}class lc extends _e{constructor(){super(),this.mode=F.Write}async execute(e){const t=new te(e.doc.database).thawAllLayers();if(e.view.selectionSet.clear(),t===0){this.showMessage(d.t("jig.laythw.alreadyThawed"));return}this.showMessage(`${d.t("jig.laythw.thawed")}: ${t}`,"success")}}class cc extends _e{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.doc.unisolateLayers();if(t===void 0){this.showMessage(d.t("jig.layuniso.noPrevious"),"warning");return}if(e.view.selectionSet.clear(),t===0){this.showMessage(d.t("jig.layuniso.nothingRestored"));return}this.showMessage(`${d.t("jig.layuniso.restored")}: ${t}`,"success")}}class dc extends _e{constructor(){super(),this.mode=F.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.unlockEntityLayer(e,t)}}async promptSelection(){const e=new He(d.t("jig.layulk.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(d.t("jig.layulk.invalidSelection"));const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return t.objectId}unlockEntityLayer(e,t){const i=new te(e.doc.database).unlockLayerByEntity(t);if(!i.ok)switch(i.reason){case"invalid_selection":this.showMessage(d.t("jig.layulk.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${d.t("jig.layulk.layerNotFound")}: ${i.layerName}`,"warning");return;case"already_unlocked":this.showMessage(`${d.t("jig.layulk.alreadyUnlocked")}: ${i.layerName}`,"info");return}e.view.selectionSet.clear(),this.showMessage(`${d.t("jig.layulk.unlocked")}: ${i.layerName}`,"success")}}class uc extends z{async execute(e){Q.emit("close-layer-manager",{})}}class hc extends _e{constructor(){super(),this.mode=F.Write}async execute(e){for(;;){const t=await this.promptMainKeyword();if(!t)return;switch(t){case"?":this.listLayers(e);break;case"Make":await this.runMake(e);break;case"Set":await this.runSet(e);break;case"New":await this.runNew(e);break;case"On":await this.runOnOff(e,!1);break;case"Off":await this.runOnOff(e,!0);break;case"Color":await this.runColor(e);break;case"Freeze":await this.runFreeze(e,!0);break;case"Thaw":await this.runFreeze(e,!1);break;case"Lock":await this.runLock(e,!0);break;case"Unlock":await this.runLock(e,!1);break;case"Description":await this.runDescription(e);break}}}layerService(e){return new te(e.doc.database)}async promptMainKeyword(){const e=new ne(d.t("jig.layer.main"));e.allowNone=!0,this.addKeyword(e,"list"),this.addKeyword(e,"make"),this.addKeyword(e,"set"),this.addKeyword(e,"new"),this.addKeyword(e,"on"),this.addKeyword(e,"off"),this.addKeyword(e,"color"),this.addKeyword(e,"freeze"),this.addKeyword(e,"thaw"),this.addKeyword(e,"lock"),this.addKeyword(e,"unlock"),this.addKeyword(e,"description");const t=await k.instance.editor.getKeywords(e);if(t.status===b.OK)return t.stringResult}addKeyword(e,t){e.keywords.add(d.t(`jig.layer.keywords.${t}.display`),d.t(`jig.layer.keywords.${t}.global`),d.t(`jig.layer.keywords.${t}.local`))}listLayers(e){const t=this.layerService(e).getLayerSummaries();console.table(t),this.showMessage(`${d.t("jig.layer.listSummary")} (${t.length})`,"info")}async promptLayerNames(e,t){const i=new le(e);i.allowSpaces=!1;const n=await k.instance.editor.getString(i);if(n.status!==b.OK)return;const o=this.layerService(t).parseLayerNameInput(n.stringResult??"");if(!o.length){this.showMessage(d.t("jig.layer.emptyInput"),"warning");return}return o}async promptSingleLayerName(e){const t=new le(e);t.allowSpaces=!0;const i=await k.instance.editor.getString(t);return i.status!==b.OK?void 0:(i.stringResult??"").trim()||void 0}async runNew(e){const t=await this.promptLayerNames(d.t("jig.layer.newPrompt"),e);if(!t)return;const{created:i,existed:n}=this.layerService(e).createLayers(t);i>0&&this.showMessage(`${d.t("jig.layer.created")}: ${i}`,"success"),n.length>0&&this.showMessage(`${d.t("jig.layer.alreadyExists")}: ${n.join(", ")}`,"warning")}async runSet(e){const t=await this.promptSingleLayerName(d.t("jig.layer.setPrompt"));t&&(this.layerService(e).setCurrentLayer(t)||this.showMessage(`${d.t("jig.layer.notFound")}: ${t}`,"warning"))}async runMake(e){const t=await this.promptSingleLayerName(d.t("jig.layer.makePrompt"));t&&this.layerService(e).makeLayer(t)}async runOnOff(e,t){const i=await this.promptLayerNames(t?d.t("jig.layer.offPrompt"):d.t("jig.layer.onPrompt"),e);if(!i)return;const n=this.layerService(e),{missing:r}=n.resolveLayers(i);r.length>0&&this.showMessage(`${d.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const{skippedCurrent:o}=n.setLayersVisibility(i,t);o.length>0&&this.showMessage(d.t("jig.layer.cannotChangeCurrent"),"warning")}async runFreeze(e,t){const i=await this.promptLayerNames(t?d.t("jig.layer.freezePrompt"):d.t("jig.layer.thawPrompt"),e);if(!i)return;const n=this.layerService(e),{missing:r}=n.resolveLayers(i);r.length>0&&this.showMessage(`${d.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const{skippedCurrent:o}=n.setLayersFrozen(i,t);o.length>0&&this.showMessage(d.t("jig.layer.cannotChangeCurrent"),"warning")}async runLock(e,t){const i=await this.promptLayerNames(t?d.t("jig.layer.lockPrompt"):d.t("jig.layer.unlockPrompt"),e);if(!i)return;const n=this.layerService(e),{missing:r}=n.resolveLayers(i);r.length>0&&this.showMessage(`${d.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning"),n.setLayersLocked(i,t)}async runColor(e){const t=await this.promptLayerNames(d.t("jig.layer.colorLayerPrompt"),e);if(!t)return;const i=this.layerService(e),{layers:n,missing:r}=i.resolveLayers(t);if(r.length>0&&this.showMessage(`${d.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning"),n.length===0)return;const o=new le(d.t("jig.layer.colorValuePrompt"));o.allowSpaces=!1;const a=await k.instance.editor.getString(o);if(a.status!==b.OK)return;const l=i.parseColorInput(a.stringResult??"");if(!l){this.showMessage(d.t("jig.layer.invalidColor"),"warning");return}i.setLayersColor(t,l)}async runDescription(e){const t=await this.promptSingleLayerName(d.t("jig.layer.descriptionLayerPrompt"));if(!t)return;const i=new le(d.t("jig.layer.descriptionValuePrompt"));i.allowSpaces=!0,i.allowEmpty=!0;const n=await k.instance.editor.getString(i);n.status===b.OK&&(this.layerService(e).setLayerDescription(t,n.stringResult??"")||this.showMessage(`${d.t("jig.layer.notFound")}: ${t}`,"warning"))}}const Jm={x:0,y:0,z:1},Qm={x:0,y:0,z:-1};function Un(s){const e=s%u.TAU;return e>=0?e:e+u.TAU}function mt(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function Mr(s,e){return Math.atan2(e.y-s.y,e.x-s.x)*180/Math.PI}function Me(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=t===1?Math.atan2(n,i):Math.atan2(n,-i);return Un(r)}function pc(s){return s===1?Jm:Qm}function mc(s){return s.normal.z>=0?1:-1}function Ci(s){return new u.AcDbArc(s.center,s.radius,s.startAngle,s.endAngle,pc(s.normalSign))}function yc(s,e){s.center=e.center,s.radius=e.radius,s.startAngle=e.startAngle,s.endAngle=e.endAngle,s.normal=pc(e.normalSign)}function De(s){return{center:{x:s.x,y:s.y,z:0},radius:1e-6,startAngle:0,endAngle:Math.PI/2,normalSign:1}}function ey(s,e,t){const i=t.x-s.x,n=t.y-s.y,r=Math.hypot(i,n);if(u.AcGeTol.isNonPositive(r))return;const o=e/r;return{x:s.x+i*o,y:s.y+n*o,z:0}}function gc(s,e,t){const i=Un(t-s);return Un(e-s)<=i+1e-7}function ty(s,e,t,i){const n=Me(s,e,1),r=Me(s,t,1),o=Me(s,i,1),a=gc(n,r,o),l=Me(s,e,-1),c=Me(s,t,-1),h=Me(s,i,-1),p=gc(l,c,h);return a&&!p?1:!a&&p?-1:(t.x-e.x)*(i.y-e.y)-(t.y-e.y)*(i.x-e.x)>=0?1:-1}function fc(s,e,t,i=!1){const n=s.x,r=s.y,o=e.x,a=e.y,l=t.x,c=t.y,h=2*(n*(a-c)+o*(c-r)+l*(r-a));if(u.AcGeTol.equalToZero(h))return;const p=((n*n+r*r)*(a-c)+(o*o+a*a)*(c-r)+(l*l+c*c)*(r-a))/h,m=((n*n+r*r)*(l-o)+(o*o+a*a)*(n-l)+(l*l+c*c)*(o-n))/h,g={x:p,y:m,z:0},f=mt(g,s);if(!Number.isFinite(f)||u.AcGeTol.isNonPositive(f))return;const w=ty(g,s,e,t),v=i?-w:w;return{center:g,radius:f,startAngle:Me(g,s,v),endAngle:Me(g,t,v),normalSign:v}}function Yt(s,e,t,i){const n=mt(s,e),r=mt(s,t);if(u.AcGeTol.isNonPositive(n)||u.AcGeTol.isNonPositive(r))return;const o=Math.max(u.FLOAT_TOL,n*u.FLOAT_TOL);if(!(Math.abs(n-r)>o))return{center:{x:s.x,y:s.y,z:0},radius:n,startAngle:Me(s,e,i),endAngle:Me(s,t,i),normalSign:i}}function Hn(s,e,t,i){const n=mt(s,e);if(u.AcGeTol.isNonPositive(n))return;const r=ey(s,n,t);if(r)return Yt(s,e,r,i)}function Zt(s,e,t){const i=mt(s,e),n=Math.abs(t);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||!u.AcGeTol.great(u.TAU-n,0))return;const r=t>=0?1:-1,o=Me(s,e,r),a=Un(o+n);return{center:{x:s.x,y:s.y,z:0},radius:i,startAngle:o,endAngle:a,normalSign:r}}function _i(s,e,t){const i=mt(s,e),n=Math.abs(t);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||u.AcGeTol.great(n,2*i))return;const r=Math.max(-1,Math.min(1,n/(2*i))),o=2*Math.asin(r),a=t>=0?o:-o;return Zt(s,e,a)}function Dr(s,e,t){const i=mt(s,e),n=Math.abs(t);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||!u.AcGeTol.great(u.TAU-n,0))return;const r=Math.sin(n/2);if(u.AcGeTol.equalToZero(r))return;const o=i/(2*r),a=o*o-i*i/4;if(u.AcGeTol.less(a,0))return;const l=Math.sqrt(Math.max(0,a)),c=(s.x+e.x)/2,h=(s.y+e.y)/2,p=e.x-s.x,g=-(e.y-s.y)/i,f=p/i,w=t>=0,x=w&&n<=Math.PI||!w&&n>Math.PI?1:-1,S={x:c+g*l*x,y:h+f*l*x};return Yt(S,s,e,w?1:-1)}function Or(s,e,t){const i=Math.cos(t),n=Math.sin(t),r=e.x-s.x,o=e.y-s.y,a=-n,l=i,c=2*(r*a+o*l);if(u.AcGeTol.equalToZero(c))return;const h=(r*r+o*o)/c;if(!Number.isFinite(h))return;const p={x:s.x+a*h,y:s.y+l*h},m=s.x-p.x,g=s.y-p.y,f=m*n-g*i;if(u.AcGeTol.equalToZero(f))return;const w=f>=0?1:-1;return Yt(p,s,e,w)}function jr(s,e,t){const i=Math.abs(t),n=mt(s,e);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||u.AcGeTol.great(n,2*i))return;const r=(s.x+e.x)/2,o=(s.y+e.y)/2,a=e.x-s.x,c=-(e.y-s.y)/n,h=a/n,p=Math.sqrt(Math.max(0,i*i-n*n/4)),m=t>=0?1:-1,g={x:r+c*p*m,y:o+h*p*m},f=t>=0?1:-1;return Yt(g,s,e,f)}class Ei extends G{constructor(e,t,i){super(e),this._builder=t,this._arc=Ci(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==mc(this._arc)){this.end(),this._arc=Ci(t);return}yc(this._arc,t)}}}class Xt extends G{constructor(e,t,i){super(e),this._builder=t,this._arc=Ci(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==mc(this._arc)){this.end(),this._arc=Ci(t);return}yc(this._arc,t)}}}const iy={"3p":"threePoint","3point":"threePoint",threepoint:"threePoint",startcenter:"startCenter",sc:"startCenter",startcenterend:"startCenterEnd",sce:"startCenterEnd",startcenterangle:"startCenterAngle",sca:"startCenterAngle",startcenterlength:"startCenterLength",startcenterchordlength:"startCenterLength",scl:"startCenterLength",startend:"startEnd",se:"startEnd",startendangle:"startEndAngle",sea:"startEndAngle",startenddirection:"startEndDirection",sed:"startEndDirection",startendradius:"startEndRadius",ser:"startEndRadius",center:"centerStart",c:"centerStart",centerstart:"centerStart",cs:"centerStart",centerstartend:"centerStartEnd",cse:"centerStartEnd",centerstartangle:"centerStartAngle",csa:"centerStartAngle",centerstartlength:"centerStartLength",centerstartchordlength:"centerStartLength",csl:"centerStartLength"};class bc extends z{constructor(){super(),this.mode=F.Write}async execute(e){k.instance.editor.resetInputToggles();const t=this.consumeEntryMode();if(t!=="default"){await this.executeEntryMode(e,t);return}const i=new I(d.t("jig.arc.startPointOrCenter"));this.addKeyword(i,"center");const n=await k.instance.editor.getPoint(i);if(n.status===b.Keyword){n.stringResult==="Center"&&await this.runCenterStartFlow(e);return}n.status===b.OK&&await this.runStartFlow(e,n.value)}async executeEntryMode(e,t){switch(t){case"threePoint":await this.runExactThreePointFlow(e);return;case"startCenter":await this.runStartCenterFlowFromEntry(e);return;case"startCenterEnd":await this.runExactStartCenterFlow(e,"end");return;case"startCenterAngle":await this.runExactStartCenterFlow(e,"angle");return;case"startCenterLength":await this.runExactStartCenterFlow(e,"chordLength");return;case"startEnd":await this.runStartEndFlowFromEntry(e);return;case"startEndAngle":await this.runExactStartEndFlow(e,"angle");return;case"startEndDirection":await this.runExactStartEndFlow(e,"direction");return;case"startEndRadius":await this.runExactStartEndFlow(e,"radius");return;case"centerStart":await this.runCenterStartFlow(e);return;case"centerStartEnd":await this.runExactCenterStartFlow(e,"end");return;case"centerStartAngle":await this.runExactCenterStartFlow(e,"angle");return;case"centerStartLength":await this.runExactCenterStartFlow(e,"chordLength");return}}consumeEntryMode(){const e=k.instance.editor.peekScriptInput();if(e==null)return"default";const t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""),i=iy[t];return i?(k.instance.editor.consumeScriptInput(),i):"default"}addKeyword(e,t){e.keywords.add(d.t(`jig.arc.keywords.${t}.display`),d.t(`jig.arc.keywords.${t}.global`),d.t(`jig.arc.keywords.${t}.local`))}appendArc(e,t){e.doc.database.tables.blockTable.modelSpace.appendEntity(Ci(t))}warnInvalidGeometry(e){this.notify(d.t(`jig.arc.invalid.${e}`),"warning")}async promptStartPoint(){const e=new I(d.t("jig.arc.startPoint")),t=await k.instance.editor.getPoint(e);return t.status===b.OK?t.value:void 0}async promptCenterPoint(e){const t=new I(d.t("jig.arc.centerPoint"));e&&(t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e));const i=await k.instance.editor.getPoint(t);return i.status===b.OK?i.value:void 0}async promptEndPoint(e){const t=new I(d.t("jig.arc.endPoint"));e&&(t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e));const i=await k.instance.editor.getPoint(t);return i.status===b.OK?i.value:void 0}async promptSecondPoint(e){const t=new I(d.t("jig.arc.secondPoint"));t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e);const i=await k.instance.editor.getPoint(t);return i.status===b.OK?i.value:void 0}async runExactThreePointFlow(e){const t=await this.promptStartPoint();if(!t)return;const i=await this.promptSecondPoint(t);i&&await this.finishThreePointArc(e,t,i)}async runStartCenterFlowFromEntry(e){const t=await this.promptStartPoint();t&&await this.runStartCenterFlow(e,t)}async runExactStartCenterFlow(e,t){const i=await this.promptStartPoint();if(!i)return;const n=await this.promptCenterPoint(i);if(!n)return;if(t==="end"){await this.finishExactCenterStartEnd(e,n,i);return}if(t==="angle"){const c=new xe(d.t("jig.arc.includedAngle"));c.allowNegative=!0,c.allowZero=!1,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(n),c.baseAngle=Mr(n,i),c.jig=new Xt(e.view,g=>Zt(n,i,this.applyCtrlDirectionValue(this.degToRad(g))),De(i));const h=await k.instance.editor.getAngle(c),p=h.status===b.OK?h.value:void 0;if(p==null)return;const m=Zt(n,i,this.applyCtrlDirectionValue(this.degToRad(p)));m?this.appendArc(e,m):this.warnInvalidGeometry("angle");return}const r=new be(d.t("jig.arc.chordLength"));r.allowNegative=!0,r.allowZero=!1,r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new u.AcGePoint3d(i),r.jig=new Xt(e.view,c=>_i(n,i,this.applyCtrlDirectionValue(c)),De(i));const o=await k.instance.editor.getDistance(r),a=o.status===b.OK?o.value:void 0;if(a==null)return;const l=_i(n,i,this.applyCtrlDirectionValue(a));l?this.appendArc(e,l):this.warnInvalidGeometry("chordLength")}async runExactCenterStartFlow(e,t){const i=await this.promptCenterPoint();if(!i)return;const n=await this.promptStartPointFromCenter(i);if(!n)return;if(t==="end"){await this.finishExactCenterStartEnd(e,i,n);return}if(t==="angle"){const c=new xe(d.t("jig.arc.includedAngle"));c.allowNegative=!0,c.allowZero=!1,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(i),c.baseAngle=Mr(i,n),c.jig=new Xt(e.view,g=>Zt(i,n,this.applyCtrlDirectionValue(this.degToRad(g))),De(n));const h=await k.instance.editor.getAngle(c),p=h.status===b.OK?h.value:void 0;if(p==null)return;const m=Zt(i,n,this.applyCtrlDirectionValue(this.degToRad(p)));m?this.appendArc(e,m):this.warnInvalidGeometry("angle");return}const r=new be(d.t("jig.arc.chordLength"));r.allowNegative=!0,r.allowZero=!1,r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new u.AcGePoint3d(n),r.jig=new Xt(e.view,c=>_i(i,n,this.applyCtrlDirectionValue(c)),De(n));const o=await k.instance.editor.getDistance(r),a=o.status===b.OK?o.value:void 0;if(a==null)return;const l=_i(i,n,this.applyCtrlDirectionValue(a));l?this.appendArc(e,l):this.warnInvalidGeometry("chordLength")}async runExactStartEndFlow(e,t){const i=await this.promptStartPoint();if(!i)return;const n=await this.promptEndPoint(i);if(!n)return;if(t==="angle"){const c=new xe(d.t("jig.arc.includedAngle"));c.allowNegative=!0,c.allowZero=!1,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(i),c.baseAngle=Mr(i,n),c.jig=new Xt(e.view,g=>Dr(i,n,this.applyCtrlDirectionValue(this.degToRad(g))),De(i));const h=await k.instance.editor.getAngle(c),p=h.status===b.OK?h.value:void 0;if(p==null)return;const m=Dr(i,n,this.applyCtrlDirectionValue(this.degToRad(p)));m?this.appendArc(e,m):this.warnInvalidGeometry("angle");return}if(t==="direction"){const c=new I(d.t("jig.arc.tangentDirection"));c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(i),c.jig=new Ei(e.view,f=>Or(i,n,Math.atan2(f.y-i.y,f.x-i.x)),De(i));const h=await k.instance.editor.getPoint(c),p=h.status===b.OK?h.value:void 0;if(!p)return;const m=Math.atan2(p.y-i.y,p.x-i.x),g=Or(i,n,m);g?this.appendArc(e,g):this.warnInvalidGeometry("direction");return}const r=new be(d.t("jig.arc.radius"));r.allowNegative=!0,r.allowZero=!1,r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new u.AcGePoint3d(i),r.jig=new Xt(e.view,c=>jr(i,n,this.applyCtrlDirectionValue(c)),De(i));const o=await k.instance.editor.getDistance(r),a=o.status===b.OK?o.value:void 0;if(a==null)return;const l=jr(i,n,this.applyCtrlDirectionValue(a));l?this.appendArc(e,l):this.warnInvalidGeometry("radius")}async runStartEndFlowFromEntry(e){const t=await this.promptStartPoint();t&&await this.runStartEndFlow(e,t)}async promptStartPointFromCenter(e){const t=new I(d.t("jig.arc.startPoint"));t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e);const i=await k.instance.editor.getPoint(t);return i.status===b.OK?i.value:void 0}async finishExactCenterStartEnd(e,t,i){const n=new I(d.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(i),n.jig=new Ei(e.view,a=>Hn(t,i,a,this.applyCtrlDirectionSign(1)),De(i));const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK)return;const o=Hn(t,i,r.value,this.applyCtrlDirectionSign(1));o?this.appendArc(e,o):this.warnInvalidGeometry("center")}getArcDirectionFactor(){return k.instance.editor.getInputToggles().ctrlArcFlip?-1:1}applyCtrlDirectionSign(e){return e*this.getArcDirectionFactor()}applyCtrlDirectionValue(e){return e*this.getArcDirectionFactor()}isCtrlDirectionFlipped(){return k.instance.editor.getInputToggles().ctrlArcFlip}async runStartFlow(e,t){const i=new I(d.t("jig.arc.secondPointOrOptions"));this.addKeyword(i,"center"),this.addKeyword(i,"end"),i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t);const n=await k.instance.editor.getPoint(i);if(n.status===b.OK){await this.finishThreePointArc(e,t,n.value);return}if(n.status===b.Keyword){if(n.stringResult==="Center"){await this.runStartCenterFlow(e,t);return}n.stringResult==="End"&&await this.runStartEndFlow(e,t)}}async finishThreePointArc(e,t,i){const n=new I(d.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(t),n.jig=new Ei(e.view,a=>fc(t,i,a,this.isCtrlDirectionFlipped()),De(t));const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK)return;const o=fc(t,i,r.value,this.isCtrlDirectionFlipped());o?this.appendArc(e,o):this.warnInvalidGeometry("threePoint")}async runCenterStartFlow(e){const t=new I(d.t("jig.arc.centerPoint")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK)return;const n=i.value,r=new I(d.t("jig.arc.startPoint"));r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new u.AcGePoint3d(n);const o=await k.instance.editor.getPoint(r);o.status===b.OK&&await this.finishCenterStartFlow(e,n,o.value)}async runStartCenterFlow(e,t){const i=new I(d.t("jig.arc.centerPoint"));i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t);const n=await k.instance.editor.getPoint(i);n.status===b.OK&&await this.finishCenterStartFlow(e,n.value,t)}async finishCenterStartFlow(e,t,i){const n=new I(d.t("jig.arc.endPointOrOptions"));this.addKeyword(n,"angle"),this.addKeyword(n,"chordLength"),n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(i),n.jig=new Ei(e.view,o=>Hn(t,i,o,this.applyCtrlDirectionSign(1)),De(i));const r=await k.instance.editor.getPoint(n);if(r.status===b.OK){const o=Hn(t,i,r.value,this.applyCtrlDirectionSign(1));o?this.appendArc(e,o):this.warnInvalidGeometry("center");return}if(r.status===b.Keyword){if(r.stringResult==="Angle"){const o=new ie(d.t("jig.arc.includedAngle"));o.allowZero=!1,o.allowNegative=!0;const a=await k.instance.editor.getDouble(o);if(a.status!==b.OK)return;const l=Zt(t,i,this.applyCtrlDirectionValue(this.degToRad(a.value)));l?this.appendArc(e,l):this.warnInvalidGeometry("angle");return}if(r.stringResult==="ChordLength"){const o=new be(d.t("jig.arc.chordLength"));o.allowZero=!1,o.allowNegative=!0,o.useBasePoint=!0,o.useDashedLine=!0,o.basePoint=new u.AcGePoint3d(i);const a=await k.instance.editor.getDistance(o);if(a.status!==b.OK)return;const l=_i(t,i,this.applyCtrlDirectionValue(a.value));l?this.appendArc(e,l):this.warnInvalidGeometry("chordLength")}}}async runStartEndFlow(e,t){const i=new I(d.t("jig.arc.endPoint"));i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t);const n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new I(d.t("jig.arc.centerPointOrOptions"));this.addKeyword(o,"angle"),this.addKeyword(o,"direction"),this.addKeyword(o,"radius"),o.useBasePoint=!0,o.useDashedLine=!0,o.basePoint=new u.AcGePoint3d(t),o.jig=new Ei(e.view,l=>Yt(l,t,r,this.applyCtrlDirectionSign(1)),De(t));const a=await k.instance.editor.getPoint(o);if(a.status===b.OK){const l=Yt(a.value,t,r,this.applyCtrlDirectionSign(1));l?this.appendArc(e,l):this.warnInvalidGeometry("center");return}if(a.status===b.Keyword){if(a.stringResult==="Angle"){const l=new ie(d.t("jig.arc.includedAngle"));l.allowZero=!1,l.allowNegative=!0;const c=await k.instance.editor.getDouble(l);if(c.status!==b.OK)return;const h=Dr(t,r,this.applyCtrlDirectionValue(this.degToRad(c.value)));h?this.appendArc(e,h):this.warnInvalidGeometry("angle");return}if(a.stringResult==="Direction"){const l=new I(d.t("jig.arc.tangentDirection"));l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(t);const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK)return;const h=c.value,p=Math.atan2(h.y-t.y,h.x-t.x),m=Or(t,r,p);m?this.appendArc(e,m):this.warnInvalidGeometry("direction");return}if(a.stringResult==="Radius"){const l=new be(d.t("jig.arc.radius"));l.allowZero=!1,l.allowNegative=!0,l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(t);const c=await k.instance.editor.getDistance(l);if(c.status!==b.OK)return;const h=jr(t,r,this.applyCtrlDirectionValue(c.value));h?this.appendArc(e,h):this.warnInvalidGeometry("radius")}}}degToRad(e){return e*Math.PI/180}}function wc(s){return{center:{x:s.x,y:s.y,z:0},radius:1e-6}}function Br(s,e){s.keywords.add(d.t(`jig.circle.keywords.${e}.display`),d.t(`jig.circle.keywords.${e}.global`),d.t(`jig.circle.keywords.${e}.local`))}function ny(s,e){s.center=e.center,s.radius=e.radius}function vc(s,e){if(!(!Number.isFinite(e)||u.AcGeTol.isNonPositive(e)))return{center:{x:s.x,y:s.y,z:0},radius:e}}function kc(s,e){const t=e.x-s.x,i=e.y-s.y,n=Math.hypot(t,i);if(!u.AcGeTol.isNonPositive(n))return{center:{x:(s.x+e.x)/2,y:(s.y+e.y)/2,z:0},radius:n/2}}function xc(s,e,t){const i=s.x,n=s.y,r=e.x,o=e.y,a=t.x,l=t.y,c=2*(i*(o-l)+r*(l-n)+a*(n-o));if(u.AcGeTol.equalToZero(c))return;const h=((i*i+n*n)*(o-l)+(r*r+o*o)*(l-n)+(a*a+l*l)*(n-o))/c,p=((i*i+n*n)*(a-r)+(r*r+o*o)*(i-a)+(a*a+l*l)*(r-i))/c,m=Math.hypot(h-i,p-n);if(!(!Number.isFinite(m)||u.AcGeTol.isNonPositive(m)))return{center:{x:h,y:p,z:0},radius:m}}class Fr extends G{constructor(e,t){super(e),this._circle=new u.AcDbCircle(t,0)}get entity(){return this._circle}update(e){this._circle.radius=e}}class Sc extends G{constructor(e,t,i){super(e),this._circle=new u.AcDbCircle(i.center,i.radius),this._builder=t}get entity(){return this._circle}update(e){const t=this._builder(e);t&&ny(this._circle,t)}}class Pc extends z{constructor(){super(),this.mode=F.Write}async execute(e){let t;class i{constructor(p,m){this.cmd=p,this.machine=m}buildPrompt(){const p=new I(d.t("jig.circle.centerOrOptions"));return Br(p,"threeP"),Br(p,"twoP"),p}async handleResult(p){if(p.status===b.OK)return t=await this.cmd.runCenterFlow(e,p.value),"finish";if(p.status!==b.Keyword)return"finish";const m=p.stringResult??"";return m==="3P"?(this.machine.setState(new o(this.cmd,this.machine)),"continue"):m==="2P"?(this.machine.setState(new n(this.cmd,this.machine)),"continue"):"finish"}}class n{constructor(p,m){this.cmd=p,this.machine=m}buildPrompt(){return new I(d.t("jig.circle.twoPointFirst"))}async handleResult(p){return p.status!==b.OK?"finish":(this.machine.setState(new r(this.cmd,p.value)),"continue")}}class r{constructor(p,m){this.cmd=p,this.firstPoint=m}buildPrompt(){const p=new I(d.t("jig.circle.twoPointSecond"));return p.useBasePoint=!0,p.useDashedLine=!0,p.basePoint=new u.AcGePoint3d(this.firstPoint),p.jig=new Sc(e.view,m=>kc(this.firstPoint,m),wc(this.firstPoint)),p}async handleResult(p){return p.status===b.OK&&(t=this.cmd.createFromTwoPoints(this.firstPoint,p.value)),"finish"}}class o{constructor(p,m){this.cmd=p,this.machine=m}buildPrompt(){return new I(d.t("jig.circle.threePointFirst"))}async handleResult(p){return p.status!==b.OK?"finish":(this.machine.setState(new a(this.cmd,this.machine,p.value)),"continue")}}class a{constructor(p,m,g){this.cmd=p,this.machine=m,this.firstPoint=g}buildPrompt(){const p=new I(d.t("jig.circle.threePointSecond"));return p.useBasePoint=!0,p.useDashedLine=!0,p.basePoint=new u.AcGePoint3d(this.firstPoint),p}async handleResult(p){return p.status!==b.OK?"finish":(this.machine.setState(new l(this.cmd,this.firstPoint,p.value)),"continue")}}class l{constructor(p,m,g){this.cmd=p,this.firstPoint=m,this.secondPoint=g}buildPrompt(){const p=new I(d.t("jig.circle.threePointThird"));return p.useBasePoint=!0,p.useDashedLine=!0,p.basePoint=new u.AcGePoint3d(this.secondPoint),p.jig=new Sc(e.view,m=>xc(this.firstPoint,this.secondPoint,m),wc(this.firstPoint)),p}async handleResult(p){return p.status===b.OK&&(t=this.cmd.createFromThreePoints(this.firstPoint,this.secondPoint,p.value)),"finish"}}const c=new We;c.setState(new i(this,c)),await c.run(h=>k.instance.editor.getPoint(h)),t&&e.doc.database.tables.blockTable.modelSpace.appendEntity(new u.AcDbCircle(t.center,t.radius))}async runCenterFlow(e,t){const i=new be(d.t("jig.circle.radiusOrDiameter"));Br(i,"diameter"),i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t),i.jig=new Fr(e.view,t);const n=await k.instance.editor.getDistance(i);if(n.status===b.OK)return vc(t,n.value??0);if(n.status===b.Keyword&&n.stringResult==="Diameter")return await this.promptDiameterCircle(e,t)}async promptDiameterCircle(e,t){const i=new be(d.t("jig.circle.diameter"));i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t),i.jig=new Fr(e.view,t);const n=await k.instance.editor.getDistance(i);if(n.status!==b.OK)return;const r=(n.value??0)/2;return vc(t,r)}createFromTwoPoints(e,t){return kc(e,t)}createFromThreePoints(e,t,i){return xc(e,t,i)}}class Ac extends G{constructor(e,t,i,n){super(e),this._dimBlockName="*UDIM",this._db=t,new u.AcDbDataGenerator(t).createArrowBlock(),this._dim=new u.AcDbAlignedDimension(i,n,i),this._dim.rotation=0}get entity(){return this._dim}update(e){this._dim.dimLinePoint=e,this._dim.rotation=this.calculateAngle(this._dim.xLine1Point,this._dim.xLine2Point),this._dim.dimensionText=this._dim.xLine1Point.distanceTo(this._dim.xLine2Point).toFixed(3);const t=this._dimBlockName;this._db.tables.blockTable.remove(t),this._db.tables.blockTable.add(this._dim.createDimBlock(t)),this._dim.dimBlockId=t}end(){super.end(),this._db.tables.blockTable.remove(this._dimBlockName)}calculateAngle(e,t){const i=t.x-e.x,n=t.y-e.y;return Math.atan2(n,i)}}class Cc extends z{constructor(){super(),this.mode=F.Review}async execute(e){const t=new I(d.t("jig.dimlinear.xLine1Point")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK)return;const n=i.value,r=new I(d.t("jig.dimlinear.xLine2Point"));r.useBasePoint=!0;const o=await k.instance.editor.getPoint(r);if(o.status!==b.OK)return;const a=o.value,l=new I(d.t("jig.dimlinear.dimLinePoint"));l.jig=new Ac(e.view,e.doc.database,n,a);const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK)return;const h=c.value,p=e.doc.database,m=new u.AcDbAlignedDimension(n,a,h),g=this.getAvaiableDimBlockName(p);p.tables.blockTable.add(m.createDimBlock(g)),m.dimBlockId=g,p.tables.blockTable.modelSpace.appendEntity(m)}getAvaiableDimBlockName(e){const t=e.tables.blockTable.newIterator();let i=0;for(const n of t){const r=n.name;if(!r.startsWith("*D"))continue;const o=Number(r.slice(2));Number.isInteger(o)&&o>i&&(i=o)}return`*D${i+1}`}}class Wn extends G{constructor(e,t){super(e),this._line=new u.AcDbLine(t,t)}get entity(){return this._line}update(e){this._line.endPoint=e}}class St extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.doc.database,i=[],n=[],r=()=>!!St._lastEndpoint,o=()=>St._lastEndpoint?new u.AcGePoint3d(St._lastEndpoint):void 0,a=()=>{const x=c();x&&(St._lastEndpoint=new u.AcGePoint3d(x))},l=x=>{i.push(new u.AcGePoint3d(x))},c=()=>i[i.length-1],h=x=>{const S=c();if(!S)return;const P=new u.AcDbLine(new u.AcGePoint3d(S),x);t.tables.blockTable.modelSpace.appendEntity(P),n.push(P),e.view.addEntity(P),l(x)},p=()=>{if(n.length<=0||i.length<=1)return;const x=n.pop();x==null||x.erase(),x&&e.view.removeEntity(x),i.pop()},m=()=>{if(i.length<=1)return;const x=i[0],S=c();if(!S)return;x.x===S.x&&x.y===S.y&&x.z===S.z||h(x)},g=new I(r()?d.t("jig.line.firstPointOrContinue"):d.t("jig.line.firstPoint"));r()&&g.keywords.add(d.t("jig.line.keywords.continue.display"),d.t("jig.line.keywords.continue.global"),d.t("jig.line.keywords.continue.local"));const f=await k.instance.editor.getPoint(g);if(f.status===b.OK)l(f.value);else if(f.status===b.Keyword&&f.stringResult==="Continue"&&r())l(o());else return;class w{buildPrompt(){const S=new I(d.t("jig.line.nextPointWithOptions"));S.keywords.add(d.t("jig.line.keywords.undo.display"),d.t("jig.line.keywords.undo.global"),d.t("jig.line.keywords.undo.local")),i.length>1&&S.keywords.add(d.t("jig.line.keywords.close.display"),d.t("jig.line.keywords.close.global"),d.t("jig.line.keywords.close.local"));const P=c();return P&&(S.useDashedLine=!0,S.useBasePoint=!0,S.basePoint=new u.AcGePoint3d(P),S.jig=new Wn(e.view,P)),S.allowNone=!0,S}async handleResult(S){if(S.status===b.OK)return h(S.value),"continue";if(S.status===b.Keyword){const P=S.stringResult??"";return P==="Undo"?(p(),"continue"):P==="Close"&&i.length>1?(m(),"finish"):"continue"}return"finish"}}const v=new We;v.setState(new w),await v.run(x=>k.instance.editor.getPoint(x)),a()}}const zr={x:0,y:0,z:1};function $n(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function sy(s,e){return{x:(s.x+e.x)/2,y:(s.y+e.y)/2,z:0}}function _c(s,e){const t=Math.hypot(s,e);if(!(!Number.isFinite(t)||u.AcGeTol.isNonPositive(t)))return{x:s/t,y:e/t,z:0}}function ry(s){return{x:-s.y,y:s.x,z:0}}function Nr(s){return s*Math.PI/180}function oy(s){return s*180/Math.PI}function ay(s){return oy(Math.atan2(s.y,s.x))}function Yn(s,e,t){const i=Nr(s);return Math.atan2(e*Math.sin(i),t*Math.cos(i))}function ly(s,e){return _c(e.x-s.x,e.y-s.y)}function Zn(s,e,t,i,n=0,r=u.TAU){if(!Number.isFinite(t)||!Number.isFinite(i)||u.AcGeTol.isNonPositive(t)||u.AcGeTol.isNonPositive(i))return;const o=cy(n,r);return t>=i?{center:{x:s.x,y:s.y,z:0},majorAxis:e,majorRadius:t,minorRadius:i,startAngle:o.startAngle,endAngle:o.endAngle}:{center:{x:s.x,y:s.y,z:0},majorAxis:ry(e),majorRadius:i,minorRadius:t,startAngle:o.startAngle,endAngle:o.endAngle}}function cy(s,e){const t=Math.abs(e-s);return Math.abs(t-u.TAU)<1e-10||Math.abs(t-2*u.TAU)<1e-10?{startAngle:0,endAngle:0}:{startAngle:s,endAngle:e}}function Ec(s){return new u.AcDbEllipse(s,zr,{x:1,y:0,z:0},1e-6,1e-6,0,u.TAU)}function Lc(s,e){s.center=e.center,s.normal=zr,s.majorAxisRadius=e.majorRadius,s.minorAxisRadius=e.minorRadius,s.startAngle=e.startAngle,s.endAngle=e.endAngle;const t=s;t._geo&&(t._geo.majorAxis=e.majorAxis)}class dy extends G{constructor(e,t,i){super(e),this._builder=t,this._ellipse=Ec(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&Lc(this._ellipse,t)}}class Rr extends G{constructor(e,t,i){super(e),this._builder=t,this._ellipse=Ec(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&Lc(this._ellipse,t)}}class Tc extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=new I(d.t("jig.ellipse.axisEndpointOrOptions"));this.addKeyword(t,"arc"),this.addKeyword(t,"center");const i=await k.instance.editor.getPoint(t);if(i.status===b.Keyword){const n=i.stringResult??"";n==="Center"?await this.runCenterFlow(e,!1):n==="Arc"&&await this.runArcEntryFlow(e);return}i.status===b.OK&&await this.runAxisEndFlow(e,i.value,!1)}addKeyword(e,t){e.keywords.add(d.t(`jig.ellipse.keywords.${t}.display`),d.t(`jig.ellipse.keywords.${t}.global`),d.t(`jig.ellipse.keywords.${t}.local`))}appendEllipse(e,t){const i=new u.AcDbEllipse(t.center,zr,t.majorAxis,t.majorRadius,t.minorRadius,t.startAngle,t.endAngle);e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){this.notify(d.t(`jig.ellipse.invalid.${e}`),"warning")}async runArcEntryFlow(e){const t=new I(d.t("jig.ellipse.arcAxisEndpointOrCenter"));this.addKeyword(t,"center");const i=await k.instance.editor.getPoint(t);if(i.status===b.Keyword){i.stringResult==="Center"&&await this.runCenterFlow(e,!0);return}i.status===b.OK&&await this.runAxisEndFlow(e,i.value,!0)}async runCenterFlow(e,t){const i=new I(d.t("jig.ellipse.center")),n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new I(d.t("jig.ellipse.firstAxisEndpoint"));o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new u.AcGePoint3d(r),o.jig=new Wn(e.view,r);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)return;const l=ly(r,a.value);if(!l){this.warnInvalidInput("axis");return}const c=$n(r,a.value),h=await this.promptOtherAxis(e,r,l,c,t);h&&this.appendEllipse(e,h)}async runAxisEndFlow(e,t,i){const n=new I(d.t("jig.ellipse.secondAxisEndpoint"));n.useDashedLine=!0,n.useBasePoint=!0,n.basePoint=new u.AcGePoint3d(t),n.jig=new Wn(e.view,t);const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=o.x-t.x,l=o.y-t.y,c=_c(a,l);if(!c){this.warnInvalidInput("axis");return}const h=sy(t,o),p=$n(t,o)/2,m=await this.promptOtherAxis(e,h,c,p,i);m&&this.appendEllipse(e,m)}async promptOtherAxis(e,t,i,n,r){for(;;){const o=new I(d.t("jig.ellipse.otherAxisOrRotation"));this.addKeyword(o,"rotation"),o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new u.AcGePoint3d(t),o.jig=new dy(e.view,h=>{const p=$n(t,h);return Zn(t,i,n,p)},t);const a=await k.instance.editor.getPoint(o);if(a.status===b.Keyword){if(a.stringResult!=="Rotation")return;const h=new ie(d.t("jig.ellipse.rotationAngle"));h.allowNegative=!1,h.allowZero=!0,h.jig=new Rr(e.view,f=>{const w=n*Math.abs(Math.cos(Nr(f)));return Zn(t,i,n,w)},t);const p=await k.instance.editor.getDouble(h);if(p.status!==b.OK)return;const m=n*Math.abs(Math.cos(Nr(p.value??0))),g=Zn(t,i,n,m);if(!g){this.warnInvalidInput("rotation");continue}return r?await this.promptArcAngles(e,g):g}if(a.status!==b.OK)return;const l=$n(t,a.value),c=Zn(t,i,n,l);if(!c){this.warnInvalidInput("otherAxis");continue}return r?await this.promptArcAngles(e,c):c}}async promptArcAngles(e,t){const i=ay(t.majorAxis),n=new xe(d.t("jig.ellipse.arcStartAngle"));n.allowNegative=!0,n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(t.center),n.baseAngle=i,n.jig=new Rr(e.view,c=>({...t,startAngle:Yn(c,t.majorRadius,t.minorRadius),endAngle:u.TAU}),t.center);const r=await k.instance.editor.getAngle(n);if(r.status!==b.OK)return;const o=Yn(r.value??0,t.majorRadius,t.minorRadius),a=new xe(d.t("jig.ellipse.arcEndAngle"));a.allowNegative=!0,a.useBasePoint=!0,a.useDashedLine=!0,a.basePoint=new u.AcGePoint3d(t.center),a.baseAngle=i,a.jig=new Rr(e.view,c=>({...t,startAngle:o,endAngle:Yn(c,t.majorRadius,t.minorRadius)}),t.center);const l=await k.instance.editor.getAngle(a);if(l.status===b.OK)return{...t,startAngle:o,endAngle:Yn(l.value??0,t.majorRadius,t.minorRadius)}}}const Ts=class Ts extends z{constructor(){super(),this.mode=F.Write}get settings(){return Ts._lastSettings}normalizeSysVarNumber(e,t){const i=Number(e);return Number.isFinite(i)?i:t}normalizePositiveSysVarNumber(e,t){const i=this.normalizeSysVarNumber(e,t);return i>0?i:t}sysVarRadiansToDegrees(e){return Math.round(e*180/Math.PI*1e6)/1e6}getSysVar(e,t,i){try{return e.getVar(t,i)}catch{return}}getDatabaseSysVarSettings(e){const t=this.settings;if(!(e instanceof u.AcDbDatabase))return t;try{const i=u.AcDbSysVarManager.instance(),n=this.getSysVar(i,u.AcDbSystemVariables.HPASSOC,e);return{...t,patternName:this.normalizePatternName(this.getSysVar(i,u.AcDbSystemVariables.HPNAME,e)??t.patternName),patternScale:this.normalizePositiveSysVarNumber(this.getSysVar(i,u.AcDbSystemVariables.HPSCALE,e),t.patternScale),patternAngleDeg:this.sysVarRadiansToDegrees(this.normalizeSysVarNumber(this.getSysVar(i,u.AcDbSystemVariables.HPANG,e),t.patternAngleDeg*Math.PI/180)),associative:n==null?t.associative:Number(n)!==0}}catch{return t}}getActiveSettings(){var e;return this.getDatabaseSysVarSettings((e=k.instance.curDocument)==null?void 0:e.database)}setActiveSysVar(e,t){var n;const i=(n=k.instance.curDocument)==null?void 0:n.database;i&&u.AcDbSysVarManager.instance().setVar(e,t,i)}normalizePatternName(e){const t=e.trim().toUpperCase();return t.length>0?t:u.HATCH_PATTERN_SOLID}styleToKeyword(e){switch(e){case u.AcDbHatchStyle.Outer:return"Outer";case u.AcDbHatchStyle.Ignore:return"Ignore";case u.AcDbHatchStyle.Normal:default:return"Normal"}}keywordToStyle(e){switch(e){case"Outer":return u.AcDbHatchStyle.Outer;case"Ignore":return u.AcDbHatchStyle.Ignore;case"Normal":default:return u.AcDbHatchStyle.Normal}}buildEdgesFromPolyline(e){var r;if(!e.closed||e.numberOfVertices<2)return[];const t=(r=e._geo)==null?void 0:r.vertices,i=t&&t.length>1?t.map(o=>({x:o.x,y:o.y,bulge:o.bulge})):Array.from({length:e.numberOfVertices},(o,a)=>{const l=e.getPoint2dAt(a);return{x:l.x,y:l.y,bulge:0}});if(i.length<2)return[];const n=[];for(let o=0;o<i.length;o++){const a=i[o],l=i[(o+1)%i.length],c=a.bulge??0;Math.abs(c)>1e-12?n.push(new u.AcGeCircArc2d(a,l,c)):n.push(new u.AcGeLine2d(a,l))}return n}buildEdgesFromEntity(e){if(e instanceof u.AcDbPolyline)return this.buildEdgesFromPolyline(e);if(e instanceof u.AcDbCircle){const t=e.center;return[new u.AcGeCircArc2d({x:t.x,y:t.y},e.radius,0,Math.PI*2,!1)]}if(e instanceof u.AcDbArc){if(!e.closed)return[];const t=e.center;return[new u.AcGeCircArc2d({x:t.x,y:t.y},e.radius,e.startAngle,e.endAngle,!1)]}return e instanceof u.AcDbLine?[new u.AcGeLine2d(e.startPoint,e.endPoint)]:[]}collectLoopsFromIds(e,t){const i=e.doc.database.tables.blockTable.modelSpace,n=[];return t.forEach(r=>{const o=i.getIdAt(r);o&&n.push(...this.buildEdgesFromEntity(o))}),this.buildLoopsFromEdges(n)}collectLoopsFromAllBoundaries(e){const t=e.doc.database.tables.blockTable.modelSpace,i=[];for(const n of t.newIterator())i.push(...this.buildEdgesFromEntity(n));return this.buildLoopsFromEdges(i)}buildLoopsFromEdges(e){if(e.length===0)return[];const t=[1e-6,1e-5,1e-4,.001];let i=[];for(const n of t){const r=u.AcGeLoop2d.buildFromEdges(e,n).filter(o=>o.closed&&o.numberOfEdges>0);r.length>i.length&&(i=r)}return i}signedArea(e){if(e.length<3)return 0;let t=0;for(let i=0,n=e.length-1;i<e.length;n=i++){const r=e[n],o=e[i];t+=r.x*o.y-o.x*r.y}return t*.5}isPointOnSegment(e,t,i,n,r,o,a=1e-8){const l=r-i,c=o-n,h=e-i,p=t-n;if(Math.abs(l*p-c*h)>a)return!1;const g=h*l+p*c;if(g<-a)return!1;const f=l*l+c*c;return!(g-f>a)}isPointInPolygon(e,t){if(t.length<3)return!1;for(let n=0,r=t.length-1;n<t.length;r=n++){const o=t[r],a=t[n];if(this.isPointOnSegment(e.x,e.y,o.x,o.y,a.x,a.y))return!0}let i=!1;for(let n=0,r=t.length-1;n<t.length;r=n++){const o=t[n].x,a=t[n].y,l=t[r].x,c=t[r].y;a>e.y!=c>e.y&&e.x<(l-o)*(e.y-a)/(c-a+Number.EPSILON)+o&&(i=!i)}return i}buildLoopInfos(e){const t=[];e.forEach(i=>{const n=i.getPoints(128).map(r=>({x:r.x,y:r.y}));n.length<3||t.push({loop:i,points:n,area:Math.abs(this.signedArea(n)),parent:null,children:[]})});for(let i=0;i<t.length;i++){const n=t[i].points[0];let r=null,o=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++)i!==a&&(t[a].area<=t[i].area||this.isPointInPolygon(n,t[a].points)&&t[a].area<o&&(o=t[a].area,r=a));t[i].parent=r,r!=null&&t[r].children.push(i)}return t}resolveLoopsForPickPoint(e,t){const i=this.buildLoopInfos(t);if(!i.length)return[];const n=i.map((a,l)=>this.isPointInPolygon(e,a.points)?l:-1).filter(a=>a>=0);if(!n.length)return[];n.sort((a,l)=>i[a].area-i[l].area);const r=n[0],o=new Set([r]);return this.settings.style!==u.AcDbHatchStyle.Ignore&&i[r].children.forEach(a=>o.add(a)),[...o].map(a=>i[a].loop)}appendHatch(e,t){if(!t.length)return!1;const i=new u.AcDbHatch;e.doc.database instanceof u.AcDbDatabase&&(i.database=e.doc.database);const n=this.getDatabaseSysVarSettings(e.doc.database),r=this.normalizePatternName(n.patternName),o=r===u.HATCH_PATTERN_SOLID;return i.patternName=r,i.patternType=u.AcDbHatchPatternType.Predefined,i.patternScale=n.patternScale,i.patternAngle=n.patternAngleDeg*Math.PI/180,i.hatchStyle=n.style,i.isSolidFill=o,this.configureHatch(i),t.forEach(a=>i.add(a)),e.doc.database.tables.blockTable.modelSpace.appendEntity(i),!0}configureHatch(e){}async promptPatternName(){const e=new le(d.t("jig.hatch.patternName"));e.allowEmpty=!1;const t=this.getActiveSettings();e.defaultValue=t.patternName,e.useDefaultValue=!0;const i=await k.instance.editor.getString(e);if(i.status!==b.OK)return;const n=this.normalizePatternName(i.stringResult??e.defaultValue);this.settings.patternName=n,this.setActiveSysVar(u.AcDbSystemVariables.HPNAME,n)}async promptPatternScale(){const e=new ie(d.t("jig.hatch.scale"));e.allowNone=!0,e.allowNegative=!1,e.allowZero=!1;const t=this.getActiveSettings();e.defaultValue=t.patternScale,e.useDefaultValue=!0;const i=await k.instance.editor.getDouble(e);if(i.status!==b.OK)return;const n=i.value??e.defaultValue;n>0&&(this.settings.patternScale=n,this.setActiveSysVar(u.AcDbSystemVariables.HPSCALE,n))}async promptPatternAngle(){const e=new ie(d.t("jig.hatch.angle"));e.allowNone=!0,e.allowNegative=!0,e.allowZero=!0;const t=this.getActiveSettings();e.defaultValue=t.patternAngleDeg,e.useDefaultValue=!0;const i=await k.instance.editor.getDouble(e);if(i.status!==b.OK)return;const n=i.value??e.defaultValue;this.settings.patternAngleDeg=n,this.setActiveSysVar(u.AcDbSystemVariables.HPANG,n*Math.PI/180)}async promptStyle(){const e=this.getActiveSettings(),t=this.styleToKeyword(e.style),i=new ne(d.t("jig.hatch.style"));i.allowNone=!0;const n=i.keywords.add(d.t("jig.hatch.keywords.normal.display"),d.t("jig.hatch.keywords.normal.global"),d.t("jig.hatch.keywords.normal.local")),r=i.keywords.add(d.t("jig.hatch.keywords.outer.display"),d.t("jig.hatch.keywords.outer.global"),d.t("jig.hatch.keywords.outer.local")),o=i.keywords.add(d.t("jig.hatch.keywords.ignore.display"),d.t("jig.hatch.keywords.ignore.global"),d.t("jig.hatch.keywords.ignore.local"));i.keywords.default=t==="Outer"?r:t==="Ignore"?o:n;const a=await k.instance.editor.getKeywords(i);(a.status===b.OK||a.status===b.Keyword)&&a.stringResult&&(this.settings.style=this.keywordToStyle(a.stringResult))}async promptAssociative(){const e=this.getActiveSettings(),t=new ne(d.t("jig.hatch.associative"));t.allowNone=!0;const i=t.keywords.add(d.t("jig.hatch.keywords.yes.display"),d.t("jig.hatch.keywords.yes.global"),d.t("jig.hatch.keywords.yes.local")),n=t.keywords.add(d.t("jig.hatch.keywords.no.display"),d.t("jig.hatch.keywords.no.global"),d.t("jig.hatch.keywords.no.local"));t.keywords.default=e.associative?i:n;const r=await k.instance.editor.getKeywords(t);if(r.status===b.OK||r.status===b.Keyword){const o=r.stringResult==="Yes";this.settings.associative=o,this.setActiveSysVar(u.AcDbSystemVariables.HPASSOC,o?1:0)}}async doSelectObjects(e){const t=new xt(d.t("jig.hatch.select")),i=await k.instance.editor.getSelection(t);if(i.status!==b.OK||!i.value)return!1;const n=this.collectLoopsFromIds(e,i.value.ids);return n.length?this.appendHatch(e,n):!1}async doPickPoints(e){const t=this.collectLoopsFromAllBoundaries(e);if(!t.length)return!1;let i=!1;for(;;){const n=new I(d.t("jig.hatch.pickPoint"));n.allowNone=!0;const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK||!r.value)break;const o=this.resolveLoopsForPickPoint(r.value,t);o.length&&this.appendHatch(e,o)&&(i=!0)}return i}async execute(e){let t=!0;for(;t;){const i=new He(d.t("jig.hatch.prompt"));i.allowNone=!0,i.setRejectMessage(d.t("jig.hatch.invalidBoundary")),i.addAllowedClass("Polyline"),i.addAllowedClass("Circle"),i.addAllowedClass("Arc"),i.addAllowedClass("Line"),i.keywords.add(d.t("jig.hatch.keywords.pick.display"),d.t("jig.hatch.keywords.pick.global"),d.t("jig.hatch.keywords.pick.local")),i.keywords.add(d.t("jig.hatch.keywords.select.display"),d.t("jig.hatch.keywords.select.global"),d.t("jig.hatch.keywords.select.local")),i.keywords.add(d.t("jig.hatch.keywords.pattern.display"),d.t("jig.hatch.keywords.pattern.global"),d.t("jig.hatch.keywords.pattern.local")),i.keywords.add(d.t("jig.hatch.keywords.scale.display"),d.t("jig.hatch.keywords.scale.global"),d.t("jig.hatch.keywords.scale.local")),i.keywords.add(d.t("jig.hatch.keywords.angle.display"),d.t("jig.hatch.keywords.angle.global"),d.t("jig.hatch.keywords.angle.local")),i.keywords.add(d.t("jig.hatch.keywords.style.display"),d.t("jig.hatch.keywords.style.global"),d.t("jig.hatch.keywords.style.local")),i.keywords.add(d.t("jig.hatch.keywords.associative.display"),d.t("jig.hatch.keywords.associative.global"),d.t("jig.hatch.keywords.associative.local"));const n=await k.instance.editor.getEntity(i);if(n.status===b.OK&&n.objectId){const r=this.collectLoopsFromIds(e,[n.objectId]);if(!r.length)continue;this.appendHatch(e,r);continue}if(n.status===b.Keyword){const r=n.stringResult??"";r==="PickPoints"?await this.doPickPoints(e):r==="SelectObjects"?await this.doSelectObjects(e):r==="Pattern"?await this.promptPatternName():r==="Scale"?await this.promptPatternScale():r==="Angle"?await this.promptPatternAngle():r==="HatchStyle"?await this.promptStyle():r==="AssociativeMode"&&await this.promptAssociative();continue}t=!1}}};Ts._lastSettings={patternName:u.HATCH_PATTERN_SOLID,patternScale:1,patternAngleDeg:0,style:u.AcDbHatchStyle.Normal,associative:!0};let Xn=Ts;const uy=".png,.jpg,.jpeg,.bmp,.gif,.tif,.tiff",hy=100;function py(s,e){if(!s.objects.imageDefinition.has(e))return e;const t=e.lastIndexOf("."),i=t>0?e.slice(0,t):e,n=t>0?e.slice(t):"";let r=1;for(;s.objects.imageDefinition.has(`${i}_${r}${n}`);)r++;return`${i}_${r}${n}`}function my(s,e){const t=Math.max(1,s),i=Math.max(1,e),n=Math.max(t,i),r=n>0?hy/n:1;return{width:Math.max(1,t*r),height:Math.max(1,i*r)}}async function yy(s){const e=URL.createObjectURL(s);try{return await new Promise((t,i)=>{const n=new Image;n.onload=()=>t({width:n.naturalWidth||100,height:n.naturalHeight||100}),n.onerror=()=>i(new Error("Failed to decode image")),n.src=e})}finally{URL.revokeObjectURL(e)}}function gy(){return new Promise(s=>{const e=document.createElement("input");e.type="file",e.accept=uy,e.style.display="none",document.body.appendChild(e);let t=!1;const i=o=>{t||(t=!0,e.removeEventListener("change",n),e.removeEventListener("cancel",r),e.remove(),s(o))},n=()=>{var o;return i((o=e.files)==null?void 0:o[0])},r=()=>i(void 0);e.addEventListener("change",n),e.addEventListener("cancel",r),e.click()})}class fy extends G{constructor(e,t,i,n){super(e),this._mode="point",this._position=new u.AcGePoint3d,this._scale=1,this._rotationRad=0,this._baseWidth=i,this._baseHeight=n,this._entity=new u.AcDbRasterImage,this._entity.image=t,this._entity.width=i,this._entity.height=n,this.applyGeometry()}get entity(){return this._entity}setMode(e){this._mode=e}setPosition(e){this._position=new u.AcGePoint3d(e),this.applyGeometry()}setScale(e){this._scale=e,this.applyGeometry()}setRotationRad(e){this._rotationRad=e,this.applyGeometry()}update(e){if(this._mode==="point"&&typeof e!="number"){this.setPosition(e);return}if(typeof e=="number"){if(this._mode==="scale"){this.setScale(e>0?e:this._scale);return}this._mode==="rotation"&&this.setRotationRad(e*Math.PI/180)}}applyGeometry(){this._entity.position=new u.AcGePoint3d(this._position),this._entity.width=Math.max(1e-6,this._baseWidth*this._scale),this._entity.height=Math.max(1e-6,this._baseHeight*this._scale),this._entity.rotation=this._rotationRad}}class Ic extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=await gy();if(!t)return;let i;try{i=await yy(t)}catch{this.showMessage(d.t("jig.imageattach.decodeFailed"),"error");return}const n=my(i.width,i.height),r=new fy(e.view,t,n.width,n.height);try{r.setMode("point");const o=new I(d.t("jig.imageattach.insertionPoint"));o.jig=r;const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK||!a.value)return;const l=new u.AcGePoint3d(a.value);r.setPosition(l),r.setMode("scale");const c=new ie(d.t("jig.imageattach.scale"));c.allowNone=!0,c.allowNegative=!1,c.allowZero=!1,c.useDefaultValue=!0,c.defaultValue=1,c.jig=r;const h=await k.instance.editor.getDouble(c);if(h.status===b.Cancel||h.status===b.Error)return;const p=h.status===b.OK&&h.value!==void 0?h.value:1;if(!(p>0)){this.showMessage(d.t("jig.imageattach.invalidScale"),"warning");return}r.setScale(p),r.setMode("rotation");const m=new xe(d.t("jig.imageattach.rotation"));m.allowNone=!0,m.allowNegative=!0,m.allowZero=!0,m.useDefaultValue=!0,m.defaultValue=0,m.useBasePoint=!0,m.useDashedLine=!0,m.basePoint=l,m.jig=r;const g=await k.instance.editor.getAngle(m);if(g.status===b.Cancel||g.status===b.Error)return;const w=(g.status===b.OK&&g.value!==void 0?g.value:0)*Math.PI/180,v=e.doc.database,x=py(v,t.name),S=Math.max(1e-6,n.width*p),P=Math.max(1e-6,n.height*p);ct(v,"IMAGEATTACH",()=>{const A=new u.AcDbRasterImageDef;A.sourceFileName=t.name,v.objects.imageDefinition.setAt(x,A);const _=new u.AcDbRasterImage;_.position=l,_.width=S,_.height=P,_.rotation=w,_.image=t,_.imageDefId=A.objectId,v.tables.blockTable.modelSpace.appendEntity(_)})}finally{r.end()}}}const Do=class Do{static set(e){this._options={...e}}static consume(){const e=this._options;return this._options=null,e}static clear(){this._options=null}};Do._options=null;let qn=Do;function Mc(s){const e=s.trim();return!e||/[\r\n]/.test(e)?!1:!e.startsWith("*")}class by extends G{constructor(e,t){super(e),this._mode="point",this._position=new u.AcGePoint3d,this._scaleX=1,this._scaleY=1,this._scaleZ=1,this._rotationRad=0,this._entity=new u.AcDbBlockReference(t),this.applyGeometry()}get entity(){return this._entity}setMode(e){this._mode=e}setPosition(e){this._position=new u.AcGePoint3d(e),this.applyGeometry()}setUniformScale(e){this._scaleX=e,this._scaleY=e,this._scaleZ=e,this.applyGeometry()}setScaleFactors(e,t,i){this._scaleX=e,this._scaleY=t,this._scaleZ=i,this.applyGeometry()}setRotationRad(e){this._rotationRad=e,this.applyGeometry()}update(e){if(this._mode==="point"&&typeof e!="number"){this.setPosition(e);return}if(typeof e=="number"){if(this._mode==="scale"){this.setUniformScale(e>0?e:this._scaleX);return}this._mode==="rotation"&&this.setRotationRad(e*Math.PI/180)}}applyGeometry(){this._entity.position=new u.AcGePoint3d(this._position),this._entity.scaleFactors=new u.AcGePoint3d(this._scaleX,this._scaleY,this._scaleZ),this._entity.rotation=this._rotationRad}}class Dc extends z{constructor(){super(),this.mode=F.Write}async execute(e){const i=e.doc.database.tables.blockTable,n=qn.consume(),r=new le(d.t("jig.insert.blockName")),o=await k.instance.editor.getString(r);if(o.status!==b.OK)return;const a=String(o.stringResult??"").trim();if(!Mc(a)){this.showMessage(d.t("jig.insert.invalidBlockName"),"warning");return}if(!i.has(a)){this.showMessage(`${d.t("jig.insert.blockNotFound")}: ${a}`,"warning");return}const l=i.getAt(a);if(l!=null&&l.isXref){this.showMessage(d.t("jig.insert.xrefNotAllowed"),"warning");return}const c=new by(e.view,a);try{do if(!await this.placeOne(e,a,c,n))return;while(n!=null&&n.repeatPlacement)}finally{c.end()}}async placeOne(e,t,i,n){const r=e.doc.database;i.setMode("point");const o=new I(d.t("jig.insert.insertionPoint"));o.jig=i;const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK||!a.value)return!1;const l=new u.AcGePoint3d(a.value);i.setPosition(l);let c=1,h=1,p=1;if(!((n==null?void 0:n.specifyScale)!==!1)&&n)c=Vr(n.scaleX,1),h=Vr(n.scaleY,c),p=Vr(n.scaleZ,c),i.setScaleFactors(c,h,p);else{i.setMode("scale");const v=new ie(d.t("jig.insert.scale"));v.allowNone=!0,v.allowNegative=!1,v.allowZero=!1,v.useDefaultValue=!0,v.defaultValue=1,v.jig=i;const x=await k.instance.editor.getDouble(v);if(x.status===b.Cancel||x.status===b.Error)return!1;const S=x.status===b.OK&&x.value!==void 0?x.value:1;if(!(S>0))return this.showMessage(d.t("jig.insert.invalidScale"),"warning"),!1;c=h=p=S,i.setUniformScale(S)}let g=0;if(!((n==null?void 0:n.specifyRotation)!==!1)&&n)g=Number.isFinite(n.rotationDeg)?n.rotationDeg:0,i.setRotationRad(g*Math.PI/180);else{i.setMode("rotation");const v=new xe(d.t("jig.insert.rotation"));v.allowNone=!0,v.allowNegative=!0,v.allowZero=!0,v.useDefaultValue=!0,v.defaultValue=0,v.useBasePoint=!0,v.useDashedLine=!0,v.basePoint=l,v.jig=i;const x=await k.instance.editor.getAngle(v);if(x.status===b.Cancel||x.status===b.Error)return!1;g=x.status===b.OK&&x.value!==void 0?x.value:0}const w=g*Math.PI/180;return ct(r,"INSERT",()=>{const v=new u.AcDbBlockReference(t);v.position=l,v.scaleFactors=new u.AcGePoint3d(c,h,p),v.rotation=w,r.tables.blockTable.modelSpace.appendEntity(v)}),!0}}function Vr(s,e){return s!==void 0&&s>0?s:e}class Oc extends G{constructor(e,t,i){if(super(e),this._mline=new u.AcDbMLine,this._points=t,this._resolveState=i,t.length>0){const n=this._resolveState();Gr(this._mline,t,n.styleName,n.justification,n.scale,!1,n.elementOffsets)}}get entity(){return this._mline}update(e){if(this._points.length<=0)return;const t=[...this._points,new u.AcGePoint3d(e)],i=this._resolveState();Gr(this._mline,t,i.styleName,i.justification,i.scale,!1,i.elementOffsets)}}class jc extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.doc.database;let i=u.AcDbMLineJustification.Zero,n=t.cmlscale??1,r=t.cmlstyle||"STANDARD";const o=[];let a=!1;const l=()=>{const A=t.objects.mlineStyle.getAt(r);return xy((A==null?void 0:A.elements)??[],i,n)},c=A=>o.push(new u.AcGePoint3d(A)),h=()=>{o.length>1&&o.pop()},p=()=>{if(o.length<=1)return;const A=o[0],_=o[o.length-1];Py(A,_)||c(A),a=!0},m=async()=>{const A=new ne(d.t("jig.mline.justificationPrompt"));A.allowNone=!0,A.keywords.add(d.t("jig.mline.keywords.top.display"),d.t("jig.mline.keywords.top.global"),d.t("jig.mline.keywords.top.local")),A.keywords.add(d.t("jig.mline.keywords.zero.display"),d.t("jig.mline.keywords.zero.global"),d.t("jig.mline.keywords.zero.local")),A.keywords.add(d.t("jig.mline.keywords.bottom.display"),d.t("jig.mline.keywords.bottom.global"),d.t("jig.mline.keywords.bottom.local"));const _=await k.instance.editor.getKeywords(A);if(_.status===b.None)return!0;if(_.status!==b.Keyword)return!1;const C=_.stringResult??"";return C==="Top"?i=u.AcDbMLineJustification.Top:C==="Bottom"?i=u.AcDbMLineJustification.Bottom:i=u.AcDbMLineJustification.Zero,!0},g=async()=>{const A=new ie(d.t("jig.mline.scalePrompt"));A.allowNone=!0,A.allowZero=!0,A.allowNegative=!0,A.useDefaultValue=!0,A.defaultValue=n;const _=await k.instance.editor.getDouble(A);return _.status===b.None?!0:_.status!==b.OK?!1:(n=_.value??n,!0)},f=()=>{const A=[...t.objects.mlineStyle.entries()].map(([_])=>_);if(A.length<=0){this.showMessage(d.t("jig.mline.styleListEmpty"),"warning");return}this.showMessage(`${d.t("jig.mline.styleListHeader")} ${A.join(", ")}`,"info")},w=async()=>{for(;;){const A=new le(d.t("jig.mline.stylePrompt"));A.allowEmpty=!1,A.allowSpaces=!1;const _=await k.instance.editor.getString(A);if(_.status!==b.OK)return!1;const C=(_.stringResult??"").trim();if(C){if(C==="?"){f();continue}return r=C,!0}}},v=async A=>A==="Justification"?await m():A==="Scale"?await g():A==="Style"?await w():!0;for(;;){const A=new I(d.t("jig.mline.startPointWithOptions"));A.keywords.add(d.t("jig.mline.keywords.justification.display"),d.t("jig.mline.keywords.justification.global"),d.t("jig.mline.keywords.justification.local")),A.keywords.add(d.t("jig.mline.keywords.scale.display"),d.t("jig.mline.keywords.scale.global"),d.t("jig.mline.keywords.scale.local")),A.keywords.add(d.t("jig.mline.keywords.style.display"),d.t("jig.mline.keywords.style.global"),d.t("jig.mline.keywords.style.local"));const _=await k.instance.editor.getPoint(A);if(_.status===b.OK){c(_.value);break}if(_.status!==b.Keyword||!await v(_.stringResult??""))return}class x{buildPrompt(){const _=new I(d.t("jig.mline.nextPointWithOptions"));return _.keywords.add(d.t("jig.mline.keywords.justification.display"),d.t("jig.mline.keywords.justification.global"),d.t("jig.mline.keywords.justification.local")),_.keywords.add(d.t("jig.mline.keywords.scale.display"),d.t("jig.mline.keywords.scale.global"),d.t("jig.mline.keywords.scale.local")),_.keywords.add(d.t("jig.mline.keywords.style.display"),d.t("jig.mline.keywords.style.global"),d.t("jig.mline.keywords.style.local")),_.keywords.add(d.t("jig.mline.keywords.undo.display"),d.t("jig.mline.keywords.undo.global"),d.t("jig.mline.keywords.undo.local")),o.length>1&&_.keywords.add(d.t("jig.mline.keywords.close.display"),d.t("jig.mline.keywords.close.global"),d.t("jig.mline.keywords.close.local")),_.useDashedLine=!0,_.useBasePoint=!0,_.basePoint=new u.AcGePoint3d(o[o.length-1]),_.jig=new Oc(e.view,o,()=>({justification:i,scale:n,styleName:r,elementOffsets:l()})),_.allowNone=!0,_}async handleResult(_){if(_.status===b.OK)return c(_.value),"continue";if(_.status!==b.Keyword)return"finish";const C=_.stringResult??"";return C==="Undo"?(h(),"continue"):C==="Close"&&o.length>1?(p(),"finish"):await v(C)?"continue":"finish"}}const S=new We;if(S.setState(new x),await S.run(A=>k.instance.editor.getPoint(A)),o.length<2)return;const P=new u.AcDbMLine;Gr(P,o,r,i,n,a,l()),t.tables.blockTable.modelSpace.appendEntity(P),t.cmlstyle=r,t.cmlscale=n}}function Gr(s,e,t,i,n,r,o){if(e.length<=0){s.clearSegments();return}if(s.styleName=t,s.styleObjectHandle="",s.justification=i,s.scale=n,s.styleCount=o.length,s.closed=r,s.startPosition=e[0],e.length<2){s.clearSegments();return}s.segments=wy(e,o)}function wy(s,e){const t=vy(s);return s.slice(1).map((i,n)=>{const r=n+1,o=ky(t,r);return{position:i,direction:t[Math.min(r,t.length-1)],miterDirection:o.direction,elements:e.map(a=>({parameterCount:1,parameters:[a*o.offsetScale],fillCount:0,fillParameters:[]}))}})}function vy(s){const e=[];for(let t=0;t<s.length-1;t++){const i=s[t],n=s[t+1],r=Kr({x:n.x-i.x,y:n.y-i.y,z:n.z-i.z});e.push(r??{x:1,y:0,z:0})}return e}function ky(s,e){if(s.length<=0)return{direction:{x:0,y:1,z:0},offsetScale:1};if(e<=0)return{direction:Jn(s[0]),offsetScale:1};if(e>=s.length)return{direction:Jn(s[s.length-1]),offsetScale:1};const t=Jn(s[e-1]),i=Jn(s[e]),n=Kr({x:t.x+i.x,y:t.y+i.y,z:t.z+i.z});if(!n)return{direction:i,offsetScale:1};const r=Math.abs(Sy(n,i));return u.AcGeTol.isNonPositive(r)?{direction:n,offsetScale:1}:{direction:n,offsetScale:1/r}}function xy(s,e,t){if(s.length<=0)return[];let i=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(const o of s)o.offset<i&&(i=o.offset),o.offset>n&&(n=o.offset);let r=0;return e===u.AcDbMLineJustification.Top?r=-n:e===u.AcDbMLineJustification.Bottom&&(r=-i),s.map(o=>(o.offset+r)*t)}function Jn(s){return Kr({x:-s.y,y:s.x,z:0})??{x:0,y:1,z:0}}function Kr(s){const e=Math.sqrt(s.x*s.x+s.y*s.y+s.z*s.z);if(u.AcGeTol.isPositive(e))return{x:s.x/e,y:s.y/e,z:s.z/e}}function Sy(s,e){return s.x*e.x+s.y*e.y+s.z*e.z}function Py(s,e){return u.DEFAULT_TOL.equalPoint3d(s,e)}class Bc extends z{constructor(){super(),this.mtextEditor=new Ke,this.mode=F.Write}async execute(e){const t=new In(d.t("main.inputManager.firstCorner"),d.t("main.inputManager.secondCorner"));t.useBasePoint=!1,t.useDashedLine=!1;const i=await k.instance.editor.getBox(t);if(i.status!==b.OK||!i.value)return;const n=i.value,r=Math.max(Math.abs(n.max.x-n.min.x),1e-4),o=e.view,a=this.pixelsToWorldY(o,24),l={x:n.min.x,y:n.max.y,z:0},c=Array.from(new Set(k.instance.avaiableFonts.flatMap(g=>g.name).map(g=>g.trim()).filter(g=>g.length>0))),h=await this.mtextEditor.open({view:o,location:l,width:r,textHeight:a,toolbarFontFamilies:c});if(!h||!h.contents.trim())return;const m=new u.AcDbMText;m.location=h.location,m.contents=h.contents,m.width=h.width,m.height=h.height,m.lineSpacingFactor=h.lineSpacingFactor,m.attachmentPoint=h.attachmentPoint,e.doc.database.tables.blockTable.modelSpace.appendEntity(m)}pixelsToWorldY(e,t){const i=e.screenToWorld({x:0,y:0}),n=e.screenToWorld({x:0,y:t});return Math.max(Math.abs(n.y-i.y),1e-4)}}class Fc extends z{constructor(){super(),this.mode=F.Write}async execute(e){for(;;){const t=new I(d.t("jig.point.point")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK||!i.value)return;const n=new u.AcDbPoint;n.position=new u.AcGePoint3d(i.value),e.doc.database.tables.blockTable.modelSpace.appendEntity(n)}}}const Ay=3,Cy=1024;function _y(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function Ur(s,e){s.reset(!1),e.forEach((t,i)=>s.addVertexAt(i,t)),s.closed=!0}function zc(s,e,t,i){const n=_y(s,t);if(u.AcGeTol.isNonPositive(n))return;const r=Math.PI*2/e,o=Math.atan2(t.y-s.y,t.x-s.x),a=i==="Inscribed"?n:n/Math.cos(Math.PI/e);if(!Number.isFinite(a)||u.AcGeTol.isNonPositive(a))return;const l=i==="Inscribed"?o:o+r/2,c=[];for(let h=0;h<e;h++){const p=l+h*r;c.push(new u.AcGePoint2d(s.x+a*Math.cos(p),s.y+a*Math.sin(p)))}return c}function Nc(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=Math.hypot(i,n);if(u.AcGeTol.isNonPositive(r))return;const o=Math.PI*2/t,a=[new u.AcGePoint2d(s),new u.AcGePoint2d(e)];let l=e.x,c=e.y,h=i,p=n;for(let m=2;m<t;m++){const g=h*Math.cos(o)-p*Math.sin(o),f=h*Math.sin(o)+p*Math.cos(o);l+=g,c+=f,a.push(new u.AcGePoint2d(l,c)),h=g,p=f}return a}class Ey extends G{constructor(e,t,i,n){super(e),this._polyline=new u.AcDbPolyline,this._center=t,this._sides=i,this._modeProvider=n}get entity(){return this._polyline}update(e){const t=zc(this._center,this._sides,e,this._modeProvider());t&&Ur(this._polyline,t)}}class Ly extends G{constructor(e,t,i){super(e),this._polyline=new u.AcDbPolyline,this._firstPoint=t,this._sides=i}get entity(){return this._polyline}update(e){const t=Nc(this._firstPoint,e,this._sides);t&&Ur(this._polyline,t)}}const Ji=class Ji extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=await this.promptSides();if(t==null)return;const i=new I(d.t("jig.polygon.centerOrEdge"));this.addKeyword(i,"edge");const n=await k.instance.editor.getPoint(i);if(n.status===b.Keyword){n.stringResult==="Edge"&&await this.runEdgeFlow(e,t);return}n.status===b.OK&&await this.runCenterFlow(e,t,n.value)}addKeyword(e,t){e.keywords.add(d.t(`jig.polygon.keywords.${t}.display`),d.t(`jig.polygon.keywords.${t}.global`),d.t(`jig.polygon.keywords.${t}.local`))}appendPolygon(e,t){const i=new u.AcDbPolyline;Ur(i,t),e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){this.notify(d.t(`jig.polygon.invalid.${e}`),"warning")}async promptSides(){for(;;){const e=Ji._lastSides,t=new le(d.t("jig.polygon.numberOfSides"));t.allowEmpty=!0,t.allowSpaces=!1,t.defaultValue=String(e),t.useDefaultValue=!0;const i=await k.instance.editor.getString(t);if(i.status!==b.OK)return;const n=(i.stringResult??"").trim(),r=n===""?e:Number(n);if(Number.isInteger(r)&&r>=Ay&&r<=Cy)return Ji._lastSides=r,r;this.warnInvalidInput("sides")}}async runCenterFlow(e,t,i){let n="Inscribed";for(;;){const r=new I(d.t("jig.polygon.radiusOrType"));this.addKeyword(r,"inscribed"),this.addKeyword(r,"circumscribed"),r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(i),r.jig=new Ey(e.view,i,t,()=>n);const o=await k.instance.editor.getPoint(r);if(o.status===b.Keyword){const l=o.stringResult??"";if(l==="Inscribed"){n="Inscribed";continue}if(l==="Circumscribed"){n="Circumscribed";continue}return}if(o.status!==b.OK)return;const a=zc(i,t,o.value,n);if(!a){this.warnInvalidInput("radius");continue}this.appendPolygon(e,a);return}}async runEdgeFlow(e,t){const i=new I(d.t("jig.polygon.edgeStart")),n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new I(d.t("jig.polygon.edgeEnd"));o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new u.AcGePoint3d(r),o.jig=new Ly(e.view,r,t);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)return;const l=Nc(r,a.value,t);if(!l){this.warnInvalidInput("edge");return}this.appendPolygon(e,l)}};Ji._lastSides=4;let Qn=Ji;class Rc extends G{constructor(e,t,i,n,r){super(e),this._hasTemp=!1,this._polyline=new u.AcDbPolyline,this._points=t,this._bulges=i,this._currentBulge=n,this._bulgeProvider=r,this._baseCount=t.length,this._appliedBulge=this._bulges[this._baseCount-1],this.addBaseVertices()}get entity(){return this._polyline}update(e){var r;if(this._baseCount===0)return;this._hasTemp&&(this._polyline.removeVertexAt(this._baseCount),this._hasTemp=!1);const t=this._baseCount-1,n=((r=this._bulgeProvider)==null?void 0:r.call(this,e))??this._currentBulge??this._bulges[t];if(n!==this._appliedBulge){const o=this._points[t];this._polyline.removeVertexAt(t),this._polyline.addVertexAt(t,o,n),this._appliedBulge=n}this._polyline.addVertexAt(this._baseCount,new u.AcGePoint2d(e),void 0),this._hasTemp=!0}addBaseVertices(){this._points.forEach((e,t)=>this._polyline.addVertexAt(t,e,this._bulges[t]))}}class Ty extends G{constructor(e,t,i){super(e),this._polyline=new u.AcDbPolyline,t.forEach((n,r)=>this._polyline.addVertexAt(r,n,i[r]))}get entity(){return this._polyline}update(e){}}class Vc extends z{constructor(){super(),this.mode=F.Write}complementBulge(e){if(u.AcGeTol.equalToZero(e))return e;const t=4*Math.atan(e),n=(Math.sign(t)||1)*(Math.PI*2-Math.abs(t));return u.AcGeTol.equalToZero(n)?e:Math.tan(n/4)}flipArcBulgeForCtrl(e){return-this.complementBulge(e)}computeArcCenterFromBulge(e,t,i){const n=t.x-e.x,r=t.y-e.y,o=Math.hypot(n,r);if(u.AcGeTol.isNonPositive(o))return;const a=(e.x+t.x)/2,l=(e.y+t.y)/2,c=-r/o,h=n/o,p=o/2*i;return{x:a+c*p,y:l+h*p}}getGeometricTangentAtPoint(e,t,i){const n=e.x-t.x,r=e.y-t.y;return i?Math.atan2(-r,n):Math.atan2(r,-n)}getArcTangentAtEnd(e,t,i){const n=this.computeArcCenterFromBulge(e,t,i);if(n)return this.getGeometricTangentAtPoint(t,n,i>=0)}getIncomingTangentRadians(e,t){if(e.length<2)return 0;const i=e[e.length-1],n=e[e.length-2],r=t[e.length-2];return r==null||u.AcGeTol.equalToZero(r)?Math.atan2(i.y-n.y,i.x-n.x):this.getArcTangentAtEnd(n,i,r)??Math.atan2(i.y-n.y,i.x-n.x)}computeBulgeFromTangentDirection(e,t,i){const n=Math.cos(i),r=Math.sin(i),o=t.x-e.x,a=t.y-e.y,l=-r,c=n,h=2*(o*l+a*c);if(u.AcGeTol.equalToZero(h))return;const p=(o*o+a*a)/h;if(!Number.isFinite(p))return;const m={x:e.x+l*p,y:e.y+c*p};return this.computeBulgeFromCenterWithTangent(e,t,m,i)}computeBulgeFromCenterWithTangent(e,t,i,n){const r=e.x-i.x,o=e.y-i.y,a=t.x-i.x,l=t.y-i.y,c=Math.cos(n),h=Math.sin(n),p=t.x-e.x,m=t.y-e.y,g=r*h-o*c;let f;u.AcGeTol.isPositive(Math.abs(g))?f=g>0:f=p*h-m*c>=0;const w=Math.atan2(o,r),v=Math.atan2(l,a);let x;if(f?(x=v-w,u.AcGeTol.isNonPositive(x)&&(x+=Math.PI*2)):(x=w-v,u.AcGeTol.isNonPositive(x)&&(x+=Math.PI*2)),!!u.AcGeTol.great(u.TAU-x,0))return f?Math.tan(x/4):-Math.tan(x/4)}computeBulgeFromTangentAndIncludedAngle(e,t,i,n){const r=Math.cos(i),o=Math.sin(i),a=t.x-e.x,l=t.y-e.y,c=-o,h=r,p=2*(a*c+l*h);if(u.AcGeTol.equalToZero(p))return;const m=(a*a+l*l)/p;if(!Number.isFinite(m))return;const g={x:e.x+c*m,y:e.y+h*m},f=this.computeBulgeFromCenterWithTangent(e,t,g,i);if(f==null)return;const w=Math.tan(n/4);if(Number.isFinite(w))return Math.sign(f)*Math.abs(w)}computeBulgeFromCenter(e,t,i){const n=e.x-i.x,r=e.y-i.y,o=t.x-i.x,a=t.y-i.y,l=n*a-r*o,c=n*o+r*a,h=Math.atan2(l,c);if(Number.isFinite(h))return Math.tan(h/4)}computeCircleCenter(e,t,i){const n=e.x,r=e.y,o=t.x,a=t.y,l=i.x,c=i.y,h=n-o,p=r-a,m=n-l,g=r-c,f=(n*n-o*o+r*r-a*a)/2,w=(n*n-l*l+r*r-c*c)/2,v=h*g-p*m;if(u.AcGeTol.equalToZero(v))return;const x=(g*f-p*w)/v,S=(-m*f+h*w)/v;return new u.AcGePoint2d(x,S)}computeBulgeFromThreePoints(e,t,i){const n=this.computeCircleCenter(e,t,i);if(n)return this.computeBulgeFromCenter(e,i,n)}computeBulgeFromRadius(e,t,i){const n=Math.abs(i),r=t.x-e.x,o=t.y-e.y,a=Math.hypot(r,o);if(a===0||a>2*n)return;const l=(e.x+t.x)/2,c=(e.y+t.y)/2,h=Math.sqrt(Math.max(0,n*n-a*a/4)),p=-o/a,m=r/a,g=i>=0?1:-1,f=l+p*h*g,w=c+m*h*g,v=new u.AcGePoint2d(f,w);return this.computeBulgeFromCenter(e,t,v)}async execute(e){k.instance.editor.resetInputToggles();const t=[],i=[];let n=!1;const r=j=>j==null?j:k.instance.editor.getInputToggles().ctrlArcFlip?this.flipArcBulgeForCtrl(j):j,o=(j,L,N)=>this.computeBulgeFromCenter(j,L,N),a=(j,L,N)=>this.computeBulgeFromThreePoints(j,L,N),l=(j,L,N)=>this.computeBulgeFromRadius(j,L,N),c=()=>this.getIncomingTangentRadians(t,i),h=j=>{const L=f();if(L)return this.computeBulgeFromTangentDirection(L,j,c())},p=(j,L,N,R)=>this.computeBulgeFromTangentAndIncludedAngle(j,L,N,R),m=()=>new Ty(e.view,t,i),g=(j,L)=>new Rc(e.view,t,i,j,L),f=()=>t[t.length-1],w=j=>{t.length>0&&(i[t.length-1]=j)},v=j=>{t.push(new u.AcGePoint2d(j)),i.push(void 0)},x=()=>{t.length<=1||(t.pop(),i.pop(),i[i.length-1]=void 0)},S=j=>j!==b.OK&&j!==b.Keyword;class P{constructor(L){this.machine=L}buildPrompt(){const L=new I(d.t("jig.polyline.nextPointWithOptions"));L.keywords.add(d.t("jig.polyline.keywords.arc.display"),d.t("jig.polyline.keywords.arc.global"),d.t("jig.polyline.keywords.arc.local")),L.keywords.add(d.t("jig.polyline.keywords.undo.display"),d.t("jig.polyline.keywords.undo.global"),d.t("jig.polyline.keywords.undo.local")),L.keywords.add(d.t("jig.polyline.keywords.close.display"),d.t("jig.polyline.keywords.close.global"),d.t("jig.polyline.keywords.close.local")),L.useDashedLine=!0,L.useBasePoint=!0;const N=f();return N&&(L.basePoint=new u.AcGePoint3d(N)),L.jig=g(void 0),L.allowNone=!0,L}async handleResult(L){if(L.status===b.Keyword){const N=L.stringResult??"";if(N==="Arc")this.machine.setState(new A(this.machine));else if(N==="Undo")x();else if(N==="Close"&&t.length>1)return n=!0,w(void 0),"finish";return"continue"}return L.status===b.OK?(w(void 0),v(L.value),"continue"):"finish"}}class A{constructor(L){this.machine=L}buildPrompt(){const L=new I(d.t("jig.polyline.nextPointWithArcOptions"));L.keywords.add(d.t("jig.polyline.keywords.angle.display"),d.t("jig.polyline.keywords.angle.global"),d.t("jig.polyline.keywords.angle.local")),L.keywords.add(d.t("jig.polyline.keywords.center.display"),d.t("jig.polyline.keywords.center.global"),d.t("jig.polyline.keywords.center.local")),L.keywords.add(d.t("jig.polyline.keywords.secondPoint.display"),d.t("jig.polyline.keywords.secondPoint.global"),d.t("jig.polyline.keywords.secondPoint.local")),L.keywords.add(d.t("jig.polyline.keywords.radius.display"),d.t("jig.polyline.keywords.radius.global"),d.t("jig.polyline.keywords.radius.local")),L.keywords.add(d.t("jig.polyline.keywords.line.display"),d.t("jig.polyline.keywords.line.global"),d.t("jig.polyline.keywords.line.local")),L.keywords.add(d.t("jig.polyline.keywords.undo.display"),d.t("jig.polyline.keywords.undo.global"),d.t("jig.polyline.keywords.undo.local")),L.keywords.add(d.t("jig.polyline.keywords.close.display"),d.t("jig.polyline.keywords.close.global"),d.t("jig.polyline.keywords.close.local")),L.useDashedLine=!0,L.useBasePoint=!0;const N=f();return N&&(L.basePoint=new u.AcGePoint3d(N)),L.jig=g(void 0,R=>r(h(R))),L.allowNone=!0,L}async handleResult(L){if(L.status===b.OK){const W=h(L.value);return W===void 0||(w(r(W)),v(L.value)),"continue"}if(L.status!==b.Keyword)return"finish";const N=L.stringResult??"";if(N==="Line")return this.machine.setState(new P(this.machine)),"continue";if(N==="Undo")return x(),"continue";if(N==="Close"&&t.length>1)return n=!0,w(void 0),"finish";const R=f();if(!R)return"finish";if(N==="Angle"){const W=new ie(d.t("jig.polyline.arcAngle"));W.jig=m();const X=await k.instance.editor.getDouble(W);if(S(X.status))return"finish";const $=new I(d.t("jig.polyline.arcEndPoint"));$.useDashedLine=!0,$.useBasePoint=!0,$.basePoint=new u.AcGePoint3d(R);const J=(X.value??0)*(Math.PI/180),se=c();$.jig=g(void 0,jo=>r(p(R,jo,se,J)));const re=await k.instance.editor.getPoint($);if(S(re.status))return"finish";const Mt=p(R,re.value,se,J);return Mt===void 0||(w(r(Mt)),v(re.value)),"continue"}if(N==="Center"){const W=new I(d.t("jig.polyline.arcCenter"));W.jig=m();const X=await k.instance.editor.getPoint(W);if(S(X.status))return"finish";const $=new I(d.t("jig.polyline.arcEndPoint"));$.useDashedLine=!0,$.useBasePoint=!0,$.basePoint=new u.AcGePoint3d(R),$.jig=g(void 0,re=>r(o(R,re,X.value)));const J=await k.instance.editor.getPoint($);if(S(J.status))return"finish";const se=o(R,J.value,X.value);return se===void 0||(w(r(se)),v(J.value)),"continue"}if(N==="SecondPoint"){const W=new I(d.t("jig.polyline.arcSecondPoint"));W.jig=m(),W.useDashedLine=!0,W.useBasePoint=!0,W.basePoint=new u.AcGePoint3d(R);const X=await k.instance.editor.getPoint(W);if(S(X.status))return"finish";const $=new I(d.t("jig.polyline.arcEndPoint"));$.useDashedLine=!0,$.useBasePoint=!0,$.basePoint=new u.AcGePoint3d(R),$.jig=g(void 0,re=>r(a(R,X.value,re)));const J=await k.instance.editor.getPoint($);if(S(J.status))return"finish";const se=a(R,X.value,J.value);return se===void 0||(w(r(se)),v(J.value)),"continue"}if(N==="Radius"){const W=new ie(d.t("jig.polyline.arcRadius"));W.jig=m();const X=await k.instance.editor.getDouble(W);if(S(X.status))return"finish";const $=new I(d.t("jig.polyline.arcEndPoint"));$.useDashedLine=!0,$.useBasePoint=!0,$.basePoint=new u.AcGePoint3d(R),$.jig=g(void 0,re=>r(l(R,re,X.value??0)));const J=await k.instance.editor.getPoint($);if(S(J.status))return"finish";const se=l(R,J.value,X.value??0);return se===void 0||(w(r(se)),v(J.value)),"continue"}return"continue"}}const _=new I(d.t("jig.polyline.firstPoint")),C=await k.instance.editor.getPoint(_);if(C.status!==b.OK)return;v(C.value);const O=new We;if(O.setState(new P(O)),await O.run(j=>k.instance.editor.getPoint(j)),t.length>=2){const j=e.doc.database,L=new u.AcDbPolyline;t.forEach((N,R)=>L.addVertexAt(R,N,i[R])),n&&(L.closed=!0),j.tables.blockTable.modelSpace.appendEntity(L)}}}function Gc(s,e){const t=new u.AcGePoint3d(e).sub(s);if(u.AcGeTol.isPositive(t.length()))return t.normalize()}class Iy extends G{constructor(e,t){super(e),this._startPoint=new u.AcGePoint3d(t),this._ray=new u.AcDbRay,this._ray.basePoint=new u.AcGePoint3d(t),this._ray.unitDir=new u.AcGePoint3d(1,0,0)}get entity(){return this._ray}update(e){const t=Gc(this._startPoint,e);t&&(this._ray.basePoint=new u.AcGePoint3d(this._startPoint),this._ray.unitDir=t)}}class Kc extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.doc.database,i=new I(d.t("jig.ray.startPoint")),n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=new u.AcGePoint3d(n.value);for(;;){const o=new I(d.t("jig.ray.throughPoint"));o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new u.AcGePoint3d(r),o.jig=new Iy(e.view,r);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)break;const l=Gc(r,a.value);if(!l)continue;const c=new u.AcDbRay;c.basePoint=new u.AcGePoint3d(r),c.unitDir=l,t.tables.blockTable.modelSpace.appendEntity(c)}}}const My=Math.tan(Math.PI/8),Dy={chamferDist1:0,chamferDist2:0,filletRadius:0,width:0,elevation:0,thickness:0,rotation:0};function yt(s,e){s.keywords.add(d.t(`jig.rect.keywords.${e}.display`),d.t(`jig.rect.keywords.${e}.global`),d.t(`jig.rect.keywords.${e}.local`))}function Oy(s,e){s.keywords.add(d.t(`jig.rect.keywords.${e}.display`),d.t(`jig.rect.keywords.${e}.global`),d.t(`jig.rect.keywords.${e}.local`))}function jy(s,e,t){const i=Math.cos(t),n=Math.sin(t);return new u.AcGePoint2d(s.x+e.x*i-e.y*n,s.y+e.x*n+e.y*i)}function By(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=Math.cos(t),o=Math.sin(t);return new u.AcGePoint2d(i*r+n*o,-i*o+n*r)}function qt(s){return Number.isFinite(s??NaN)?Math.max(0,s??0):0}function Hr(s,e){return[{point:new u.AcGePoint2d(0,0)},{point:new u.AcGePoint2d(s,0)},{point:new u.AcGePoint2d(s,e)},{point:new u.AcGePoint2d(0,e)}]}function Uc(s,e,t,i){const n=s>=0?1:-1,r=e>=0?1:-1,o=Math.abs(s),a=Math.abs(e),l=Math.min(qt(t),o/2),c=Math.min(qt(i),a/2);if(u.AcGeTol.isNonPositive(l)&&u.AcGeTol.isNonPositive(c))return Hr(s,e);const h=new u.AcGePoint2d(n*l,0),p=new u.AcGePoint2d(0,r*c),m=new u.AcGePoint2d(s-n*l,0),g=new u.AcGePoint2d(s,r*c),f=new u.AcGePoint2d(s,e-r*c),w=new u.AcGePoint2d(s-n*l,e),v=new u.AcGePoint2d(n*l,e),x=new u.AcGePoint2d(0,e-r*c);return[{point:h},{point:m},{point:g},{point:f},{point:w},{point:v},{point:x},{point:p}]}function Fy(s,e,t){const i=Math.abs(s),n=Math.abs(e),r=Math.min(qt(t),i/2,n/2);if(u.AcGeTol.isNonPositive(r))return Hr(s,e);const o=Uc(s,e,r,r),l=(s*e>=0?1:-1)*My;return o.map((c,h)=>({point:c.point,bulge:h%2===1?l:void 0}))}function zy(s,e,t){return u.AcGeTol.isPositive(t.filletRadius)?Fy(s,e,t.filletRadius):u.AcGeTol.isPositive(t.chamferDist1)||u.AcGeTol.isPositive(t.chamferDist2)?Uc(s,e,t.chamferDist1,t.chamferDist2):Hr(s,e)}function Wr(s,e,t,i){let n=0,r=0;if(t.mode==="corner"){const l=By(e,t.secondPoint,i.rotation);n=l.x,r=l.y}else n=t.length,r=t.width;if(u.AcGeTol.equalToZero(n)||u.AcGeTol.equalToZero(r))return!1;s.reset(!1);const o=zy(n,r,i),a=qt(i.width);return o.forEach((l,c)=>{const h=jy(e,l.point,i.rotation);u.AcGeTol.isPositive(a)?s.addVertexAt(c,h,l.bulge,a,a):s.addVertexAt(c,h,l.bulge)}),s.elevation=i.elevation,s.closed=!0,!0}class Hc extends G{constructor(e,t,i){super(e),this._rect=new u.AcDbPolyline,this._firstPoint=new u.AcGePoint2d(t),this._settingsProvider=i}get entity(){return this._rect}update(e){Wr(this._rect,this._firstPoint,{mode:"corner",secondPoint:e},this._settingsProvider())}}class Jt extends G{constructor(e,t,i,n){super(e),this._rect=new u.AcDbPolyline,Wr(this._rect,t,i,n)}get entity(){return this._rect}update(e){}}function $r(s){return{chamferDist1:s.chamferDist1,chamferDist2:s.chamferDist2,filletRadius:s.filletRadius,width:s.width,elevation:s.elevation,thickness:s.thickness,rotation:s.rotation}}function et(s){return Number.isFinite(s??NaN)&&u.AcGeTol.isPositive(s??0)}const Qi=class Qi extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=$r(Qi._settings),i=await this.promptFirstCorner(t);if(!i)return;const n=await this.promptSecondInput(e,i,t);if(!n)return;const r=new u.AcDbPolyline;if(!Wr(r,i,n,t)){this.warnRectMessage("invalidRect");return}u.AcGeTol.isPositive(t.thickness)&&this.warnRectMessage("thicknessNotSupported"),e.doc.database.tables.blockTable.modelSpace.appendEntity(r),Qi._settings=$r(t)}warnRectMessage(e){this.notify(d.t(`jig.rect.${e}`),"warning")}async promptFirstCorner(e){for(;;){const t=new I(d.t("jig.rect.firstPointWithOptions"));yt(t,"chamfer"),yt(t,"elevation"),yt(t,"fillet"),yt(t,"thickness"),yt(t,"width");const i=await k.instance.editor.getPoint(t);if(i.status===b.OK)return i.value;if(i.status!==b.Keyword)return;const n=i.stringResult??"";if(n==="Chamfer"){if(!await this.promptChamfer(e))return}else if(n==="Elevation"){if(!await this.promptElevation(e))return}else if(n==="Fillet"){if(!await this.promptFillet(e))return}else if(n==="Thickness"){if(!await this.promptThickness(e))return}else if(n==="Width"&&!await this.promptWidth(e))return}}async promptSecondInput(e,t,i){let n;class r{constructor(l){this.cmd=l}buildPrompt(){const l=new I(d.t("jig.rect.otherCornerWithOptions"));return yt(l,"area"),yt(l,"dimensions"),yt(l,"rotation"),l.useDashedLine=!1,l.useBasePoint=!0,l.basePoint=new u.AcGePoint3d(t),l.jig=new Hc(e.view,t,()=>i),l}async handleResult(l){if(l.status===b.OK)return n={mode:"corner",secondPoint:l.value},"finish";if(l.status!==b.Keyword)return"finish";const c=l.stringResult??"";if(c==="Rotation")return await this.cmd.promptRotation(e,t,i)?"continue":"finish";if(c==="Dimensions"){const h=await this.cmd.promptDimensions(e,t,i);return h&&(n=h),"finish"}if(c==="Area"){const h=await this.cmd.promptArea(e,t,i);return h&&(n=h),"finish"}return"continue"}}const o=new We;return o.setState(new r(this)),await o.run(a=>k.instance.editor.getPoint(a)),n}async promptPositiveDouble(e,t){for(;;){const i=new ie(e);i.allowNegative=!1,i.allowZero=!1,t&&(i.jig=t);const n=await k.instance.editor.getDouble(i);if(n.status!==b.OK)return;if(et(n.value))return n.value;this.warnRectMessage("invalidPositive")}}async promptChamfer(e){const t=await this.promptPositiveDouble(d.t("jig.rect.chamferFirst"));if(!et(t))return!1;const i=await this.promptPositiveDouble(d.t("jig.rect.chamferSecond"));return et(i)?(e.chamferDist1=t,e.chamferDist2=i,e.filletRadius=0,!0):!1}async promptFillet(e){const t=await this.promptPositiveDouble(d.t("jig.rect.filletRadius"));return et(t)?(e.filletRadius=t,e.chamferDist1=0,e.chamferDist2=0,!0):!1}async promptWidth(e){const t=new ie(d.t("jig.rect.segmentWidth"));t.allowNegative=!1,t.allowZero=!0;const i=await k.instance.editor.getDouble(t);return i.status!==b.OK?!1:(e.width=qt(i.value),!0)}async promptElevation(e){const t=new ie(d.t("jig.rect.elevationValue"));t.allowNegative=!0,t.allowZero=!0;const i=await k.instance.editor.getDouble(t);return i.status!==b.OK?!1:(e.elevation=i.value??0,!0)}async promptThickness(e){const t=new ie(d.t("jig.rect.thicknessValue"));t.allowNegative=!1,t.allowZero=!0;const i=await k.instance.editor.getDouble(t);return i.status!==b.OK?!1:(e.thickness=qt(i.value),!0)}async promptRotation(e,t,i){const n=new xe(d.t("jig.rect.rotationAngle"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(t),n.allowNegative=!0,n.allowZero=!0,n.jig=new Jt(e.view,t,{mode:"dimensions",length:1,width:1},i);const r=await k.instance.editor.getAngle(n);return r.status!==b.OK?!1:(i.rotation=(r.value??0)*Math.PI/180,!0)}async promptDimensions(e,t,i){const n={mode:"dimensions",length:1,width:1},r=await this.promptPositiveDouble(d.t("jig.rect.dimensionLength"),new Jt(e.view,t,n,i));if(!et(r))return;const o=await this.promptPositiveDouble(d.t("jig.rect.dimensionWidth"),new Jt(e.view,t,{mode:"dimensions",length:r,width:1},i));if(et(o))return{mode:"dimensions",length:r,width:o}}async promptArea(e,t,i){const n=await this.promptPositiveDouble(d.t("jig.rect.areaValue"),new Jt(e.view,t,{mode:"dimensions",length:1,width:1},i));if(!et(n))return;const r=new ie(d.t("jig.rect.areaLengthOrWidth"));Oy(r,"rectWidth"),r.allowNegative=!1,r.allowZero=!1,r.jig=new Jt(e.view,t,{mode:"dimensions",length:1,width:1},i);const o=await k.instance.editor.getDouble(r);if(o.status===b.Keyword){if(o.stringResult!=="Width")return;const l=await this.promptPositiveDouble(d.t("jig.rect.areaSpecifyWidth"),new Jt(e.view,t,{mode:"dimensions",length:1,width:1},i));return et(l)?{mode:"dimensions",length:(n??0)/(l??1),width:l}:void 0}if(o.status!==b.OK||!et(o.value))return;const a=o.value;return{mode:"dimensions",length:a,width:(n??0)/a}}};Qi._settings=$r(Dy);let es=Qi;const Yr=1,Ny=.005,Ry=.1;function Wc(s){const e=Math.max(1,s.width),t=Math.max(1,s.height),i=s.screenToWorld({x:0,y:0}),n=s.screenToWorld({x:e,y:t});return Math.hypot(n.x-i.x,n.y-i.y)}function $c(s){const t=Wc(s)*Ny;return Number.isFinite(t)&&t>0?t:1}function Pt(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function Zr(s,e){const t=Math.min(s.x,e.x),i=Math.max(s.x,e.x),n=Math.min(s.y,e.y),r=Math.max(s.y,e.y);return[new u.AcGePoint2d(t,n),new u.AcGePoint2d(i,n),new u.AcGePoint2d(i,r),new u.AcGePoint2d(t,r)]}function Yc(s){let e=0;const t=s.length;for(let i=0;i<t;i++){const n=s[i],r=s[(i+1)%t];e+=n.x*r.y-r.x*n.y}return e/2}function Zc(s){const e=s.map(t=>new u.AcGePoint2d(t.x,t.y));return e.length>=3&&Yc(e)<0&&e.reverse(),e}function Xc(s,e){if(s.length<2)return 0;let t=0;const i=e?s.length:s.length-1;for(let n=0;n<i;n++){const r=s[n],o=s[(n+1)%s.length];t+=Pt(r,o)}return t}function Vy(s,e,t){const i=Xc(s,e);let n=i>0?(t%i+i)%i:0;const r=e?s.length:s.length-1;for(let a=0;a<r;a++){const l=s[a],c=s[(a+1)%s.length],h=Pt(l,c);if(n<=h||a===r-1){const p=h>0?n/h:0;return new u.AcGePoint2d(l.x+(c.x-l.x)*p,l.y+(c.y-l.y)*p)}n-=h}const o=s[e?0:s.length-1];return new u.AcGePoint2d(o.x,o.y)}function Gy(s,e){if(!e)return 1;const t=Math.sin(s*12.9898+78.233)*43758.5453;return .75+(t-Math.floor(t))*.5}function Ky(s,e,t){const i=Math.max(e*.35,s*1e-4),n=[];let r=s,o=0;for(;r>i*.5;){let a=e*Gy(o,t);if(a=Math.min(Math.max(a,i),r),r-a<i*.5&&(a=r),n.push(a),r-=a,o++,n.length>4096)break}return n.length===0&&n.push(s),n}function qc(s,e,t,i){if(e.length<2)return!1;const n=t?Zc(e):e,r=Xc(n,t);if(!u.AcGeTol.isPositive(r))return!1;const o=Math.max(i.arcLength,r*1e-4),a=Ky(r,o,i.variance!==!1);if(t&&a.length<3){const m=r/3;a.length=0,a.push(m,m,m)}const l=i.reverse?-Yr:Yr,c=i.style==="calligraphy",h=c?o*Ry:void 0;s.reset(!1);let p=0;return a.forEach((m,g)=>{const f=Vy(n,t,p);c&&h!=null?s.addVertexAt(g,f,l,0,h):s.addVertexAt(g,f,l),p+=m}),s.closed=t,s.numberOfVertices>=2}function Jc(s,e,t){const i=Pt(s,e),n=Math.max(1,Math.ceil(i/Math.max(t,1e-8))),r=[];for(let o=0;o<n;o++){const a=o/n;r.push(new u.AcGePoint2d(s.x+(e.x-s.x)*a,s.y+(e.y-s.y)*a))}return r}function Uy(s,e,t,i){if(Math.abs(t)<1e-12)return Jc(s,e,i);const n=e.x-s.x,r=e.y-s.y,o=Math.hypot(n,r);if(!u.AcGeTol.isPositive(o))return[new u.AcGePoint2d(s.x,s.y)];const a=t>=0?1:-1,l=4*Math.atan(Math.abs(t)),c=o/(2*Math.sin(l/2)),h=(s.x+e.x)/2,p=(s.y+e.y)/2,m=-r/o,g=n/o,f=c*Math.cos(l/2),w=h+m*f*a,v=p+g*f*a,x=Math.atan2(s.y-v,s.x-w),S=l*a,P=Math.abs(c*S),A=Math.max(2,Math.ceil(P/Math.max(i,1e-8))),_=[];for(let C=0;C<A;C++){const O=x+S*C/A;_.push(new u.AcGePoint2d(w+c*Math.cos(O),v+c*Math.sin(O)))}return _}function Hy(s){var n;const e=(n=s._geo)==null?void 0:n.vertices;if(e&&e.length>1)return e.map(r=>({x:r.x,y:r.y,bulge:r.bulge??0}));const t=s.numberOfVertices,i=s.getBulgeAt;return Array.from({length:t},(r,o)=>{const a=s.getPoint2dAt(o);return{x:a.x,y:a.y,bulge:(i==null?void 0:i(o))??0}})}function Wy(s,e){const t=Hy(s);if(t.length<2)return[];const i=[],n=s.closed?t.length:t.length-1;for(let r=0;r<n;r++){const o=t[r],a=t[(r+1)%t.length];i.push(...Uy(o,a,o.bulge,e))}if(!s.closed){const r=t[t.length-1];i.push(new u.AcGePoint2d(r.x,r.y))}return i}function $y(s,e){const t=s.radius;if(!u.AcGeTol.isPositive(t))return[];const i=2*Math.PI*t,n=Math.max(8,Math.ceil(i/Math.max(e,1e-8))),r=s.center,o=[];for(let a=0;a<n;a++){const l=a/n*Math.PI*2;o.push(new u.AcGePoint2d(r.x+t*Math.cos(l),r.y+t*Math.sin(l)))}return o}function Yy(s,e){const t=s.majorAxisRadius,i=s.minorAxisRadius;if(!u.AcGeTol.isPositive(t)||!u.AcGeTol.isPositive(i))return[];const n=s._geo,r=(n==null?void 0:n.majorAxis)??{x:1,y:0},o=Math.hypot(r.x,r.y)||1,a=r.x/o,l=r.y/o,c=-l,h=a,p=Math.PI*(3*(t+i)-Math.sqrt((3*t+i)*(t+3*i))),m=Math.max(12,Math.ceil(p/Math.max(e,1e-8))),g=s.center,f=s.startAngle??0;let v=(s.endAngle??Math.PI*2)-f;v<=0&&(v+=Math.PI*2);const S=Math.abs(v-Math.PI*2)<1e-6?m:m+1,P=[];for(let A=0;A<S;A++){const _=f+v*A/m,C=t*Math.cos(_),O=i*Math.sin(_);P.push(new u.AcGePoint2d(g.x+a*C+c*O,g.y+l*C+h*O))}return P}function Zy(s,e){var o;const t=s._geo,i=(o=t==null?void 0:t.fitPoints)!=null&&o.length?t.fitPoints:t==null?void 0:t.controlPoints;if(!i||i.length<2)return[];const n=[],r=s.closed?i.length:i.length-1;for(let a=0;a<r;a++){const l=i[a],c=i[(a+1)%i.length];n.push(...Jc(l,c,e))}if(!s.closed){const a=i[i.length-1];n.push(new u.AcGePoint2d(a.x,a.y))}return n}function Qc(s,e){if(s instanceof u.AcDbPolyline){const t=Wy(s,e);return t.length>=2?{points:t,closed:s.closed}:void 0}if(s instanceof u.AcDbCircle){const t=$y(s,e);return t.length>=2?{points:t,closed:!0}:void 0}if(s instanceof u.AcDbEllipse){const t=Yy(s,e),i=s.startAngle??0;let r=(s.endAngle??Math.PI*2)-i;for(;r<0;)r+=Math.PI*2;const o=r<1e-6||Math.abs(r-Math.PI*2)<.001;return t.length>=2?{points:t,closed:o}:void 0}if(s instanceof u.AcDbSpline){const t=Zy(s,e);return t.length>=2?{points:t,closed:!!s.closed}:void 0}}function Xr(s,e,t){return Pt(s,e)<=Math.max(t*.5,1e-6)}const Xy={mode:"rectangular",style:"normal",variance:!0};function Li(s,e){s.keywords.add(d.t(`jig.revcloud.keywords.${e}.display`),d.t(`jig.revcloud.keywords.${e}.global`),d.t(`jig.revcloud.keywords.${e}.local`))}function $e(s){return new u.AcGePoint2d(s.x,s.y)}function At(s,e,t,i,n=!1){return qc(s,e,t,{arcLength:i.arcLength??1,style:i.style,variance:i.variance,reverse:n})}class ed extends G{constructor(e,t,i,n){super(e),this._cloud=new u.AcDbPolyline,this._path=t.map($e),this._closed=i,this._settings=n,this.rebuild()}get entity(){return this._cloud}updatePath(e,t){this._path=e.map($e),this._closed=t,this.rebuild()}update(e){if(this._path.length===0)return;const t=[...this._path,$e(e)],i=this._closed&&t.length>=3;At(this._cloud,t,i,this._settings)}rebuild(){if(this._path.length<2){this._cloud.reset(!1);return}At(this._cloud,this._path,this._closed,this._settings)}}class qy extends G{constructor(e,t,i){super(e),this._cloud=new u.AcDbPolyline,this._firstPoint=$e(t),this._settings=i}get entity(){return this._cloud}update(e){At(this._cloud,Zr(this._firstPoint,e),!0,this._settings)}}class Jy extends G{constructor(e,t,i){super(e),this._closed=!1,this._cloud=new u.AcDbPolyline,this._points=[$e(t)],this._settings=i}get entity(){return this._cloud}get points(){return this._points}get closed(){return this._closed}addPoint(e){const t=$e(e),i=this._points[this._points.length-1];i&&Pt(i,t)<1e-8||this._points.push(t)}update(e){const t=this._settings.arcLength??1,i=this._points[this._points.length-1];i&&Pt(i,e)>=t&&this._points.push($e(e)),this._closed=this._points.length>=3&&Xr(this._points[0],e,t);const n=this._closed?this._points:[...this._points,$e(e)];At(this._cloud,n,this._closed,this._settings)}}class Qy extends G{constructor(e,t,i,n){super(e),this._reverse=!1,this._cloud=new u.AcDbPolyline,this._path=t,this._closed=i,this._settings=n,this._valid=At(this._cloud,t,i,n)}get entity(){return this._cloud}get valid(){return this._valid}get reverse(){return this._reverse}update(e){}toggleReverse(){this._reverse=!this._reverse,this._valid=At(this._cloud,this._path,this._closed,this._settings,this._reverse),this.render()}}const Is=class Is extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=Is._settings;for(t.arcLength==null&&(t.arcLength=$c(e.view));;){const i=new I(d.t("jig.revcloud.firstCornerOrOptions"));Li(i,"arcLength"),Li(i,"object");const n=i.keywords.add(d.t("jig.revcloud.keywords.rectangular.display"),d.t("jig.revcloud.keywords.rectangular.global"),d.t("jig.revcloud.keywords.rectangular.local")),r=i.keywords.add(d.t("jig.revcloud.keywords.polygonal.display"),d.t("jig.revcloud.keywords.polygonal.global"),d.t("jig.revcloud.keywords.polygonal.local")),o=i.keywords.add(d.t("jig.revcloud.keywords.freehand.display"),d.t("jig.revcloud.keywords.freehand.global"),d.t("jig.revcloud.keywords.freehand.local"));Li(i,"style"),i.keywords.default=t.mode==="polygonal"?r:t.mode==="freehand"?o:n;const a=await k.instance.editor.getPoint(i);if(a.status===b.Keyword){const l=a.stringResult??"";if(l==="ArcLength"){if(!await this.promptArcLength(t))return;continue}if(l==="Object"){await this.convertObject(e,t);return}if(l==="Rectangular"){t.mode="rectangular",await this.drawRectangular(e,t);return}if(l==="Polygonal"){t.mode="polygonal",await this.drawPolygonal(e,t);return}if(l==="Freehand"){t.mode="freehand",await this.drawFreehand(e,t);return}if(l==="Style"){if(!await this.promptStyle(t))return;continue}continue}if(a.status!==b.OK||!a.value)return;t.mode==="polygonal"?await this.drawPolygonal(e,t,a.value):t.mode==="freehand"?await this.drawFreehand(e,t,a.value):await this.drawRectangular(e,t,a.value);return}}async promptArcLength(e){const t=new be(d.t("jig.revcloud.arcLength"));t.allowNegative=!1,t.allowZero=!1,t.useDefaultValue=e.arcLength!=null,t.defaultValue=e.arcLength??1;const i=await k.instance.editor.getDistance(t);if(i.status!==b.OK&&i.status!==b.None)return!1;const n=i.value??t.defaultValue;return u.AcGeTol.isPositive(n)?(e.arcLength=n,!0):(this.showMessage(d.t("jig.revcloud.invalidArcLength"),"warning"),!0)}async promptStyle(e){const t=new ne(d.t("jig.revcloud.style"));t.allowNone=!0;const i=t.keywords.add(d.t("jig.revcloud.keywords.normal.display"),d.t("jig.revcloud.keywords.normal.global"),d.t("jig.revcloud.keywords.normal.local")),n=t.keywords.add(d.t("jig.revcloud.keywords.calligraphy.display"),d.t("jig.revcloud.keywords.calligraphy.global"),d.t("jig.revcloud.keywords.calligraphy.local"));t.keywords.default=e.style==="calligraphy"?n:i;const r=await k.instance.editor.getKeywords(t);return r.status===b.Cancel?!1:((r.status===b.OK||r.status===b.Keyword)&&(r.stringResult==="Calligraphy"?e.style="calligraphy":r.stringResult==="Normal"&&(e.style="normal")),!0)}async drawRectangular(e,t,i){const n=i??await this.promptPoint("firstCorner");if(!n)return;const r=new I(d.t("jig.revcloud.oppositeCorner"));r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(n.x,n.y,0),r.useDashedLine=!1,r.jig=new qy(e.view,n,t);const o=await k.instance.editor.getPoint(r);if(o.status!==b.OK||!o.value)return;const a=Zr(n,o.value);u.AcGeTol.equalToZero(a[0].x-a[1].x)||u.AcGeTol.equalToZero(a[0].y-a[3].y)||await this.commitCloud(e,a,!0,t)}async drawPolygonal(e,t,i){const n=i??await this.promptPoint("startPoint");if(!n)return;const r=[$e(n)];class o{buildPrompt(){const c=new I(d.t(r.length>=2?"jig.revcloud.nextPointOrUndo":"jig.revcloud.nextPoint"));r.length>=2&&Li(c,"undo"),c.useDashedLine=!1,c.useBasePoint=!0;const h=r[r.length-1];return c.basePoint=new u.AcGePoint3d(h.x,h.y,0),c.allowNone=r.length>=3,c.jig=new ed(e.view,r,!0,t),c}async handleResult(c){return c.status===b.Keyword?(c.stringResult==="Undo"&&r.length>1&&r.pop(),"continue"):c.status===b.OK&&c.value?(r.push($e(c.value)),"continue"):"finish"}}const a=new We;a.setState(new o),await a.run(l=>k.instance.editor.getPoint(l)),!(r.length<3)&&await this.commitCloud(e,r,!0,t)}async drawFreehand(e,t,i){const n=i??await this.promptPoint("firstPoint");if(!n)return;const r=new Jy(e.view,n,t),o=t.arcLength??1;for(;;){const a=new I(d.t("jig.revcloud.guideCursor"));a.jig=r,a.useDashedLine=!1,a.useBasePoint=!0,a.basePoint=new u.AcGePoint3d(n.x,n.y,0),a.allowNone=!0,a.disableOSnap=!0;const l=await k.instance.editor.getPoint(a);if(l.status===b.Cancel)return;if(l.status===b.None){if(r.points.length<2)return;await this.commitCloud(e,r.points,r.closed,t);return}if(l.status!==b.OK||!l.value)return;if(r.points.length>=3&&Xr(r.points[0],l.value,o)){await this.commitCloud(e,r.points,!0,t);return}r.addPoint(l.value)}}async convertObject(e,t){for(;;){const i=new He(d.t("jig.revcloud.selectObject"));i.setRejectMessage(d.t("jig.revcloud.invalidObject")),i.addAllowedClass("Polyline"),i.addAllowedClass("Circle"),i.addAllowedClass("Ellipse"),i.addAllowedClass("Spline");const n=await k.instance.editor.getEntity(i);if(n.status!==b.OK||!n.objectId)return;const r=e.doc.database.openEntityForRead(n.objectId);if(!r)return;const o=Qc(r,(t.arcLength??1)*.5);if(!o){this.showMessage(d.t("jig.revcloud.invalidObject"),"warning");continue}await this.commitCloud(e,o.points,o.closed,t)&&this.eraseEntity(e,r);return}}async commitCloud(e,t,i,n){const r=new Qy(e.view,t,i,n);if(!r.valid)return!1;try{for(;r.render(),!!await this.promptReverse(r);)r.toggleReverse();const o=new u.AcDbPolyline;return At(o,t,i,n,r.reverse)?(e.doc.database.tables.blockTable.modelSpace.appendEntity(o),!0):!1}finally{r.end()}}async promptReverse(e){const t=new ne(d.t("jig.revcloud.reverseDirection"));t.jig=e,t.allowNone=!0,Li(t,"yes");const i=t.keywords.add(d.t("jig.revcloud.keywords.no.display"),d.t("jig.revcloud.keywords.no.global"),d.t("jig.revcloud.keywords.no.local"));t.keywords.default=i;const n=await k.instance.editor.getKeywords(t);return(n.status===b.OK||n.status===b.Keyword)&&n.stringResult==="Yes"}async promptPoint(e){const t=new I(d.t(`jig.revcloud.${e}`)),i=await k.instance.editor.getPoint(t);if(!(i.status!==b.OK||!i.value))return i.value}eraseEntity(e,t){t.erase(),e.view.removeEntity(t)}};Is._settings={...Xy};let ts=Is;const eg={type:"line",increment:.1,tolerance:.5};function qr(s,e){s.keywords.add(d.t(`jig.sketch.keywords.${e}.display`),d.t(`jig.sketch.keywords.${e}.global`),d.t(`jig.sketch.keywords.${e}.local`))}function is(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function gt(s){return new u.AcGePoint2d(s.x,s.y)}function ns(s){return new u.AcGePoint3d(s.x,s.y,0)}function td(s,e,t){const i=gt(e);if(s.length===0)return s.push(i),!0;const n=s[s.length-1];return is(n,i)<t?!1:(s.push(i),!0)}function id(s,e){if(s.length<=2)return s.map(gt);const t=Math.max(e,1e-8),i=[gt(s[0])];for(let o=1;o<s.length-1;o++){const a=i[i.length-1];is(a,s[o])>=t&&i.push(gt(s[o]))}const n=gt(s[s.length-1]),r=i[i.length-1];return is(r,n)>1e-8&&i.push(n),i}class nd extends G{constructor(e,t,i){super(e),this._polyline=new u.AcDbPolyline,this._points=[gt(t)],this._increment=Math.max(i,1e-8),this._polyline.addVertexAt(0,this._points[0])}get entity(){return this._polyline}get points(){return this._points}update(e){td(this._points,e,this._increment)&&this._polyline.addVertexAt(this._points.length-1,this._points[this._points.length-1])}}class tg{constructor(e){this.view=e,this._entities=[]}addStroke(e){if(e.length<2)return;const t=new u.AcDbPolyline;e.forEach((i,n)=>t.addVertexAt(n,gt(i))),this._entities.push(t),this.view.addTransientEntity(t)}render(){this._entities.forEach(e=>this.view.addTransientEntity(e))}dispose(){this._entities.forEach(e=>this.view.removeTransientEntity(e.objectId)),this._entities.length=0}}class ss extends G{constructor(e,t){super(e),this.preview=t}update(e){}render(){this.preview.render()}}const Ms=class Ms extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=Ms._settings,i=[],n=new tg(e.view);try{for(;;){n.render();const r=new I(d.t("jig.sketch.specifySketch"));qr(r,"type"),qr(r,"increment"),qr(r,"tolerance"),r.allowNone=!0,r.disableOSnap=!0,r.jig=new ss(e.view,n);const o=await k.instance.editor.getPoint(r);if(o.status===b.Keyword){const l=o.stringResult??"";if(l==="Type"){if(!await this.promptType(t,n))return;continue}if(l==="Increment"){if(!await this.promptIncrement(t,n))return;continue}if(l==="Tolerance"){if(!await this.promptTolerance(t,n))return;continue}continue}if(o.status===b.None){this.commitStrokes(e,i);return}if(o.status!==b.OK||!o.value)return;const a=await this.captureStroke(e,t,o.value,n);if(a===!1)return;a.length>=2&&(i.push({points:a,type:t.type,tolerance:t.tolerance}),n.addStroke(a))}}finally{n.dispose()}}async promptType(e,t){t==null||t.render();const i=new ne(d.t("jig.sketch.type"));i.allowNone=!0,t&&(i.jig=new ss(t.view,t));const n=i.keywords.add(d.t("jig.sketch.keywords.line.display"),d.t("jig.sketch.keywords.line.global"),d.t("jig.sketch.keywords.line.local")),r=i.keywords.add(d.t("jig.sketch.keywords.polyline.display"),d.t("jig.sketch.keywords.polyline.global"),d.t("jig.sketch.keywords.polyline.local")),o=i.keywords.add(d.t("jig.sketch.keywords.spline.display"),d.t("jig.sketch.keywords.spline.global"),d.t("jig.sketch.keywords.spline.local"));i.keywords.default=e.type==="polyline"?r:e.type==="spline"?o:n;const a=await k.instance.editor.getKeywords(i);return a.status===b.Cancel?!1:((a.status===b.OK||a.status===b.Keyword)&&(a.stringResult==="Polyline"?e.type="polyline":a.stringResult==="Spline"?e.type="spline":(a.stringResult==="Line"||a.stringResult==="Lines")&&(e.type="line")),!0)}async promptIncrement(e,t){t==null||t.render();const i=new be(d.t("jig.sketch.increment"));i.allowNegative=!1,i.allowZero=!1,i.useDefaultValue=!0,i.defaultValue=e.increment,t&&(i.jig=new ss(t.view,t));const n=await k.instance.editor.getDistance(i);if(n.status===b.Cancel)return!1;const r=n.value??e.increment;return u.AcGeTol.isPositive(r)&&(e.increment=r),!0}async promptTolerance(e,t){t==null||t.render();const i=new be(d.t("jig.sketch.tolerance"));i.allowNegative=!1,i.allowZero=!0,i.useDefaultValue=!0,i.defaultValue=e.tolerance,t&&(i.jig=new ss(t.view,t));const n=await k.instance.editor.getDistance(i);if(n.status===b.Cancel)return!1;const r=n.value??e.tolerance;return r>=0&&Number.isFinite(r)&&(e.tolerance=r),!0}async captureStroke(e,t,i,n){n.render();const r=new nd(e.view,i,t.increment),o=new I(d.t("jig.sketch.sketching"));o.jig=r,o.useDashedLine=!1,o.useBasePoint=!0,o.basePoint=ns(i),o.allowNone=!0,o.disableOSnap=!0;const a=await k.instance.editor.getPoint(o);if(a.status===b.Cancel)return!1;const l=[...r.points];if(a.status===b.OK&&a.value){const c=l[l.length-1];(!c||is(c,a.value)>1e-8)&&l.push(gt(a.value))}return l}commitStrokes(e,t){for(const i of t)this.appendStroke(e,i)}appendStroke(e,t){const i=e.doc.database.tables.blockTable.modelSpace,n=t.points;if(t.type==="line"){for(let o=1;o<n.length;o++){const a=new u.AcDbLine(ns(n[o-1]),ns(n[o]));i.appendEntity(a),e.view.addEntity(a)}return}if(t.type==="spline"){const o=id(n,t.tolerance);if(o.length<2)return;const a=o.map(ns),l=Math.min(3,Math.max(1,a.length-1)),c=new u.AcDbSpline(a,"Chord",l,!1);i.appendEntity(c),e.view.addEntity(c);return}const r=new u.AcDbPolyline;n.forEach((o,a)=>r.addVertexAt(a,o)),i.appendEntity(r),e.view.addEntity(r)}};Ms._settings={...eg};let rs=Ms;class sd extends G{constructor(e,t,i,n){super(e),this._points=t,this._settings=i,this._closed=n,this._spline=this.createSpline(t)}get entity(){return this._spline}update(e){const t=new u.AcGePoint2d(e),i=this._points[this._points.length-1],r=!i||!sg(i,t)?[...this._points,t]:[...this._points];try{this.rebuildSpline(r)}catch{this.rebuildSpline(this._points)}}createSpline(e){return Jr(e,this._settings,this._closed)}rebuildSpline(e){if(e.length<2){const o=[new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(1,1,0)],a=1,l=Ti(o.length,a);this._spline.rebuild(o,l,void 0,a);return}const t=e.map(o=>new u.AcGePoint3d(o.x,o.y,0)),i=od(t.length,this._settings),n=this._closed&&t.length>=3;if(this._settings.method==="fit"){this._spline.rebuild(t,ad(this._settings.knotsType),i,n);return}const r=Ti(t.length,i);this._spline.rebuild(t,r,void 0,i,!1),n&&(this._spline.closed=!0)}}class rd extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=[],i={method:"fit",knotsType:"chord",degree:3};let n=!1;const r=S=>{t.push(new u.AcGePoint2d(S))},o=()=>{t.length<=1||t.pop()},a=()=>t[t.length-1],l=()=>t.length>=3,c=()=>new sd(e.view,t,i,n),h=()=>new ig(e.view,t,i,n),p=async()=>{const S=new ne(d.t("jig.spline.methodPrompt"));S.keywords.add(d.t("jig.spline.keywords.fit.display"),d.t("jig.spline.keywords.fit.global"),d.t("jig.spline.keywords.fit.local")),S.keywords.add(d.t("jig.spline.keywords.cv.display"),d.t("jig.spline.keywords.cv.global"),d.t("jig.spline.keywords.cv.local"));const P=await k.instance.editor.getKeywords(S);return P.status!==b.OK?!1:(P.stringResult==="Fit"?i.method="fit":P.stringResult==="CV"&&(i.method="cv"),!0)},m=async()=>{const S=new ne(d.t("jig.spline.knotsPrompt"));S.jig=h(),S.keywords.add(d.t("jig.spline.keywords.chord.display"),d.t("jig.spline.keywords.chord.global"),d.t("jig.spline.keywords.chord.local")),S.keywords.add(d.t("jig.spline.keywords.sqrtChord.display"),d.t("jig.spline.keywords.sqrtChord.global"),d.t("jig.spline.keywords.sqrtChord.local")),S.keywords.add(d.t("jig.spline.keywords.uniform.display"),d.t("jig.spline.keywords.uniform.global"),d.t("jig.spline.keywords.uniform.local"));const P=await k.instance.editor.getKeywords(S);return P.status!==b.OK?!1:(P.stringResult==="Chord"?i.knotsType="chord":P.stringResult==="SqrtChord"?i.knotsType="sqrtChord":P.stringResult==="Uniform"&&(i.knotsType="uniform"),!0)},g=async()=>{const S=new kr(d.t("jig.spline.degreePrompt"),1,10);S.jig=h();const P=await k.instance.editor.getInteger(S);if(P.status!==b.OK)return!1;const A=Math.floor(P.value??i.degree);return i.degree=Math.max(1,A),!0},f=S=>{S.useDashedLine=!0,S.useBasePoint=!0;const P=a();P&&(S.basePoint=new u.AcGePoint3d(P)),S.jig=c(),S.allowNone=!0};class w{constructor(P){this.machine=P}buildPrompt(){const P=new I(d.t("jig.spline.nextPointWithFitOptions"));return P.keywords.add(d.t("jig.spline.keywords.method.display"),d.t("jig.spline.keywords.method.global"),d.t("jig.spline.keywords.method.local")),P.keywords.add(d.t("jig.spline.keywords.knots.display"),d.t("jig.spline.keywords.knots.global"),d.t("jig.spline.keywords.knots.local")),P.keywords.add(d.t("jig.spline.keywords.undo.display"),d.t("jig.spline.keywords.undo.global"),d.t("jig.spline.keywords.undo.local")),P.keywords.add(d.t("jig.spline.keywords.close.display"),d.t("jig.spline.keywords.close.global"),d.t("jig.spline.keywords.close.local")),f(P),P}async handleResult(P){if(P.status===b.OK)return r(P.value),"continue";if(P.status!==b.Keyword)return"finish";const A=P.stringResult??"";return A==="Method"?await p()?(i.method==="cv"&&this.machine.setState(new v(this.machine)),"continue"):"finish":A==="Knots"?await m()?"continue":"finish":A==="Undo"?(o(),"continue"):A==="Close"&&l()?(n=!0,"finish"):"continue"}}class v{constructor(P){this.machine=P}buildPrompt(){const P=new I(d.t("jig.spline.nextPointWithCvOptions"));return P.keywords.add(d.t("jig.spline.keywords.method.display"),d.t("jig.spline.keywords.method.global"),d.t("jig.spline.keywords.method.local")),P.keywords.add(d.t("jig.spline.keywords.degree.display"),d.t("jig.spline.keywords.degree.global"),d.t("jig.spline.keywords.degree.local")),P.keywords.add(d.t("jig.spline.keywords.undo.display"),d.t("jig.spline.keywords.undo.global"),d.t("jig.spline.keywords.undo.local")),P.keywords.add(d.t("jig.spline.keywords.close.display"),d.t("jig.spline.keywords.close.global"),d.t("jig.spline.keywords.close.local")),f(P),P}async handleResult(P){if(P.status===b.OK)return r(P.value),"continue";if(P.status!==b.Keyword)return"finish";const A=P.stringResult??"";return A==="Method"?await p()?(i.method==="fit"&&this.machine.setState(new w(this.machine)),"continue"):"finish":A==="Degree"?await g()?"continue":"finish":A==="Undo"?(o(),"continue"):A==="Close"&&l()?(n=!0,"finish"):"continue"}}for(;t.length===0;){const S=new I(d.t("jig.spline.firstPointWithOptions"));S.keywords.add(d.t("jig.spline.keywords.method.display"),d.t("jig.spline.keywords.method.global"),d.t("jig.spline.keywords.method.local"));const P=await k.instance.editor.getPoint(S);if(P.status===b.OK){r(P.value);break}if(P.status===b.Keyword&&P.stringResult==="Method"){if(!await p())return;continue}return}const x=new We;if(x.setState(i.method==="fit"?new w(x):new v(x)),await x.run(S=>k.instance.editor.getPoint(S)),t.length>=2){const S=e.doc.database,P=Jr(t,i,n);S.tables.blockTable.modelSpace.appendEntity(P)}}}class ig extends G{constructor(e,t,i,n){super(e),this._spline=Jr(t,i,n)}get entity(){return this._spline}update(e){}}function Jr(s,e,t){if(s.length<2){const c=[new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(1,1,0)],h=1,p=Ti(c.length,h);return new u.AcDbSpline(c,p,void 0,h)}const i=s.map(c=>new u.AcGePoint3d(c.x,c.y,0)),n=e.method==="fit"?ng(i):i;if(n.length<2){const c=[new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(1,1,0)],h=1,p=Ti(c.length,h);return new u.AcDbSpline(c,p,void 0,h)}const r=od(n.length,e),o=t&&n.length>=3;if(e.method==="fit")return new u.AcDbSpline(n,ad(e.knotsType),r,o);const a=Ti(n.length,r),l=new u.AcDbSpline(n,a,void 0,r,!1);return o&&(l.closed=!0),l}function od(s,e){const t=Math.max(1,s-1);return e.method==="fit"?Math.min(3,t):Math.min(Math.max(1,e.degree),t)}function ng(s){if(s.length<=1)return s;const e=[new u.AcGePoint3d(s[0])];for(let t=1;t<s.length;t++){const i=e[e.length-1],n=s[t];rg(i,n)||e.push(new u.AcGePoint3d(n))}return e}function sg(s,e){return u.DEFAULT_TOL.equalPoint2d(s,e)}function rg(s,e){return u.DEFAULT_TOL.equalPoint3d(s,e)}function ad(s){switch(s){case"chord":return"Chord";case"sqrtChord":return"SqrtChord";case"uniform":default:return"Uniform"}}function Ti(s,e){const t=[],i=s+e+1;for(let n=0;n<i;n++)n<e+1?t.push(0):n>=i-e-1?t.push(1):t.push((n-e)/(s-e));return t}async function Qr(s,e){const t=u.acdbHostApplicationServices(),i=t._workingDatabase;t.workingDatabase=s;try{return await e()}finally{t._workingDatabase=i}}const og=".dwg,.dxf",ld=100;function ag(s){var a,l,c,h,p,m,g;const e=(l=(a=window.mlightcadGetLocalFilePath)==null?void 0:a.call(window,s))==null?void 0:l.trim();if(e)return e;const t=(c=window.electron)==null?void 0:c.webUtils,i=(p=(h=t==null?void 0:t.getPathForFile)==null?void 0:h.call(t,s))==null?void 0:p.trim();if(i)return i;const n=s,r=(m=n.path)==null?void 0:m.trim();if(r)return r;const o=(g=n.mozFullPath)==null?void 0:g.trim();return o||s.name}function lg(s){return s.replace(/\.(dwg|dxf)$/i,"")||s}function cg(s,e){const t=lg(e);if(!s.tables.blockTable.has(t))return t;let i=1;for(;s.tables.blockTable.has(`${t}_${i}`);)i++;return`${t}_${i}`}function dg(){return new Promise(s=>{const e=document.createElement("input");e.type="file",e.accept=og,e.style.display="none",document.body.appendChild(e);let t=!1;const i=o=>{t||(t=!0,e.removeEventListener("change",n),e.removeEventListener("cancel",r),e.remove(),s(o))},n=()=>{var o;return i((o=e.files)==null?void 0:o[0])},r=()=>i(void 0);e.addEventListener("change",n),e.addEventListener("cancel",r),e.click()})}function ug(s){var i,n;const e=((n=(i=s.extents)==null?void 0:i.clone)==null?void 0:n.call(i))??new u.AcGeBox3d;if(!e.isEmpty())return e;const t=new u.AcGeBox3d;for(const r of s.tables.blockTable.modelSpace.newIterator())if(!(r instanceof u.AcDbViewport))try{const o=r.geometricExtents;o&&!o.isEmpty()&&(t.expandByPoint(o.min),t.expandByPoint(o.max))}catch{}return t.isEmpty()?new u.AcGeBox3d(new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(ld,ld,0)):t}class hg extends G{constructor(e,t){super(e),this._mode="point",this._position=new u.AcGePoint3d,this._scale=1,this._rotationRad=0;const i=t.min,n=t.max;this._localCorners=[new u.AcGePoint2d(i.x,i.y),new u.AcGePoint2d(n.x,i.y),new u.AcGePoint2d(n.x,n.y),new u.AcGePoint2d(i.x,n.y)],this._entity=u.AcDbPolyline.from2dPoints(this._localCorners.map(r=>r.clone()),!0),this.applyGeometry()}get entity(){return this._entity}setMode(e){this._mode=e}setPosition(e){this._position=new u.AcGePoint3d(e),this.applyGeometry()}setScale(e){this._scale=e,this.applyGeometry()}setRotationRad(e){this._rotationRad=e,this.applyGeometry()}update(e){if(this._mode==="point"&&typeof e!="number"){this.setPosition(e);return}if(typeof e=="number"){if(this._mode==="scale"){this.setScale(e>0?e:this._scale);return}this._mode==="rotation"&&this.setRotationRad(e*Math.PI/180)}}applyGeometry(){const e=Math.cos(this._rotationRad),t=Math.sin(this._rotationRad),i=this._scale,n=this._localCorners.map(r=>{const o=r.x*i,a=r.y*i;return new u.AcGePoint2d(this._position.x+o*e-a*t,this._position.y+o*t+a*e)});this._entity.reset(!1),n.forEach((r,o)=>{this._entity.addVertexAt(o,r)}),this._entity.closed=!0}}class cd extends z{constructor(){super(),this.mode=F.Write}async execute(e){var a;const t=await dg();if(!t)return;const i=(a=t.name.split(".").pop())==null?void 0:a.toLocaleLowerCase();if(i!=="dwg"&&i!=="dxf"){this.showMessage(d.t("jig.xattach.unsupportedFile"),"warning");return}let n;try{const l=await t.arrayBuffer();n=await k.instance.withBusyIndicator(async()=>{const c=new u.AcDbDatabase;return await Qr(c,async()=>{await c.read(l,{readOnly:!0},i==="dwg"?u.AcDbFileType.DWG:u.AcDbFileType.DXF)}),c},d.t("jig.xattach.loading"))}catch{this.showMessage(d.t("jig.xattach.loadFailed"),"error");return}const r=ug(n),o=new hg(e.view,r);try{o.setMode("point");const l=new I(d.t("jig.xattach.insertionPoint"));l.allowNone=!0,l.useDefaultValue=!0,l.defaultValue=new u.AcGePoint3d(0,0,0),l.jig=o;const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK&&c.status!==b.None)return;const h=c.status===b.OK&&c.value?new u.AcGePoint3d(c.value):new u.AcGePoint3d(0,0,0);o.setPosition(h),o.setMode("scale");const p=new ie(d.t("jig.xattach.scale"));p.allowNone=!0,p.allowNegative=!1,p.allowZero=!1,p.useDefaultValue=!0,p.defaultValue=1,p.jig=o;const m=await k.instance.editor.getDouble(p);if(m.status===b.Cancel||m.status===b.Error)return;const g=m.status===b.OK&&m.value!==void 0?m.value:1;if(!(g>0)){this.showMessage(d.t("jig.xattach.invalidScale"),"warning");return}o.setScale(g),o.setMode("rotation");const f=new xe(d.t("jig.xattach.rotation"));f.allowNone=!0,f.allowNegative=!0,f.allowZero=!0,f.useDefaultValue=!0,f.defaultValue=0,f.useBasePoint=!0,f.useDashedLine=!0,f.basePoint=h,f.jig=o;const w=await k.instance.editor.getAngle(f);if(w.status===b.Cancel||w.status===b.Error)return;const x=(w.status===b.OK&&w.value!==void 0?w.value:0)*Math.PI/180,S=e.doc.database,P=cg(S,t.name),A=ag(t),_={position:h,scale:g,rotationRad:x},C=await It.instance.attachOverlay({blockName:P,fileName:t.name,sourceDb:n,sourcePath:A,transform:_});try{ct(S,"XATTACH",()=>{const{insert:O}=It.createHostXrefInsert(S,P,A,_,n.tables.blockTable.modelSpace.origin);C.insertId=O.objectId})}catch(O){throw It.instance.unload(C.id),O}Q.emit("missed-data-changed",{})}finally{o.end()}}}const Qt=1e6;class dd extends z{constructor(){super(),this.mode=F.Write}async execute(e){let t="point";for(;;){const i=new I(d.t("jig.xline.firstPointOrOptions"));i.keywords.add(d.t("jig.xline.keywords.hor.display"),d.t("jig.xline.keywords.hor.global"),d.t("jig.xline.keywords.hor.local")),i.keywords.add(d.t("jig.xline.keywords.ver.display"),d.t("jig.xline.keywords.ver.global"),d.t("jig.xline.keywords.ver.local")),i.keywords.add(d.t("jig.xline.keywords.ang.display"),d.t("jig.xline.keywords.ang.global"),d.t("jig.xline.keywords.ang.local"));const n=await k.instance.editor.getPoint(i);if(n.status===b.Keyword)n.stringResult==="Hor"?t="hor":n.stringResult==="Ver"?t="ver":n.stringResult==="Ang"&&(t="ang");else if(n.status===b.OK&&n.value){t="point";const h=new I(d.t("jig.xline.secondPoint"));h.useBasePoint=!0,h.useDashedLine=!0,h.basePoint=new u.AcGePoint3d(n.value);const p=await k.instance.editor.getPoint(h);if(p.status!==b.OK||!p.value)return;const m={x:p.value.x-n.value.x,y:p.value.y-n.value.y,z:p.value.z-n.value.z};this.appendFiniteXLine(e,n.value,m)||this.showMessage(d.t("jig.xline.invalidDirection"),"warning");continue}else return;if(t==="hor"){const h=new I(d.t("jig.xline.throughPoint")),p=await k.instance.editor.getPoint(h);if(p.status!==b.OK||!p.value)return;this.appendFiniteXLine(e,p.value,{x:1,y:0,z:0});continue}if(t==="ver"){const h=new I(d.t("jig.xline.throughPoint")),p=await k.instance.editor.getPoint(h);if(p.status!==b.OK||!p.value)return;this.appendFiniteXLine(e,p.value,{x:0,y:1,z:0});continue}const r=new ie(d.t("jig.xline.angle")),o=await k.instance.editor.getDouble(r);if(o.status!==b.OK||o.value==null)return;const a=new I(d.t("jig.xline.throughPoint")),l=await k.instance.editor.getPoint(a);if(l.status!==b.OK||!l.value)return;const c=o.value*Math.PI/180;this.appendFiniteXLine(e,l.value,{x:Math.cos(c),y:Math.sin(c),z:0})}}appendFiniteXLine(e,t,i){const n=this.normalizeDirection(i);if(!n)return!1;const r=new u.AcGePoint3d(t.x-n.x*Qt,t.y-n.y*Qt,t.z-n.z*Qt),o=new u.AcGePoint3d(t.x+n.x*Qt,t.y+n.y*Qt,t.z+n.z*Qt);return e.doc.database.tables.blockTable.modelSpace.appendEntity(new u.AcDbLine(r,o)),!0}normalizeDirection(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);if(u.AcGeTol.isPositive(t))return{x:e.x/t,y:e.y/t,z:e.z/t}}}function ud(s){const e=s.htmlTransientManager,t=s.activeLayoutBtrId;Bt(s,"Clear Measurements",()=>{e.deselectAll();for(const i of e.groupsOnLayer(Y))(i.layoutId==null||i.layoutId===t)&&e.detach(i.id)}),e.clear(ue),s.isHtmlDirty=!0}class hd extends z{constructor(){super(),this.mode=F.Read}async execute(e){ud(e.view)}}class pd extends z{constructor(){super(),this.mode=F.Read,this.recordsUndoStack=!1}async execute(e){const t=e.view;fa(t,!Js())}}function os(s,e){const t=e.canvas.getBoundingClientRect(),i=window.devicePixelRatio||1,n=Math.round(t.width),r=Math.round(t.height),o=e.canvasToContainer({x:0,y:0});s.style.left=`${o.x}px`,s.style.top=`${o.y}px`,s.style.width=`${n}px`,s.style.height=`${r}px`,(s.width!==n*i||s.height!==r*i)&&(s.width=n*i,s.height=r*i);const a=s.getContext("2d");return a?(a.clearRect(0,0,s.width,s.height),a.save(),a.scale(i,i),{ctx:a,dpr:i}):null}const as=s=>(s%(2*Math.PI)+2*Math.PI)%(2*Math.PI);function md(s,e,t,i,n,r=2){const o=os(s,e);if(!o)return;const{ctx:a}=o,l=e.worldToScreen(t),c=e.worldToScreen(i);a.beginPath(),a.moveTo(l.x,l.y),a.lineTo(c.x,c.y),a.strokeStyle=ge(n),a.lineWidth=r,a.stroke(),a.restore()}function yd(s,e,t,i,n,r,o=2){const a=os(s,e);if(!a)return;const{ctx:l}=a,c=e.worldToScreen(t),h=e.worldToScreen(i),p=e.worldToScreen(n);l.strokeStyle=ge(r),l.lineWidth=o,l.beginPath(),l.moveTo(c.x,c.y),l.lineTo(h.x,h.y),l.moveTo(c.x,c.y),l.lineTo(p.x,p.y),l.stroke();const m=Math.hypot(h.x-c.x,h.y-c.y),g=Math.hypot(p.x-c.x,p.y-c.y),f=Math.max(Math.min(m,g)*.3,15),w=Math.atan2(h.y-c.y,h.x-c.x),v=Math.atan2(p.y-c.y,p.x-c.x),x=as(v-w)>Math.PI;l.beginPath(),l.arc(c.x,c.y,f,w,v,x),l.stroke(),l.restore()}function gd(s,e,t,i,n=2.5){const r=os(s,e);if(!r||t.length<3){r==null||r.ctx.restore();return}const{ctx:o}=r,a=t.map(l=>e.worldToScreen(l));o.beginPath(),o.moveTo(a[0].x,a[0].y);for(let l=1;l<a.length;l++)o.lineTo(a[l].x,a[l].y);o.closePath(),o.fillStyle=Ws(i,.2),o.fill(),o.strokeStyle=ge(i),o.lineWidth=n,o.stroke(),o.restore()}function fd(s,e,t,i,n,r,o=4){const a=os(s,e);if(!a)return;const{ctx:l}=a,c=e.worldToScreen({x:t.cx,y:t.cy}),h=e.worldToScreen(i),p=e.worldToScreen(n),m=Math.hypot(h.x-c.x,h.y-c.y),g=Math.atan2(h.y-c.y,h.x-c.x),f=Math.atan2(p.y-c.y,p.x-c.x),v=as(f-g)>Math.PI;l.beginPath(),l.arc(c.x,c.y,m,g,f,v),l.strokeStyle=ge(r),l.lineWidth=o,l.stroke(),l.restore()}function bd(s,e,t){const i=Math.atan2(s.y-t.cy,s.x-t.cx),n=Math.atan2(e.y-t.cy,e.x-t.cx),r=as(n-i);return Math.min(r,2*Math.PI-r)*t.r}function eo(s,e,t){const i=Math.atan2(s.y-t.cy,s.x-t.cx),n=Math.atan2(e.y-t.cy,e.x-t.cx),r=as(n-i),o=r<=Math.PI?i+r/2:i-(2*Math.PI-r)/2;return{x:t.cx+t.r*Math.cos(o),y:t.cy+t.r*Math.sin(o),z:0}}function wd(s){let e=0;const t=s.length;for(let i=0;i<t;i++){const n=(i+1)%t;e+=s[i].x*s[n].y,e-=s[n].x*s[i].y}return Math.abs(e)/2}function to(s){const e=s.reduce((i,n)=>i+n.x,0)/s.length,t=s.reduce((i,n)=>i+n.y,0)/s.length;return{x:e,y:t}}function vd(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=t.x-s.x,o=t.y-s.y,a=i*r+n*o,l=i*o-n*r;return Math.atan2(Math.abs(l),a)*180/Math.PI}function Ct(s,e){const t=e.getBoundingClientRect(),i=window.devicePixelRatio||1,n=`${t.width}px`,r=`${t.height}px`,o=Math.max(1,Math.floor(t.width*i)),a=Math.max(1,Math.floor(t.height*i));s.style.left="0",s.style.top="0",s.style.width!==n&&(s.style.width=n),s.style.height!==r&&(s.style.height=r),s.width!==o&&(s.width=o),s.height!==a&&(s.height=a);const l=s.getContext("2d");return l?(l.setTransform(i,0,0,i,0,0),l.clearRect(0,0,t.width,t.height),l):null}function ls(s,e,t,i){const n=t.x-e.x,r=t.y-e.y,o=Math.hypot(n,r)||1,a=n/o,l=r/o,c=12,h={x:t.x-a*c-l*c*.45,y:t.y-l*c+a*c*.45},p={x:t.x-a*c+l*c*.45,y:t.y-l*c-a*c*.45};s.fillStyle=i,s.beginPath(),s.moveTo(t.x,t.y),s.lineTo(h.x,h.y),s.lineTo(p.x,p.y),s.closePath(),s.fill()}function io(s,e,t,i,n=!0,r=2){s.strokeStyle=i,s.lineWidth=r,s.beginPath(),s.moveTo(e.x,e.y),s.lineTo(t.x,t.y),s.stroke(),n&&ls(s,t,e,i)}function no(s,e,t,i,n=1.5){const r=Math.min(e.x,t.x),o=Math.min(e.y,t.y),a=Math.abs(e.x-t.x),l=Math.abs(e.y-t.y);s.fillStyle=i,s.globalAlpha=.28,s.fillRect(r,o,a,l),s.globalAlpha=1,s.strokeStyle=i,s.lineWidth=n,s.strokeRect(r,o,a,l)}class so{worldDraw(e){return this.subWorldDraw(e)}subGetGripPoints(){return[]}subMoveGripPointsAt(e,t){return this}hitTest(e,t,i){return!1}primaryPoint(){}}function ro(s,e){const t=s.viewportToCanvas({x:e.clientX,y:e.clientY}),i=s.screenToWorld(t);return{x:i.x,y:i.y}}function Ye(s,e,t){s.htmlTransientManager.updatePosition(e.id,t)}const kd=4,ei={capture:!0,passive:!1};function _t(s){const{view:e,el:t,onDragStart:i,onMove:n,onCommit:r}=s,o=s.cursor??"grab";t.style.pointerEvents="auto",t.style.cursor=o,t.style.touchAction="none",t.style.userSelect="none";let a;const l=c=>{if(c.button!==0)return;const h=c.target;if(c.detail>=2||h!=null&&h.isContentEditable||h!=null&&h.closest('[contenteditable="true"]')||t.querySelector('[contenteditable="true"]'))return;const p=c.pointerId,m=c.clientX,g=c.clientY;let f=!1;const w=()=>{window.removeEventListener("pointermove",v,ei),window.removeEventListener("pointerup",x,ei),window.removeEventListener("pointercancel",x,ei),a===w&&(a=void 0)},v=S=>{if(S.pointerId===p){if(!f){const P=S.clientX-m,A=S.clientY-g;if(P*P+A*A<kd*kd)return;f=!0,S.preventDefault(),t.style.cursor="grabbing",i==null||i()}n(ro(e,S),S),e.isHtmlDirty=!0}},x=S=>{S.pointerId===p&&(w(),f&&(t.style.cursor=o,r()))};a==null||a(),a=w,window.addEventListener("pointermove",v,ei),window.addEventListener("pointerup",x,ei),window.addEventListener("pointercancel",x,ei)};return t.addEventListener("pointerdown",l),()=>{t.removeEventListener("pointerdown",l),a==null||a()}}function cs(s){const{view:e,tipEl:t,bubbleEl:i,state:n,constrainTip:r,onDragStart:o,onLiveChange:a,onCommit:l}=s;t.element.style.width="14px",t.element.style.height="14px";let c={tip:{...n.tip},anchor:{...n.anchor}};const h=g=>Math.hypot(g.tip.x-c.tip.x,g.tip.y-c.tip.y)<1e-9&&Math.hypot(g.anchor.x-c.anchor.x,g.anchor.y-c.anchor.y)<1e-9,p=_t({view:e,el:t.element,onDragStart:()=>{c={tip:{...n.tip},anchor:{...n.anchor}},o==null||o()},onMove:g=>{n.tip=r?r(g):g,Ye(e,t,n.tip),a()},onCommit:()=>{const g={tip:{...n.tip},anchor:{...n.anchor}};h(g)||l(g)}}),m=_t({view:e,el:i.element,onDragStart:()=>{c={tip:{...n.tip},anchor:{...n.anchor}},o==null||o()},onMove:g=>{n.anchor=g,Ye(e,i,n.anchor),a()},onCommit:()=>{const g={tip:{...n.tip},anchor:{...n.anchor}};h(g)||l(g)}});return()=>{p(),m()}}class ti extends so{constructor(e,t,i){super(),this.entityId=e,this.layoutIdOption=t,this.style=i}get id(){return this.entityId}hitTest(e,t,i){return Vs(this.toRecord().geometry,e,t,i)}commit(e,t){const i=this.subWorldDrawWithDb(e,t);xa(e,i.group,{...i.extras,dispose:i.dispose})}subWorldDraw(e){throw new Error("Use AcApMeasureEntity.commit(view, db) instead of worldDraw")}createGroup(e){return new M.AcTrHtmlGroup({id:this.entityId,layer:Y,layoutId:this.resolveLayoutId(e),selectable:!0})}resolveLayoutId(e){return this.layoutIdOption??e.activeLayoutBtrId}}class Ii extends ti{constructor(e,t,i,n){super(n.id??`angle-${Date.now()}`,n.layoutId,n.style),this.vertex=e,this.arm1=t,this.arm2=i}static create(e,t,i,n,r){return new Ii(e,t,i,{style:n,id:r==null?void 0:r.id,layoutId:r==null?void 0:r.layoutId})}primaryPoint(){return{x:this.vertex.x,y:this.vertex.y,z:0}}toRecord(e){return{id:this.entityId,type:"angle",layoutId:e,style:dt(this.style),geometry:{type:"angle",vertex:{x:this.vertex.x,y:this.vertex.y},arm1:{x:this.arm1.x,y:this.arm1.y},arm2:{x:this.arm2.x,y:this.arm2.y}}}}subWorldDrawWithDb(e,t){const i=this.style.color,n=vd(this.vertex,this.arm1,this.arm2),r=this.resolveLayoutId(e),o=new M.AcTrHtmlCanvasOverlay({id:`angle-canvas-${this.entityId}`,container:e.container,layer:Y,layoutId:r}),a=(L=this.style)=>yd(o.canvas,e,this.vertex,this.arm1,this.arm2,L.color,Ve(L.lineWeight));a();const l=()=>a(kt(this.entityId)??this.style);e.events.viewChanged.addEventListener(l);const c=this.arm1.x-this.vertex.x,h=this.arm1.y-this.vertex.y,p=this.arm2.x-this.vertex.x,m=this.arm2.y-this.vertex.y,g=Math.hypot(c,h),f=Math.hypot(p,m),w=g>0?c/g:1,v=g>0?h/g:0,x=f>0?p/f:1,S=f>0?m/f:0;let P=w+x,A=v+S;const _=Math.hypot(P,A);_>0?(P/=_,A/=_):(P=-v,A=w);const C=Math.max(Math.min(g,f)*.4,Math.max(g,f)*.15),O={x:this.vertex.x+P*C,y:this.vertex.y+A*C};return{group:this.createGroup(e).add(new M.AcTrHtmlDot({id:`${this.entityId}-dotV`,color:i,worldPosition:this.vertex,layer:Y}),new M.AcTrHtmlDot({id:`${this.entityId}-dot1`,color:i,worldPosition:this.arm1,layer:Y}),new M.AcTrHtmlDot({id:`${this.entityId}-dot2`,color:i,worldPosition:this.arm2,layer:Y}),new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:i,text:ln(t,n*Math.PI/180),worldPosition:O,layer:Y,fontSize:this.style.fontSize})).addCanvas(o),entityIds:[],dispose:()=>{e.events.viewChanged.removeEventListener(l)},extras:{style:this.style,value:{kind:"angle",radians:n*Math.PI/180},snapshot:this.toRecord(r),redraw:a}}}}class Mi extends ti{constructor(e,t,i,n){super(n.id??`arc-${Date.now()}`,n.layoutId,n.style),this.geom=e,this.start=t,this.end=i}static create(e,t,i,n,r){return new Mi(e,t,i,{style:n,id:r==null?void 0:r.id,layoutId:r==null?void 0:r.layoutId})}primaryPoint(){return eo(this.start,this.end,this.geom)}toRecord(e){return{id:this.entityId,type:"arc",layoutId:e,style:dt(this.style),geometry:{type:"arc",center:{x:this.geom.cx,y:this.geom.cy},radius:this.geom.r,start:{x:this.start.x,y:this.start.y},end:{x:this.end.x,y:this.end.y}}}}subWorldDrawWithDb(e,t){const i=this.style.color,n=bd(this.start,this.end,this.geom),r=eo(this.start,this.end,this.geom),o=this.resolveLayoutId(e),a=new M.AcTrHtmlCanvasOverlay({id:`arc-canvas-${this.entityId}`,container:e.container,layer:Y,layoutId:o}),l=(p=this.style)=>fd(a.canvas,e,this.geom,this.start,this.end,p.color,Ve(p.lineWeight));l();const c=()=>l(kt(this.entityId)??this.style);return e.events.viewChanged.addEventListener(c),{group:this.createGroup(e).add(new M.AcTrHtmlDot({id:`${this.entityId}-dot1`,color:i,worldPosition:this.start,layer:Y}),new M.AcTrHtmlDot({id:`${this.entityId}-dot2`,color:i,worldPosition:this.end,layer:Y}),new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:i,text:Te(t,n),worldPosition:r,layer:Y,fontSize:this.style.fontSize})).addCanvas(a),entityIds:[],dispose:()=>{e.events.viewChanged.removeEventListener(c)},extras:{style:this.style,value:{kind:"length",value:n},snapshot:this.toRecord(o),redraw:l}}}}class Di extends ti{constructor(e,t){super(t.id??`area-${Date.now()}`,t.layoutId,t.style),this.points=e}static create(e,t,i){return new Di(e,{style:t,id:i==null?void 0:i.id,layoutId:i==null?void 0:i.layoutId})}primaryPoint(){if(this.points.length===0)return;const e=to(this.points);return{x:e.x,y:e.y,z:0}}toRecord(e){return{id:this.entityId,type:"area",layoutId:e,style:dt(this.style),geometry:{type:"area",points:this.points.map(t=>({x:t.x,y:t.y}))}}}subWorldDrawWithDb(e,t){if(this.points.length<3)return{group:this.createGroup(e),entityIds:[],dispose:()=>{},extras:{}};const i=this.style.color,n=wd(this.points),r=this.resolveLayoutId(e),o=to(this.points),a=new M.AcTrHtmlCanvasOverlay({id:`area-canvas-${this.entityId}`,container:e.container,layer:Y,layoutId:r}),l=(p=this.style)=>gd(a.canvas,e,this.points,p.color,Ve(p.lineWeight));l();const c=()=>l(kt(this.entityId)??this.style);return e.events.viewChanged.addEventListener(c),{group:this.createGroup(e).add(new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:i,text:`${Te(t,n)}²`,worldPosition:o,layer:Y,fontSize:this.style.fontSize}),...this.points.map((p,m)=>new M.AcTrHtmlDot({id:`${this.entityId}-dot${m}`,color:i,worldPosition:p,layer:Y}))).addCanvas(a),entityIds:[],dispose:()=>{e.events.viewChanged.removeEventListener(c)},extras:{style:this.style,value:{kind:"area",value:n},snapshot:this.toRecord(r),redraw:l}}}}function pg(s,e){const t=e.x-s.x,i=e.y-s.y;return Math.sqrt(t*t+i*i)}class Oi extends ti{constructor(e,t,i){super(i.id??`dist-${Date.now()}`,i.layoutId,i.style),this.p1=e,this.p2=t}static create(e,t,i,n){return new Oi(e,t,{style:i,id:n==null?void 0:n.id,layoutId:n==null?void 0:n.layoutId})}primaryPoint(){return{x:(this.p1.x+this.p2.x)/2,y:(this.p1.y+this.p2.y)/2,z:0}}toRecord(e){return{id:this.entityId,type:"distance",layoutId:e,style:dt(this.style),geometry:{type:"distance",start:{x:this.p1.x,y:this.p1.y},end:{x:this.p2.x,y:this.p2.y}}}}subWorldDrawWithDb(e,t){const i=pg(this.p1,this.p2),n=this.style.color,r=this.resolveLayoutId(e),o=this.primaryPoint(),a=new M.AcTrHtmlCanvasOverlay({id:`dist-canvas-${this.entityId}`,container:e.container,layer:Y,layoutId:r}),l=(p=this.style)=>md(a.canvas,e,this.p1,this.p2,p.color,Ve(p.lineWeight));l();const c=()=>l(kt(this.entityId)??this.style);return e.events.viewChanged.addEventListener(c),{group:this.createGroup(e).add(new M.AcTrHtmlDot({id:`${this.entityId}-dot1`,color:n,worldPosition:this.p1,layer:Y}),new M.AcTrHtmlDot({id:`${this.entityId}-dot2`,color:n,worldPosition:this.p2,layer:Y}),new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:n,text:Te(t,i),worldPosition:o,layer:Y,fontSize:this.style.fontSize})).addCanvas(a),entityIds:[],dispose:()=>{e.events.viewChanged.removeEventListener(c)},extras:{style:this.style,value:{kind:"length",value:i},snapshot:this.toRecord(r),redraw:l}}}}class ji extends ti{constructor(e,t){super(t.id??`point-${Date.now()}`,t.layoutId,t.style),this.point=e}static create(e,t,i){return new ji(e,{style:t,id:i==null?void 0:i.id,layoutId:i==null?void 0:i.layoutId})}primaryPoint(){return{x:this.point.x,y:this.point.y,z:0}}toRecord(e){return{id:this.entityId,type:"point",layoutId:e,style:dt(this.style),geometry:{type:"point",position:{x:this.point.x,y:this.point.y}}}}subWorldDrawWithDb(e,t){const i=this.resolveLayoutId(e),n={kind:"coordinate",x:this.point.x,y:this.point.y},r=this.style.color;return{group:this.createGroup(e).add(new M.AcTrHtmlDot({id:`${this.entityId}-dot`,color:r,worldPosition:this.point,layer:Y}),new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:r,text:Ks(t,n),worldPosition:this.point,layer:Y,fontSize:this.style.fontSize,transform:"translate(-50%, calc(-50% - 16px))"})),entityIds:[],dispose:()=>{},extras:{style:this.style,value:n,snapshot:this.toRecord(i)}}}}function xd(s){const e=ha(s.style),t={id:s.id,layoutId:s.layoutId,style:e},i=s.geometry;switch(i.type){case"distance":return new Oi({x:i.start.x,y:i.start.y,z:0},{x:i.end.x,y:i.end.y,z:0},t);case"angle":return new Ii({x:i.vertex.x,y:i.vertex.y,z:0},{x:i.arm1.x,y:i.arm1.y,z:0},{x:i.arm2.x,y:i.arm2.y,z:0},t);case"area":return new Di(i.points.map(n=>({x:n.x,y:n.y,z:0})),t);case"arc":return new Mi({cx:i.center.x,cy:i.center.y,r:i.radius},i.start,i.end,t);case"point":return new ji({x:i.position.x,y:i.position.y,z:0},t)}}function mg(s){return`${s}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Sd(s,e,t){const i=t.geometry.type==="distance"?"dist":t.geometry.type,n={...t,id:mg(i)};try{return xd(n).commit(s,e),!0}catch{return!1}}function yg(s,e){if(typeof document>"u")return;const t=new Blob([e],{type:"application/json;charset=utf-8"}),i=URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download=s,n.click(),URL.revokeObjectURL(i)}function gg(){return new Promise(s=>{if(typeof document>"u"){s(void 0);return}const e=document.createElement("input");e.type="file",e.accept=".json,application/json";let t=!1;const i=n=>{t||(t=!0,s(n))};e.addEventListener("cancel",()=>i()),e.onchange=async()=>{var r;const n=(r=e.files)==null?void 0:r[0];if(!n){i();return}i(await n.text())},e.click()})}class Pd extends z{constructor(){super(),this.mode=F.Read,this.recordsUndoStack=!1}async execute(e){const t=e.view,i=e.doc.fileName||e.doc.docTitle,n=ma({version:1,drawingName:i,measurements:va(t)});yg(ya(i),n)}}class Ad extends z{constructor(){super(),this.mode=F.Read,this.recordsUndoStack=!1}async execute(e){new le(d.t("jig.measurement.import.chooseFile"));const t=await gg();if(t==null)return;let i;try{i=pa(t)}catch(o){console.error(o);return}const n=e.view,r=e.doc.database;Bt(n,"Import Measurements",()=>{for(const o of i.measurements)Sd(n,r,o)})}}class Oe{constructor(e,t,i){this.drawFn=null,this.onViewChanged=()=>this.acapPaint(),this.view=e,this.overlay=new M.AcTrHtmlCanvasOverlay({id:t,container:e.container,layer:i,layoutId:e.activeLayoutBtrId}),e.htmlTransientManager.add(this.overlay),e.events.viewChanged.addEventListener(this.onViewChanged)}get id(){return this.overlay.id}acapSetDraw(e){this.drawFn=e,this.acapPaint(),this.view.isHtmlDirty=!0}acapClear(){this.acapSetDraw(null)}acapDispose(){this.view.events.viewChanged.removeEventListener(this.onViewChanged),this.view.htmlTransientManager.remove(this.overlay.id),this.view.isHtmlDirty=!0}acapPaint(){var t;const e=Ct(this.overlay.canvas,this.view.container);e&&((t=this.drawFn)==null||t.call(this,e,this.view))}}function ft(s,e,t,i,n,r,o){const a=typeof n=="string"?n:ge(n),l=e.worldToScreen(t),c=e.worldToScreen(i);s.strokeStyle=a,s.lineWidth=r,o!=null&&o.dashed&&s.setLineDash([8,5]),s.beginPath(),s.moveTo(l.x,l.y),s.lineTo(c.x,c.y),s.stroke(),o!=null&&o.dashed&&s.setLineDash([]),o!=null&&o.arrow&&ls(s,l,c,a)}function Bi(s,e,t,i,n,r){if(t.length<2)return;const o=typeof i=="string"?i:ge(i),a=t.map(l=>e.worldToScreen(l));s.strokeStyle=o,s.lineWidth=n,r!=null&&r.dashed&&s.setLineDash([8,5]),s.beginPath(),s.moveTo(a[0].x,a[0].y);for(let l=1;l<a.length;l++)s.lineTo(a[l].x,a[l].y);r!=null&&r.closed&&s.closePath(),s.stroke(),r!=null&&r.dashed&&s.setLineDash([])}function oo(s,e,t,i,n,r){if(i<=0)return;const o=typeof n=="string"?n:ge(n),a=e.worldToScreen(t),l=e.worldToScreen({x:t.x+i,y:t.y}),c=Math.hypot(l.x-a.x,l.y-a.y);s.strokeStyle=o,s.lineWidth=r,s.beginPath(),s.arc(a.x,a.y,c,0,Math.PI*2),s.stroke()}function fg(s,e,t,i,n,r){no(s,e.worldToScreen(t),e.worldToScreen(i),n,r)}function ao(s,e){return[{x:s.x,y:s.y},{x:e.x,y:s.y},{x:e.x,y:e.y},{x:s.x,y:e.y}]}function bg(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=t.x-s.x,o=t.y-s.y,a=i*r+n*o,l=i*o-n*r;return Math.atan2(Math.abs(l),a)*180/Math.PI}function Cd(s,e,t,i,n,r,o){Ii.create(t,i,n,r,o).commit(s,e)}class wg extends G{constructor(e,t,i){super(e),this._vertex=t,this._cursor=t,this._color=i,this._preview=new Oe(e,`live-angle-arm1-${Date.now()}`,ue)}get entity(){return null}update(e){this._cursor=e;const t=Ve(jt());this._preview.acapSetDraw((i,n)=>{ft(i,n,this._vertex,this._cursor,this._color,t)})}end(){super.end(),this._preview.acapDispose()}}class vg extends G{constructor(e,t,i,n,r){super(e),this._view=e,this._vertex=i,this._arm1=n,this._arm2=i,this._color=r,this._db=t,this._badgeId=`live-angle-badge-${Date.now()}`,this._htManager=this._view.htmlTransientManager,this._badge=new M.AcTrHtmlBadge({id:this._badgeId,color:r,worldPosition:i,layer:ue,layoutId:this._view.activeLayoutBtrId,fontSize:wt(),transform:"translate(-50%, calc(-50% - 30px))"}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new Oe(this._view,`live-angle-arm2-${Date.now()}`,ue)}get entity(){return null}update(e){this._arm2=e,this._color=Je(this._db),this._badge.setColor(this._color),this._badge.setFontSize(wt());const t=Ve(jt());this._preview.acapSetDraw((n,r)=>{ft(n,r,this._vertex,this._arm1,this._color,t,{dashed:!0}),ft(n,r,this._vertex,this._arm2,this._color,t)});const i=bg(this._vertex,this._arm1,e);this._badge.setText(ln(this._db,i*Math.PI/180)),this._badge.setPosition(this._vertex),this._badge.object.visible=!0}end(){super.end(),this._preview.acapDispose(),this._htManager.remove(this._badgeId)}}class _d extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Je(i);await e.view.withMode(me.SELECTION,()=>t.withCursor(Ce.Crosshair,async()=>{const r=new I(d.t("jig.measureAngle.vertex")),o=await t.getPoint(r);if(o.status!==b.OK)return;const a=o.value,l=new I(d.t("jig.measureAngle.arm1"));l.useBasePoint=!0,l.jig=new wg(e.view,a,n);const c=await t.getPoint(l);if(c.status!==b.OK)return;const h=c.value,p=new I(d.t("jig.measureAngle.arm2"));p.jig=new vg(e.view,i,a,h,n);const m=await t.getPoint(p);if(m.status!==b.OK)return;const g=m.value;Cd(e.view,i,a,h,g,at(i))}))}}class kg extends G{constructor(e,t,i,n){super(e),this._onMove=n}get entity(){return null}update(e){this._onMove(e)}}function xg(s,e,t,i){const n=e.x-s.x,r=e.y-s.y,o=i.x-t.x,a=i.y-t.y,l=n*a-r*o;if(Math.abs(l)<1e-10)return!1;const c=t.x-s.x,h=t.y-s.y,p=(c*a-h*o)/l,m=(c*r-h*n)/l;return p>0&&p<1&&m>0&&m<1}function Sg(s){let e=0;const t=s.length;for(let i=0;i<t;i++){const n=(i+1)%t;e+=s[i].x*s[n].y,e-=s[n].x*s[i].y}return Math.abs(e)/2}function Pg(s){const e=s.reduce((i,n)=>i+n.x,0)/s.length,t=s.reduce((i,n)=>i+n.y,0)/s.length;return{x:e,y:t}}function Ed(s,e,t,i,n){t.length<3||Di.create(t,i,n).commit(s,e)}class Ld extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Je(i),r=at(i),o=Ve(r.lineWeight),a=[],l=new M.AcTrHtmlCanvasOverlay({id:`live-area-canvas-${Date.now()}`,container:e.view.container,layer:ue,layoutId:e.view.activeLayoutBtrId}),c=l.canvas,h=e.view.htmlTransientManager;h.add(l);const p=`live-area-badge-${Date.now()}`,m=new M.AcTrHtmlBadge({id:p,color:n,worldPosition:{x:0,y:0},layer:ue,layoutId:e.view.activeLayoutBtrId,fontSize:r.fontSize});m.object.visible=!1,h.add(m);const g=v=>{const x=e.view.canvas.getBoundingClientRect(),S=window.devicePixelRatio||1,P=Math.round(x.width),A=Math.round(x.height),_=e.view.canvasToContainer({x:0,y:0});c.style.left=`${_.x}px`,c.style.top=`${_.y}px`,c.style.width=`${P}px`,c.style.height=`${A}px`,(c.width!==P*S||c.height!==A*S)&&(c.width=P*S,c.height=A*S);const C=c.getContext("2d");if(!C||a.length<1)return;C.clearRect(0,0,c.width,c.height),C.save(),C.scale(S,S);const O=a.map(L=>e.view.worldToScreen(L)),j=v?[...O,e.view.worldToScreen(v)]:O;if(j.length>=3){C.beginPath(),C.moveTo(j[0].x,j[0].y);for(let L=1;L<j.length;L++)C.lineTo(j[L].x,j[L].y);C.closePath(),C.fillStyle=Ws(n,.2),C.fill()}if(O.length>=2){C.beginPath(),C.moveTo(O[0].x,O[0].y);for(let L=1;L<O.length;L++)C.lineTo(O[L].x,O[L].y);C.strokeStyle=ge(n),C.lineWidth=o,C.setLineDash([8,5]),C.stroke(),C.setLineDash([])}if(v&&O.length>=1){const L=O[O.length-1],N=e.view.worldToScreen(v);C.beginPath(),C.moveTo(L.x,L.y),C.lineTo(N.x,N.y),C.strokeStyle=ge(n),C.lineWidth=o,C.stroke()}C.restore()},f=()=>g();e.view.events.viewChanged.addEventListener(f);const w=()=>{h.remove(p),h.remove(l.id),e.view.events.viewChanged.removeEventListener(f)};try{await e.view.withMode(me.SELECTION,()=>t.withCursor(Ce.Crosshair,async()=>{const v=await t.getPoint(new I(d.t("jig.measureArea.firstPoint")));if(v.status!==b.OK)return;const x=v.value;a.push(x),g();try{for(;a.length<50;){const S=new I(d.t("jig.measureArea.nextPoint"));S.useBasePoint=!0,S.allowNone=!0;const P=C=>{if(a.length<2){g(C);return}const O=[...a,C],j=Sg(O);m.setText(`${Te(i,j)}²`),m.setPosition(Pg(O)),m.object.visible=!0,g(C)};S.jig=new kg(e.view,a[a.length-1],n,P);const A=await t.getPoint(S);if(A.status!==b.OK)break;const _=A.value;if(m.object.visible=!1,a.length>=3){const C=e.view.worldToScreen(_),O=j=>{const L=e.view.worldToScreen(j),N=C.x-L.x,R=C.y-L.y;return N*N+R*R<=196};if(O(a[0])||O(a[a.length-1]))break}if(a.length>=3){const C=a[a.length-1];let O=!1;for(let j=0;j<a.length-2;j++)if(xg(C,_,a[j],a[j+1])){O=!0;break}if(O)break}a.push(_),g()}}catch{}}))}finally{w()}a.length<3||Ed(e.view,i,a,at(i))}}function lo(s,e){const t=Math.atan2(s.y-e.cy,s.x-e.cx);return{x:e.cx+e.r*Math.cos(t),y:e.cy+e.r*Math.sin(t),z:0}}function Ag(s,e,t){const i=Math.atan2(s.y-t.cy,s.x-t.cx),n=Math.atan2(e.y-t.cy,e.x-t.cx),o=(a=>(a%(2*Math.PI)+2*Math.PI)%(2*Math.PI))(n-i);return Math.min(o,2*Math.PI-o)*t.r}function Cg(s,e,t){const i=Math.atan2(s.y-t.cy,s.x-t.cx),n=Math.atan2(e.y-t.cy,e.x-t.cx),o=(l=>(l%(2*Math.PI)+2*Math.PI)%(2*Math.PI))(n-i),a=o<=Math.PI?i+o/2:i-(2*Math.PI-o)/2;return{x:t.cx+t.r*Math.cos(a),y:t.cy+t.r*Math.sin(a),z:0}}function Td(s,e,t,i,n,r,o=4){const a=e.canvas.getBoundingClientRect(),l=window.devicePixelRatio||1,c=Math.round(a.width),h=Math.round(a.height),p=e.canvasToContainer({x:0,y:0});s.style.left=`${p.x}px`,s.style.top=`${p.y}px`,s.style.width=`${c}px`,s.style.height=`${h}px`,(s.width!==c*l||s.height!==h*l)&&(s.width=c*l,s.height=h*l);const m=s.getContext("2d");if(!m)return;m.clearRect(0,0,s.width,s.height),m.save(),m.scale(l,l);const g=e.worldToScreen({x:t.cx,y:t.cy}),f=e.worldToScreen(i),w=e.worldToScreen(n),v=Math.hypot(f.x-g.x,f.y-g.y),x=Math.atan2(f.y-g.y,f.x-g.x),S=Math.atan2(w.y-g.y,w.x-g.x),_=(C=>(C%(2*Math.PI)+2*Math.PI)%(2*Math.PI))(S-x)>Math.PI;m.beginPath(),m.arc(g.x,g.y,v,x,S,_),m.strokeStyle=ge(r),m.lineWidth=o,m.stroke(),m.restore()}function Id(s,e,t,i,n,r,o){Mi.create(t,i,n,r,o).commit(s,e)}class _g extends G{constructor(e,t,i){super(e.view),this._ctx=e,this._onSnap=i;const n={x:0,y:0,z:0};this._indicatorId=`live-arc-snap-${Date.now()}`,this._htManager=e.view.htmlTransientManager,this._indicator=new M.AcTrHtmlSnapIndicator({id:this._indicatorId,color:t,worldPosition:n,layer:ue,layoutId:e.view.activeLayoutBtrId}),this._indicator.object.visible=!1,this._htManager.add(this._indicator)}get entity(){return null}update(e){const t=this._ctx.view.pick(e),i=this._ctx.doc.database.tables.blockTable.modelSpace;let n=null,r=Number.MAX_VALUE;for(const o of t){const a=i.getIdAt(o.id);let l=null;if(a instanceof u.AcDbCircle?l={cx:a.center.x,cy:a.center.y,r:a.radius}:a instanceof u.AcDbArc&&(l={cx:a.center.x,cy:a.center.y,r:a.radius}),l){const c=Math.hypot(e.x-l.cx,e.y-l.cy),h=Math.abs(c-l.r);h<r&&(r=h,n=l)}}if(n){const o=lo(e,n),a=this._ctx.view.worldToScreen(e),l=this._ctx.view.worldToScreen(o);if(Math.hypot(a.x-l.x,a.y-l.y)<=20){this._indicator.setPosition(o),this._indicator.object.visible=!0,this._onSnap(n,o);return}}this._indicator.object.visible=!1,this._onSnap(null,null)}end(){super.end(),this._htManager.remove(this._indicatorId)}}class Eg extends G{constructor(e,t,i,n){super(e),this._geom=t,this._onMove=n;const r={x:0,y:0,z:0};this._indicatorId=`live-arc-end-snap-${Date.now()}`,this._htManager=e.htmlTransientManager,this._indicator=new M.AcTrHtmlSnapIndicator({id:this._indicatorId,color:i,worldPosition:r,layer:ue,layoutId:e.activeLayoutBtrId}),this._htManager.add(this._indicator)}get entity(){return null}update(e){const t=lo(e,this._geom);this._indicator.setPosition(t),this._indicator.object.visible=!0,this._onMove(t)}end(){super.end(),this._htManager.remove(this._indicatorId)}}class Md extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Je(i),r=at(i),o=Ve(r.lineWeight),a=`live-arc-${Date.now()}`,l=new M.AcTrHtmlCanvasOverlay({id:`${a}-canvas`,container:e.view.container,layer:ue,layoutId:e.view.activeLayoutBtrId}),c=e.view.htmlTransientManager;c.add(l),await e.view.withMode(me.SELECTION,()=>t.withCursor(Ce.Crosshair,async()=>{let h=null,p=null;const m=new _g(e,n,(N,R)=>{h=N,p=R}),g=new I(d.t("jig.measureArc.startPoint"));g.jig=m;try{if((await t.getPoint(g)).status!==b.OK){c.remove(l.id);return}}catch{c.remove(l.id);return}if(!h||!p){c.remove(l.id);return}const f=h,w=p,v=`${a}-dot1`,x=`${a}-badge`;c.add(new M.AcTrHtmlDot({id:v,color:n,worldPosition:w,layer:ue,layoutId:e.view.activeLayoutBtrId}));const S=new M.AcTrHtmlBadge({id:x,color:n,worldPosition:w,layer:ue,layoutId:e.view.activeLayoutBtrId,fontSize:r.fontSize});S.object.visible=!1,c.add(S);const P=()=>Td(l.canvas,e.view,f,w,w,n,o),A=()=>P();e.view.events.viewChanged.addEventListener(A);const _=()=>{c.remove(v),c.remove(x),c.remove(l.id),e.view.events.viewChanged.removeEventListener(A)},C=N=>{Td(l.canvas,e.view,f,w,N,n,o);const R=Ag(w,N,f);S.setText(Te(i,R)),S.setPosition(Cg(w,N,f)),S.object.visible=!0},O=new I(d.t("jig.measureArc.endPoint"));O.jig=new Eg(e.view,f,n,C);let j;try{const N=await t.getPoint(O);if(N.status!==b.OK){_();return}j=N.value}catch{_();return}_();const L=lo(j,f);Id(e.view,i,f,w,L,at(i))}))}}function Lg(s,e){const t=e.x-s.x,i=e.y-s.y;return Math.sqrt(t*t+i*i)}function Dd(s,e,t,i,n,r){Oi.create(t,i,n,r).commit(s,e)}class Od extends G{constructor(e,t,i,n){super(e),this._view=e,this._p1=i,this._p2=i,this._db=t,this._color=n,this._badgeId=`live-dist-badge-${Date.now()}`,this._htManager=this._view.htmlTransientManager,this._badge=new M.AcTrHtmlBadge({id:this._badgeId,color:n,worldPosition:i,layer:ue,layoutId:this._view.activeLayoutBtrId,fontSize:wt()}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new Oe(this._view,`live-dist-stroke-${Date.now()}`,ue)}get entity(){return null}update(e){this._p2=e,this._color=Je(this._db),this._badge.setColor(this._color),this._badge.setFontSize(wt());const t=Lg(this._p1,e),i=Ve(jt());if(this._preview.acapSetDraw((n,r)=>{ft(n,r,this._p1,this._p2,this._color,i)}),t<1e-4){this._badge.object.visible=!1;return}this._badge.setText(Te(this._db,t)),this._badge.setPosition({x:(this._p1.x+e.x)/2,y:(this._p1.y+e.y)/2}),this._badge.object.visible=!0}end(){super.end(),this._preview.acapDispose(),this._htManager.remove(this._badgeId)}}class jd extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Je(i);await e.view.withMode(me.SELECTION,()=>t.withCursor(Ce.Crosshair,async()=>{const r=new I(d.t("jig.measureDistance.firstPoint")),o=await t.getPoint(r);if(o.status!==b.OK)return;const a=o.value,l=new I(d.t("jig.measureDistance.secondPoint"));l.useBasePoint=!0,l.jig=new Od(e.view,i,a,n);const c=await t.getPoint(l);if(c.status!==b.OK)return;const h=c.value;Dd(e.view,i,a,h,at(i))}))}}function Bd(s,e,t,i,n){ji.create(t,i,n).commit(s,e)}class Fd extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database;await e.view.withMode(me.SELECTION,()=>t.withCursor(Ce.Crosshair,async()=>{const n=new I(d.t("jig.measurePoint.point")),r=await t.getPoint(n);if(r.status!==b.OK)return;const o=r.value;Bd(e.view,i,o,at(i))}))}}function co(){return new u.AcCmColor(u.AcCmColorMethod.ByACI,1)}const ds=u.AcGiLineWeight.LineWeight070,zd=12;let Nd=co(),Rd=ds,Vd=zd;const uo=new Set;function ho(){for(const s of uo)s()}function po(s){return uo.add(s),()=>{uo.delete(s)}}function ee(){return Nd.clone()}function Pe(){return Rd}function tt(){return Vd}function Gd(s){Nd=s.clone(),ho()}function Kd(s){s>0&&(Rd=s,ho())}function Ud(s){!Number.isFinite(s)||s<=0||(Vd=s,ho())}function je(s){const e=Number(s);return!Number.isFinite(e)||e<=0?2:Math.max(1,e/28)}function Et(s){return s.cssColor??`rgb(${s.red}, ${s.green}, ${s.blue})`}function mo(s){const e=u.AcCmColor.fromString(s);if(e)return e;try{return new u.AcCmColor().setRGBFromCss(s)}catch{return co()}}function us(){return{color:Et(ee()),lineWeight:Pe(),fontSize:tt()}}function Hd(s="markup"){return typeof crypto<"u"&&"randomUUID"in crypto?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Wd(){return new Date().toISOString()}function $d(s){const e=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.LOGINNAME,s);return typeof e=="string"?e.trim():""}const Yd=F.Review;function Be(s){s.mode=Yd,s.recordsUndoStack=!1}function Fe(s,e,t,i){const n=Wd();return{id:Hd(s),type:s,layoutId:e.activeLayoutBtrId,style:us(),text:i==null?void 0:i.text,comment:(i==null?void 0:i.comment)??"",status:"open",author:$d(t.doc.database),createdAt:n,updatedAt:n}}async function yo(s,e,t=""){const i=new le(d.t(e));i.allowEmpty=!0,i.allowSpaces=!0,i.defaultValue=t,i.useDefaultValue=!0;const n=await s.view.editor.getString(i);if(n.status===b.OK)return(n.stringResult??t).trim()}async function hs(s,e){return(await pr({el:s.textElement,listenOn:s.element,multiline:(e==null?void 0:e.multiline)??!0,initialText:(e==null?void 0:e.initialText)??""})??"").trim()}async function Ze(s,e){await s.view.withMode(me.SELECTION,()=>s.view.editor.withCursor(Ce.Crosshair,e))}let ps;function Zd(s){ps=s}function Fi(s,e){ps==null||ps(s,e)}function Xd(s){const e=s.style.lineWeight!=null&&s.style.lineWeight>0?s.style.lineWeight:ds;return{color:mo(s.style.color),lineWeight:e,canvasLineWidth:je(e),layer:an,layoutId:s.layoutId}}class Lt extends so{constructor(e){super(),this.record=e}get id(){return this.record.id}toRecord(){return this.record}get markupRecord(){return this.toRecord()}setRecord(e){this.record=e}style(){return Xd(this.record)}hitTest(e,t,i){return zs(this.record.geometry,e,t,i)}primaryPoint(){const e=rn(this.record.geometry);if(e)return{x:e.x,y:e.y,z:0}}subGetGripPoints(){const e=rn(this.record.geometry);return e?[new u.AcGePoint3d(e.x,e.y,0)]:[]}subMoveGripPointsAt(e,t){return e.length===0?this:e.includes(0)?(this.record={...this.record,geometry:Fs(this.record.geometry,t.x,t.y)},this):this}emptyResult(e){return{group:e,entityIds:[],dispose:()=>{}}}createGroup(){const{layer:e,layoutId:t}=this.style();return new M.AcTrHtmlGroup({id:this.record.id,layer:e,layoutId:t,selectable:!0})}}const Tg=8;function Ig(s,e,t){const i=s.worldToScreen(t),n={x:i.x+e,y:i.y},r=s.screenToWorld(n);return Math.abs(r.x-t.x)}function zi(s,e,t){const i=Math.min(s.x,e.x),n=Math.max(s.x,e.x),r=Math.min(s.y,e.y),o=Math.max(s.y,e.y),a=n-i,l=o-r,c={x:(i+n)/2,y:(r+o)/2},h=Ig(t,Tg,c),p=Math.max(h,1e-6),m=Math.max(4,Math.ceil(a/p)*2),g=Math.max(4,Math.ceil(l/p)*2),f=[];let w=0;const v=x=>x?.4:-.4;for(let x=0;x<=m;x++){const S=x/m;f.push({x:i+a*S,y:r,bulge:x<m?v(w++%2===0):0})}for(let x=1;x<=g;x++){const S=x/g;f.push({x:n,y:r+l*S,bulge:x<g?v(w++%2===0):0})}for(let x=1;x<=m;x++){const S=1-x/m;f.push({x:i+a*S,y:o,bulge:x<m?v(w++%2===0):0})}for(let x=1;x<g;x++){const S=1-x/g;f.push({x:i,y:r+l*S,bulge:x<g-1?v(w++%2===0):0})}return f}function qd(s,e){return[{x:s.x,y:s.y},{x:e.x,y:s.y},{x:e.x,y:e.y},{x:s.x,y:e.y}]}function Mg(s,e,t,i=6){if(Math.abs(t)<1e-8)return[{x:e.x,y:e.y}];const n=e.x-s.x,r=e.y-s.y;if(Math.hypot(n,r)<1e-12)return[{x:e.x,y:e.y}];const a=(s.x+e.x)/2-r*(1-t*t)/(4*t),l=(s.y+e.y)/2+n*(1-t*t)/(4*t),c=Math.hypot(s.x-a,s.y-l),h=Math.atan2(s.y-l,s.x-a);let m=Math.atan2(e.y-l,e.x-a)-h;t>0?m<=0&&(m+=Math.PI*2):m>=0&&(m-=Math.PI*2);const g=[],f=Math.max(2,i);for(let w=1;w<=f;w++){const v=w/f,x=h+m*v;g.push({x:a+c*Math.cos(x),y:l+c*Math.sin(x)})}return g}function ms(s){if(s.length<2)return s.map(t=>({x:t.x,y:t.y}));const e=[{x:s[0].x,y:s[0].y}];for(let t=0;t<s.length;t++){const i=s[t],n=s[(t+1)%s.length],r=Mg({x:i.x,y:i.y},{x:n.x,y:n.y},i.bulge);for(const o of r)e.push(o)}return e}function Jd(s,e,t,i,n,r,o){const a=(o==null?void 0:o.dx)??0,l=(o==null?void 0:o.dy)??0,c=zi(t,i,e),h=ms(c).map(m=>({x:m.x+a,y:m.y+l}));if(h.length<2)return;const p=h.map(m=>e.worldToScreen(m));s.strokeStyle=n,s.lineWidth=r,s.beginPath(),s.moveTo(p[0].x,p[0].y);for(let m=1;m<p.length;m++)s.lineTo(p[m].x,p[m].y);s.closePath(),s.stroke()}function Dg(s,e,t,i){const n=zi(e,t,i);s.reset(!1);for(let r=0;r<n.length;r++)s.addVertexAt(r,{x:n[r].x,y:n[r].y},n[r].bulge);s.closed=!0}function Og(s,e,t){const i=qd(e,t);s.reset(!1);for(let n=0;n<i.length;n++)s.addVertexAt(n,i[n]);s.closed=!0}let ii=!0;function jg(){return ii}function Bg(s){ii=s}async function ys(s,e){for(;;){const t=ii?"jig.markup.shape.calloutOn":"jig.markup.shape.calloutOff",i=new I(`${d.t(e)} ${d.t(t)}`);i.keywords.add(d.t("jig.markup.shape.keywords.callout.display"),d.t("jig.markup.shape.keywords.callout.global"),d.t("jig.markup.shape.keywords.callout.local")),i.keywords.add(d.t("jig.markup.shape.keywords.noCallout.display"),d.t("jig.markup.shape.keywords.noCallout.global"),d.t("jig.markup.shape.keywords.noCallout.local"));const n=await s.view.editor.getPoint(i);if(n.status===b.Keyword){const r=n.stringResult??"";if(r==="Callout"){ii=!0;continue}if(r==="NoCallout"){ii=!1;continue}continue}return n.status!==b.OK?void 0:n.value}}function Fg(s){return s.kind==="circle"?{...s.center}:{x:(s.corner1.x+s.corner2.x)/2,y:(s.corner1.y+s.corner2.y)/2}}function ni(s,e){if(s.kind==="circle"){const{center:w,radius:v}=s,x=e.x-w.x,S=e.y-w.y,P=Math.hypot(x,S);if(P<1e-9||v<=0)return{x:w.x+v,y:w.y};const A=v/P;return{x:w.x+x*A,y:w.y+S*A}}const t=Math.min(s.corner1.x,s.corner2.x),i=Math.max(s.corner1.x,s.corner2.x),n=Math.min(s.corner1.y,s.corner2.y),r=Math.max(s.corner1.y,s.corner2.y),o=(t+i)/2,a=(n+r)/2,l=(i-t)/2,c=(r-n)/2,h=e.x-o,p=e.y-a;if(Math.abs(h)<1e-9&&Math.abs(p)<1e-9)return{x:i,y:a};const m=Math.abs(h)>1e-9?l/Math.abs(h):Number.POSITIVE_INFINITY,g=Math.abs(p)>1e-9?c/Math.abs(p):Number.POSITIVE_INFINITY,f=Math.min(m,g);return{x:o+h*f,y:a+p*f}}function zg(s,e,t){return ms(zi(s,e,t))}class Ng extends G{constructor(e,t,i){super(e),this._view=e,this._outline=t,this._color=i,this._ht=this._view.htmlTransientManager;const n=Fg(t);this._tip=ni(t,{x:n.x+1,y:n.y}),this._anchor={...this._tip};const r=Date.now();this._tipDotId=`live-shape-callout-tip-${r}`,this._bubbleId=`live-shape-callout-bubble-${r}`;const o=this._view.activeLayoutBtrId;this._tipDot=new M.AcTrHtmlDot({id:this._tipDotId,color:i,worldPosition:this._tip,layer:ae,layoutId:o}),this._ht.add(this._tipDot),this._bubble=new M.AcTrHtmlCallout({id:this._bubbleId,color:i,text:"",fontSize:tt(),worldPosition:this._tip,layer:ae,layoutId:o}),this._ht.add(this._bubble),this._preview=new Oe(this._view,`live-shape-callout-stroke-${r}`,ae),this._unsubDrawStyle=po(()=>this.applyCurrentStyle()),this.paintPreview(),this._view.isHtmlDirty=!0}get entity(){return null}update(e){const t={x:e.x,y:e.y};this._tip=ni(this._outline,t),this._anchor=t,this._tipDot.setPosition(this._tip),this._bubble.setPosition(t),this.paintPreview(),this._view.isHtmlDirty=!0}get capsule(){return this._bubble}end(){}disposePreview(){var e;(e=this._unsubDrawStyle)==null||e.call(this),this._unsubDrawStyle=void 0,this._preview.acapDispose(),this._ht.remove(this._tipDotId),this._ht.remove(this._bubbleId),this._view.isHtmlDirty=!0}applyCurrentStyle(){this._color=ee(),this._tipDot.setColor(this._color),this._bubble.setColor(this._color),this._bubble.setFontSize(tt()),this.paintPreview(),this._view.isHtmlDirty=!0}paintPreview(){const e=this._outline,t=this._color,i=je(Pe()),n=this._tip,r=this._anchor,o=this._view;this._preview.acapSetDraw((a,l)=>{if(e.kind==="circle")oo(a,l,e.center,e.radius,t,i);else if(e.kind==="cloud"){const c=zg(e.corner1,e.corner2,o);Bi(a,l,c,t,i,{closed:!0})}else Bi(a,l,ao(e.corner1,e.corner2),t,i,{closed:!0});ft(a,l,n,r,t,i)})}}async function gs(s,e){if(!ii)return;const t=ee(),i=new Ng(s.view,e,t);try{const n=new I(d.t("jig.markup.shape.calloutAnchor"));n.useBasePoint=!1,n.jig=i;const r=await s.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=ni(e,{x:o.x,y:o.y}),l=await hs(i.capsule);return{tip:a,anchor:{x:o.x,y:o.y},text:l||void 0}}finally{i.disposePreview()}}function Ni(s,e){U().setSelectedId(e),s.htmlTransientManager.selectGroup(e)}function Qd(s){const{view:e,group:t,record:i,callout:n,style:r,cleanups:o,outline:a}=s,{color:l,layer:c,layoutId:h}=r,p=e.container,m=new M.AcTrHtmlCanvasOverlay({id:`${i.id}-shape-leader`,container:p,layer:c,layoutId:h});t.addCanvas(m);const g={tip:{...n.tip},anchor:{...n.anchor}},f=()=>{const S=Ct(m.canvas,p);S&&io(S,e.worldToScreen(g.tip),e.worldToScreen(g.anchor),i.style.color,!1,je(i.style.lineWeight!=null&&i.style.lineWeight>0?i.style.lineWeight:ds))};f(),e.events.viewChanged.addEventListener(f),o.push(()=>e.events.viewChanged.removeEventListener(f));const w=new M.AcTrHtmlCallout({id:`${i.id}-shape-bubble`,color:l,text:n.text||i.text||"",fontSize:i.style.fontSize,worldPosition:g.anchor,layer:c,layoutId:h}),v=new M.AcTrHtmlDot({id:`${i.id}-shape-tip`,color:l,worldPosition:g.tip,layer:c,layoutId:h});return t.add(w,v),o.push(Cn({view:e,el:w.textElement,listenOn:w.element,recordId:i.id,multiline:!0})),{live:g,redraw:f,tipDot:v,bubble:w,bindGrips:()=>{o.push(cs({view:e,tipEl:v,bubbleEl:w,state:g,constrainTip:S=>ni(a,S),onDragStart:()=>Ni(e,i.id),onLiveChange:f,onCommit:S=>{const P=U().get(i.id);if(!P||P.geometry.type!==a.kind)return;const A=P.geometry;A.type!=="cloud"&&A.type!=="rect"&&A.type!=="circle"||ve(e,"Move Callout",()=>{var C;const _=U().updateGeometry(i.id,{...A,callout:{tip:S.tip,anchor:S.anchor,text:((C=A.callout)==null?void 0:C.text)??n.text}});_&&Fi(e,_)})}}))}}}function Ri(s){const{view:e,recordId:t,centerEl:i,onLiveOffset:n,attached:r}=s;let o={x:i.object.position.x,y:i.object.position.y},a={...o},l;return _t({view:e,el:i.element,cursor:"move",onDragStart:()=>{Ni(e,t);const c=U().get(t);o=(c?rn(c.geometry):void 0)??{x:i.object.position.x,y:i.object.position.y},a={...o},l=r?{tip:{...r.live.tip},anchor:{...r.live.anchor}}:void 0},onMove:c=>{a=c;const h=c.x-o.x,p=c.y-o.y;n==null||n(h,p),Ye(e,i,c),r&&l&&(r.live.tip=oe(l.tip,h,p),r.live.anchor=oe(l.anchor,h,p),Ye(e,r.tipDot,r.live.tip),Ye(e,r.bubble,r.live.anchor),r.redraw())},onCommit:()=>{const c=a.x-o.x,h=a.y-o.y;if(Math.hypot(c,h)<1e-9){n==null||n(0,0);return}ve(e,"Move Markup",()=>{const p=U().get(t);if(!p)return;const m=U().updateGeometry(t,Fs(p.geometry,c,h));m&&Fi(e,m)})}})}class eu extends Lt{constructor(e){super(e)}primaryPoint(){const e=this.record.geometry;if(e.type==="callout")return{x:e.anchor.x,y:e.anchor.y,z:0}}subGetGripPoints(){const e=this.record.geometry;return e.type!=="callout"?[]:[new u.AcGePoint3d(e.tip.x,e.tip.y,0),new u.AcGePoint3d(e.anchor.x,e.anchor.y,0),new u.AcGePoint3d((e.tip.x+e.anchor.x)/2,(e.tip.y+e.anchor.y)/2,0)]}subMoveGripPointsAt(e,t){const i=this.record.geometry;if(i.type!=="callout")return this;let n={...i.tip},r={...i.anchor};for(const o of e)o===0?n={x:n.x+t.x,y:n.y+t.y}:o===1?r={x:r.x+t.x,y:r.y+t.y}:o===2&&(n={x:n.x+t.x,y:n.y+t.y},r={x:r.x+t.x,y:r.y+t.y});return this.record={...this.record,geometry:{type:"callout",tip:n,anchor:r}},this}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="callout")return this.emptyResult(this.createGroup());const{color:i,canvasLineWidth:n,layer:r,layoutId:o}=this.style(),a=this.createGroup(),l=[],c=[],h=e.container,p=new M.AcTrHtmlCanvasOverlay({id:`${this.record.id}-leader`,container:h,layer:r,layoutId:o});a.addCanvas(p);const m={tip:{...t.tip},anchor:{...t.anchor}},g=()=>{const S=Ct(p.canvas,h);S&&io(S,e.worldToScreen(m.tip),e.worldToScreen(m.anchor),this.record.style.color,!0,n)};g(),e.events.viewChanged.addEventListener(g),l.push(()=>e.events.viewChanged.removeEventListener(g));const f=new M.AcTrHtmlCallout({id:`${this.record.id}-bubble`,color:i,text:this.record.text||this.record.comment||"Callout",fontSize:this.record.style.fontSize,worldPosition:m.anchor,layer:r,layoutId:o}),w=new M.AcTrHtmlDot({id:`${this.record.id}-tip`,color:i,worldPosition:m.tip,layer:r,layoutId:o}),v=new M.AcTrHtmlDot({id:`${this.record.id}-center`,color:i,worldPosition:{x:(m.tip.x+m.anchor.x)/2,y:(m.tip.y+m.anchor.y)/2},layer:r,layoutId:o});a.add(f,w,v),l.push(Cn({view:e,el:f.textElement,listenOn:f.element,recordId:this.record.id,multiline:!0}));const x=()=>{Ye(e,v,{x:(m.tip.x+m.anchor.x)/2,y:(m.tip.y+m.anchor.y)/2})};return c.push(()=>{l.push(cs({view:e,tipEl:w,bubbleEl:f,state:m,onDragStart:()=>Ni(e,this.record.id),onLiveChange:()=>{g(),x()},onCommit:S=>{ve(e,"Move Callout",()=>{const P=U().updateGeometry(this.record.id,{type:"callout",tip:S.tip,anchor:S.anchor});P&&Fi(e,P)})}}),Ri({view:e,recordId:this.record.id,centerEl:v,attached:{live:m,redraw:g,tipDot:w,bubble:f}}))}),{group:a,entityIds:[],dispose:()=>{for(const S of l)try{S()}catch{}},bindGrips:()=>{for(const S of c)S()}}}}class tu extends Lt{constructor(e){super(e)}subGetGripPoints(){return[]}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="highlight")return this.emptyResult(this.createGroup());const{color:i,canvasLineWidth:n,layer:r,layoutId:o}=this.style(),a=this.createGroup(),l=[],c=e.container,h=new M.AcTrHtmlCanvasOverlay({id:`${this.record.id}-hl`,container:c,layer:r,layoutId:o});a.addCanvas(h);const p=()=>{const m=Ct(h.canvas,c);m&&no(m,e.worldToScreen(t.corner1),e.worldToScreen(t.corner2),this.record.style.color,n)};return p(),e.events.viewChanged.addEventListener(p),l.push(()=>e.events.viewChanged.removeEventListener(p)),a.add(new M.AcTrHtmlDot({id:`${this.record.id}-dot`,color:i,worldPosition:{x:(t.corner1.x+t.corner2.x)/2,y:(t.corner1.y+t.corner2.y)/2},layer:r,layoutId:o})),{group:a,entityIds:[],dispose:()=>{for(const m of l)try{m()}catch{}}}}}class iu extends Lt{constructor(e){super(e)}subGetGripPoints(){const e=this.record.geometry;return e.type!=="line"&&e.type!=="arrow"?[]:[new u.AcGePoint3d(e.start.x,e.start.y,0),new u.AcGePoint3d(e.end.x,e.end.y,0)]}subMoveGripPointsAt(e,t){const i=this.record.geometry;if(i.type!=="line"&&i.type!=="arrow")return this;let n={...i.start},r={...i.end};for(const o of e)o===0?n={x:n.x+t.x,y:n.y+t.y}:o===1&&(r={x:r.x+t.x,y:r.y+t.y});return this.record={...this.record,geometry:i.type==="arrow"?{type:"arrow",start:n,end:r}:{type:"line",start:n,end:r}},this}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="line"&&t.type!=="arrow")return this.emptyResult(this.createGroup());const{color:i,canvasLineWidth:n,layer:r,layoutId:o}=this.style(),a=this.createGroup(),l=[],c=[],h={start:{...t.start},end:{...t.end}},p=new M.AcTrHtmlDot({id:`${this.record.id}-dot1`,color:i,worldPosition:h.start,layer:r,layoutId:o}),m=new M.AcTrHtmlDot({id:`${this.record.id}-dot2`,color:i,worldPosition:h.end,layer:r,layoutId:o});a.add(p,m);const g=e.container,f=new M.AcTrHtmlCanvasOverlay({id:`${this.record.id}-stroke`,container:g,layer:r,layoutId:o});a.addCanvas(f);let w={start:{...h.start},end:{...h.end}};const v=t.type==="arrow",x=()=>{const A=Ct(f.canvas,g);if(!A)return;const _=e.worldToScreen(h.start),C=e.worldToScreen(h.end);A.strokeStyle=this.record.style.color,A.lineWidth=n,A.beginPath(),A.moveTo(_.x,_.y),A.lineTo(C.x,C.y),A.stroke(),v&&ls(A,_,C,this.record.style.color)};x(),e.events.viewChanged.addEventListener(x),l.push(()=>e.events.viewChanged.removeEventListener(x));const S=()=>{Ni(e,this.record.id),w={start:{...h.start},end:{...h.end}}},P=()=>{const A=Math.hypot(h.start.x-w.start.x,h.start.y-w.start.y),_=Math.hypot(h.end.x-w.end.x,h.end.y-w.end.y);if(A<1e-9&&_<1e-9){x();return}ve(e,v?"Move Arrow":"Move Line",()=>{const C=U().updateGeometry(this.record.id,v?{type:"arrow",start:{...h.start},end:{...h.end}}:{type:"line",start:{...h.start},end:{...h.end}});C&&Fi(e,C)})};return c.push(()=>{l.push(_t({view:e,el:p.element,onDragStart:S,onMove:A=>{h.start=A,Ye(e,p,A),x()},onCommit:P}),_t({view:e,el:m.element,onDragStart:S,onMove:A=>{h.end=A,Ye(e,m,A),x()},onCommit:P}))}),{group:a,entityIds:[],dispose:()=>{for(const A of l)try{A()}catch{}},bindGrips:()=>{for(const A of c)A()}}}}class nu extends Lt{constructor(e){super(e)}subGetGripPoints(){return super.subGetGripPoints()}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="cloud"&&t.type!=="rect"&&t.type!=="circle")return this.emptyResult(this.createGroup());const{color:i,canvasLineWidth:n,layer:r,layoutId:o}=this.style(),a=this.createGroup(),l=[],c=[];let h,p,m={dx:0,dy:0};t.type==="cloud"?(h={x:(t.corner1.x+t.corner2.x)/2,y:(t.corner1.y+t.corner2.y)/2},p={kind:"cloud",corner1:t.corner1,corner2:t.corner2}):t.type==="rect"?(h={x:(t.corner1.x+t.corner2.x)/2,y:(t.corner1.y+t.corner2.y)/2},p={kind:"rect",corner1:t.corner1,corner2:t.corner2}):(h={...t.center},p={kind:"circle",center:t.center,radius:t.radius});const g=e.container,f=new M.AcTrHtmlCanvasOverlay({id:`${this.record.id}-shape`,container:g,layer:r,layoutId:o});a.addCanvas(f);const w=()=>{const S=Ct(f.canvas,g);if(!S)return;const P=this.record.style.color;if(t.type==="cloud")Jd(S,e,t.corner1,t.corner2,P,n,m);else if(t.type==="rect"){const A=ao(t.corner1,t.corner2).map(_=>({x:_.x+m.dx,y:_.y+m.dy}));Bi(S,e,A,P,n,{closed:!0})}else oo(S,e,{x:t.center.x+m.dx,y:t.center.y+m.dy},t.radius,P,n)};w(),e.events.viewChanged.addEventListener(w),l.push(()=>e.events.viewChanged.removeEventListener(w));const v=new M.AcTrHtmlDot({id:`${this.record.id}-dot`,color:i,worldPosition:h,layer:r,layoutId:o});a.add(v);const x=t.callout?Qd({view:e,group:a,record:this.record,callout:t.callout,style:this.style(),cleanups:l,outline:p}):void 0;return c.push(()=>{var S;(S=x==null?void 0:x.bindGrips)==null||S.call(x),l.push(Ri({view:e,recordId:this.record.id,centerEl:v,attached:x,onLiveOffset:(P,A)=>{m={dx:P,dy:A},w()}}))}),{group:a,entityIds:[],dispose:()=>{for(const S of l)try{S()}catch{}},bindGrips:()=>{for(const S of c)S()}}}}class su extends Lt{constructor(e){super(e)}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="stamp"&&t.type!=="symbol")return this.emptyResult(this.createGroup());const{color:i,layer:n,layoutId:r}=this.style(),o=this.createGroup(),a=[],l=[],c=t.type==="stamp"?t.stampId:t.symbolId,h=new M.AcTrHtmlStamp({id:`${this.record.id}-stamp`,color:i,stampId:c,text:this.record.text,imageUrl:t.imageUrl,worldPosition:t.position,layer:n,layoutId:r});return o.add(h),l.push(()=>{a.push(Ri({view:e,recordId:this.record.id,centerEl:h}))}),{group:o,entityIds:[],dispose:()=>{for(const p of a)try{p()}catch{}},bindGrips:()=>{for(const p of l)p()}}}}class ru extends Lt{constructor(e){super(e)}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="text")return this.emptyResult(this.createGroup());const{color:i,layer:n,layoutId:r}=this.style(),o=this.createGroup(),a=[],l=[],c=new M.AcTrHtmlBadge({id:`${this.record.id}-badge`,color:i,text:this.record.text||"Note",fontSize:this.record.style.fontSize,worldPosition:t.position,layer:n,layoutId:r});return o.add(c),a.push(Cn({view:e,el:c.element,recordId:this.record.id})),l.push(()=>{a.push(Ri({view:e,recordId:this.record.id,centerEl:c}))}),{group:o,entityIds:[],dispose:()=>{for(const h of a)try{h()}catch{}},bindGrips:()=>{for(const h of l)h()}}}}function fs(s){switch(s.geometry.type){case"text":return new ru(s);case"line":case"arrow":return new iu(s);case"cloud":case"rect":case"circle":return new nu(s);case"highlight":return new tu(s);case"callout":return new eu(s);case"stamp":case"symbol":return new su(s)}}const Rg=fs;function wb(s){return s}class ou{constructor(){this.published=new Set,this.suppressingStoreRemove=!1}republishAll(e){this.clearVisuals(e,{clearStore:!1});for(const t of U().list())this.publish(e,t)}publish(e,t){var f;const i=e,n=U().selectedId===t.id;this.published.has(t.id)&&this.unpublish(e,t.id,{keepInStore:!0});const o=fs(t).worldDraw(i),{group:a,entityIds:l}=o,c={entityIds:l,dispose:o.dispose},h=U(),p=a.onSelectedChanged;a.onSelectedChanged=(w,v)=>{p==null||p(w,v),w?(h.setSelectedId(v.id),c.entityIds.length>0&&i.highlight(c.entityIds)):(h.selectedId===v.id&&h.setSelectedId(void 0),c.entityIds.length>0&&i.unhighlight(c.entityIds))};const m=a.onVisibleChanged;a.onVisibleChanged=(w,v)=>{m==null||m(w,v);for(const x of c.entityIds)i.setTransientEntityVisible(x,w)};const g=a.onDispose;a.onDispose=()=>{g==null||g(),c.entityIds.length>0&&i.unhighlight(c.entityIds),c.dispose(),this.published.delete(t.id),this.suppressingStoreRemove||h.removeRecord(t.id)},i.htmlTransientManager.add(a),(f=o.bindGrips)==null||f.call(o),i.isHtmlDirty=!0,this.published.add(t.id),n&&(U().setSelectedId(t.id),i.htmlTransientManager.selectGroup(t.id))}unpublish(e,t,i){const n=(i==null?void 0:i.keepInStore)===!0,r=()=>this.unpublishInternal(e,t,n);if(!n&&!fe().isBusy){ve(e,"Delete Markup",r);return}r()}unpublishInternal(e,t,i){const n=e;this.suppressingStoreRemove=i;try{n.htmlTransientManager.has(t)?n.htmlTransientManager.remove(t):(this.published.delete(t),i||U().removeRecord(t))}finally{this.suppressingStoreRemove=!1}n.isHtmlDirty=!0}clearVisuals(e,t){const i=(t==null?void 0:t.clearStore)!==!1,n=()=>this.clearVisualsInternal(e,i);if(i&&!fe().isBusy){ve(e,"Clear Markups",n);return}n()}clearLayout(e,t,i){const n=(i==null?void 0:i.clearStore)!==!1,r=()=>{const o=U().list().filter(a=>a.layoutId===t).map(a=>a.id);for(const a of o)this.unpublish(e,a,{keepInStore:!n});e.isHtmlDirty=!0};if(n&&!fe().isBusy){ve(e,"Clear Markups",r);return}r()}clearVisualsInternal(e,t){const i=e;this.suppressingStoreRemove=!0;try{i.htmlTransientManager.deselectAll(),i.htmlTransientManager.clear(an),i.htmlTransientManager.clear(ae),this.published.clear()}finally{this.suppressingStoreRemove=!1}t&&U().clear({markDirty:!0}),i.isHtmlDirty=!0}forgetPublished(){this.published.clear()}select(e,t){e.htmlTransientManager.selectGroup(t),U().setSelectedId(t)}focus(e,t){const i=fs(t).primaryPoint();if(!i)return;const n=e,r=50,o=new u.AcGeBox2d().expandByPoint({x:i.x-r,y:i.y-r}).expandByPoint({x:i.x+r,y:i.y+r});n.zoomTo(o,1.5),this.select(e,t.id)}}let go;function it(){return go||(go=new ou),go}Zd((s,e)=>{it().publish(s,e)});function au(){fe().clear(),vt().clear(),U().reset(),it().forgetPublished(),lt()}function ze(s,e){ve(s,"Create Markup",()=>{U().upsert(e),it().publish(s,e)})}function bs(s,e){const t=U(),i=t.selectedId;i&&ve(s,"Markup Style",()=>{const n=t.updateStyle(i,e);n&&it().publish(s,n)})}class lu extends z{constructor(){super(),Be(this)}async execute(e){const t=e.view;it().clearLayout(t,t.activeLayoutBtrId,{clearStore:!0})}}class Vg extends G{constructor(e,t,i){super(e),this._view=e,this._p1=t,this._p2=t,this._color=i,this._preview=new Oe(this._view,`live-markup-arrow-${Date.now()}`,ae)}get entity(){return null}update(e){this._p2=e,this._color=ee();const t=je(Pe());this._preview.acapSetDraw((i,n)=>{ft(i,n,this._p1,this._p2,this._color,t,{arrow:!0})})}end(){super.end(),this._preview.acapDispose()}}class cu extends z{constructor(){super(),Be(this)}async execute(e){await Ze(e,async()=>{const t=ee(),i=new I(d.t("jig.markup.arrow.firstPoint")),n=await e.view.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new I(d.t("jig.markup.arrow.secondPoint"));o.useBasePoint=!0,o.jig=new Vg(e.view,r,t);const a=await e.view.editor.getPoint(o);if(a.status!==b.OK)return;const l=a.value,h={...Fe("arrow",e.view,e),type:"arrow",geometry:{type:"arrow",start:{x:r.x,y:r.y},end:{x:l.x,y:l.y}}};ze(e.view,h)})}}class Gg extends G{constructor(e,t,i,n){super(e),this._view=e,this._tip={x:t.x,y:t.y,z:t.z??0},this._anchor={...this._tip},this._color=n,this._ht=this._view.htmlTransientManager;const r=this._view.activeLayoutBtrId,o=Date.now();this._tipDotId=`live-markup-callout-tip-${o}`,this._bubbleId=`live-markup-callout-bubble-${o}`,this._tipDot=new M.AcTrHtmlDot({id:this._tipDotId,color:n,worldPosition:this._tip,layer:ae,layoutId:r}),this._ht.add(this._tipDot),this._bubble=new M.AcTrHtmlCallout({id:this._bubbleId,color:n,text:i,fontSize:tt(),worldPosition:this._tip,layer:ae,layoutId:r}),this._ht.add(this._bubble),this._preview=new Oe(this._view,`live-markup-callout-leader-${o}`,ae),this._unsubDrawStyle=po(()=>this.applyCurrentStyle()),this._view.isHtmlDirty=!0}get entity(){return null}update(e){this._anchor={x:e.x,y:e.y,z:e.z??0},this._color=ee(),this._bubble.setPosition(this._anchor),this._bubble.setFontSize(tt()),this.paintLeader(),this._view.isHtmlDirty=!0}get capsule(){return this._bubble}end(){}disposePreview(){var e;(e=this._unsubDrawStyle)==null||e.call(this),this._unsubDrawStyle=void 0,this._preview.acapDispose(),this._ht.remove(this._tipDotId),this._ht.remove(this._bubbleId),this._view.isHtmlDirty=!0}applyCurrentStyle(){this._color=ee(),this._tipDot.setColor(this._color),this._bubble.setColor(this._color),this._bubble.setFontSize(tt()),this.paintLeader(),this._view.isHtmlDirty=!0}paintLeader(){const e=je(Pe()),t=this._color,i=this._tip,n=this._anchor;this._preview.acapSetDraw((r,o)=>{ft(r,o,n,i,t,e,{arrow:!0})})}}class du extends z{constructor(){super(),Be(this)}async execute(e){await Ze(e,async()=>{const t=ee(),i=new I(d.t("jig.markup.callout.tip")),n=await e.view.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new Gg(e.view,r,"",t);try{const a=new I(d.t("jig.markup.callout.anchor"));a.basePoint=new u.AcGePoint3d(r.x,r.y,r.z??0),a.useBasePoint=!0,a.useDashedLine=!1,a.jig=o;const l=await e.view.editor.getPoint(a);if(l.status!==b.OK)return;const c=l.value,h=await hs(o.capsule),m={...Fe("callout",e.view,e,{text:h||void 0}),type:"callout",geometry:{type:"callout",tip:{x:r.x,y:r.y},anchor:{x:c.x,y:c.y}}};ze(e.view,m)}finally{o.disposePreview()}})}}function Kg(s,e){return ro(s,e)}function Ug(s,e,t){Ye(s,e,t)}function Hg(s){return _t(s)}function Wg(s){const{outline:e,...t}=s;return cs({...t,constrainTip:e?i=>ni(e,i):void 0})}class $g extends G{constructor(e,t,i){super(e),this._radius=0,this._view=e,this._center=t,this._color=i,this._preview=new Oe(this._view,`live-markup-circle-${Date.now()}`,ae)}get entity(){return null}update(e){this._radius=Math.max(e,0),this._color=ee();const t=je(Pe());this._preview.acapSetDraw((i,n)=>{oo(i,n,this._center,this._radius,this._color,t)})}end(){super.end(),this._preview.acapDispose()}}class uu extends z{constructor(){super(),Be(this)}async execute(e){await Ze(e,async()=>{const t=ee(),i=await ys(e,"jig.markup.circle.center");if(!i)return;const n=new be(d.t("jig.markup.circle.radius"));n.allowZero=!1,n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(i.x,i.y,i.z??0),n.jig=new $g(e.view,i,t);const r=await e.view.editor.getDistance(n);if(r.status!==b.OK)return;const o=r.value,a=await gs(e,{kind:"circle",center:{x:i.x,y:i.y},radius:o}),c={...Fe("circle",e.view,e,{text:a==null?void 0:a.text}),type:"circle",geometry:{type:"circle",center:{x:i.x,y:i.y},radius:o,callout:a}};ze(e.view,c)})}}function Yg(s,e,t){return ms(zi(s,e,t))}class Zg extends G{constructor(e,t,i){super(e),this._view=e,this._first=t,this._second=t,this._color=i,this._preview=new Oe(this._view,`live-markup-cloud-${Date.now()}`,ae)}get entity(){return null}update(e){this._second=e,this._color=ee();const t=je(Pe()),i=Yg(this._first,this._second,this._view);this._preview.acapSetDraw((n,r)=>{Bi(n,r,i,this._color,t,{closed:!0})})}end(){super.end(),this._preview.acapDispose()}}class hu extends z{constructor(){super(),Be(this)}async execute(e){await Ze(e,async()=>{const t=ee(),i=await ys(e,"jig.markup.cloud.firstCorner");if(!i)return;const n=new I(d.t("jig.markup.cloud.secondCorner"));n.useBasePoint=!0,n.jig=new Zg(e.view,i,t);const r=await e.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=await gs(e,{kind:"cloud",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y}}),c={...Fe("cloud",e.view,e,{text:a==null?void 0:a.text}),type:"cloud",geometry:{type:"cloud",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y},callout:a}};ze(e.view,c)})}}class Xg extends G{constructor(e,t,i){super(e),this._view=e,this._first=t,this._second=t,this._colorCss=Et(i),this._preview=new Oe(this._view,`live-markup-highlight-${Date.now()}`,ae)}get entity(){return null}update(e){this._second=e,this._colorCss=Et(ee());const t=je(Pe());this._preview.acapSetDraw((i,n)=>{fg(i,n,this._first,this._second,this._colorCss,t)})}end(){super.end(),this._preview.acapDispose()}}class pu extends z{constructor(){super(),Be(this)}async execute(e){await Ze(e,async()=>{const t=ee(),i=Et(t),n=new I(d.t("jig.markup.highlight.firstCorner")),r=await e.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=new I(d.t("jig.markup.highlight.secondCorner"));a.useBasePoint=!0,a.jig=new Xg(e.view,o,t);const l=await e.view.editor.getPoint(a);if(l.status!==b.OK)return;const c=l.value,p={...Fe("highlight",e.view,e),type:"highlight",style:{color:i,lineWeight:Pe()},geometry:{type:"highlight",corner1:{x:o.x,y:o.y},corner2:{x:c.x,y:c.y}}};ze(e.view,p)})}}const qg=["text","line","arrow","cloud","rect","circle","highlight","callout","stamp","symbol"];function si(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function Ee(s){return si(s)&&typeof s.x=="number"&&typeof s.y=="number"}function mu(s){return!(!si(s)||!Ee(s.tip)||!Ee(s.anchor)||s.text!==void 0&&typeof s.text!="string")}function Jg(s){return typeof s=="string"&&$o.includes(s)}function Qg(s){return typeof s=="string"&&qg.includes(s)}function ef(s){if(!si(s)||typeof s.id!="string"||!Qg(s.type)||!si(s.style)||typeof s.style.color!="string"||!si(s.geometry)||s.geometry.type!==s.type||!Jg(s.status))return;const e=s.geometry;switch(s.type){case"text":if(!Ee(e.position))return;break;case"line":case"arrow":if(!Ee(e.start)||!Ee(e.end))return;break;case"cloud":case"rect":case"highlight":if(!Ee(e.corner1)||!Ee(e.corner2)||(s.type==="cloud"||s.type==="rect")&&e.callout!==void 0&&!mu(e.callout))return;break;case"circle":if(!Ee(e.center)||typeof e.radius!="number"||!(e.radius>0)||e.callout!==void 0&&!mu(e.callout))return;break;case"callout":if(!Ee(e.tip)||!Ee(e.anchor))return;break;case"stamp":if(!Ee(e.position)||typeof e.stampId!="string")return;break;case"symbol":if(!Ee(e.position)||typeof e.symbolId!="string")return;break;default:return}return{id:s.id,type:s.type,layoutId:typeof s.layoutId=="string"?s.layoutId:void 0,style:{color:s.style.color,lineWeight:typeof s.style.lineWeight=="number"?s.style.lineWeight:void 0,fontSize:typeof s.style.fontSize=="number"&&s.style.fontSize>0?s.style.fontSize:void 0},text:typeof s.text=="string"?s.text:void 0,comment:typeof s.comment=="string"?s.comment:"",status:s.status,author:typeof s.author=="string"?s.author:"",createdAt:typeof s.createdAt=="string"?s.createdAt:new Date().toISOString(),updatedAt:typeof s.updatedAt=="string"?s.updatedAt:new Date().toISOString(),geometry:s.geometry}}function yu(s){let e;try{e=JSON.parse(s)}catch{throw new Error("Invalid markup sidecar: not JSON")}if(!si(e)||e.version!==1)throw new Error("Invalid markup sidecar: expected version 1");if(!Array.isArray(e.markups))throw new Error("Invalid markup sidecar: markups must be an array");const t=[];for(const i of e.markups){const n=ef(i);n&&t.push(n)}return{version:1,drawingName:typeof e.drawingName=="string"?e.drawingName:void 0,markups:t}}function gu(s){return`${JSON.stringify(s,null,2)}
525
- `}function fu(s){return s?`${s.replace(/\.(dwg|dxf)$/i,"")}.markup.json`:"drawing.markup.json"}function tf(s,e){if(typeof document>"u")return;const t=new Blob([e],{type:"application/json;charset=utf-8"}),i=URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download=s,n.click(),URL.revokeObjectURL(i)}function nf(){return new Promise(s=>{if(typeof document>"u"){s(void 0);return}const e=document.createElement("input");e.type="file",e.accept=".json,application/json";let t=!1;const i=n=>{t||(t=!0,s(n))};e.addEventListener("cancel",()=>i()),e.onchange=async()=>{var r;const n=(r=e.files)==null?void 0:r[0];if(!n){i();return}i(await n.text())},e.click()})}class bu extends z{constructor(){super(),this.mode=F.Read,this.recordsUndoStack=!1}async execute(e){const t=U();t.drawingName||(t.drawingName=e.doc.fileName||e.doc.docTitle);const i=gu(t.toSidecar());tf(fu(t.drawingName),i),t.markClean()}}class wu extends z{constructor(){super(),this.mode=F.Review,this.recordsUndoStack=!1}async execute(e){new le(d.t("jig.markup.import.chooseFile"));const t=await nf();if(t==null)return;let i;try{i=yu(t)}catch(r){console.error(r);return}const n=U();ve(e.view,"Import Markups",()=>{n.replaceAll(i.markups,i.drawingName),it().republishAll(e.view)})}}class sf extends G{constructor(e,t,i,n){super(e),this._view=e,this._p1=t,this._p2=t,this._color=i,this._ht=this._view.htmlTransientManager,this._badgeId=`live-markup-line-${Date.now()}`,this._badge=new M.AcTrHtmlBadge({id:this._badgeId,color:i,text:n,worldPosition:t,layer:ae,layoutId:this._view.activeLayoutBtrId}),this._badge.object.visible=!1,this._ht.add(this._badge),this._preview=new Oe(this._view,`live-markup-line-stroke-${Date.now()}`,ae)}get entity(){return null}update(e){this._p2=e,this._color=ee(),this._badge.setColor(this._color);const t=je(Pe());this._preview.acapSetDraw((i,n)=>{ft(i,n,this._p1,this._p2,this._color,t)}),this._badge.setPosition({x:(this._p1.x+e.x)/2,y:(this._p1.y+e.y)/2}),this._badge.object.visible=!0}end(){super.end(),this._preview.acapDispose(),this._ht.remove(this._badgeId)}}class vu extends z{constructor(){super(),Be(this)}async execute(e){await Ze(e,async()=>{const t=ee(),i=new I(d.t("jig.markup.line.firstPoint")),n=await e.view.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new I(d.t("jig.markup.line.secondPoint"));o.useBasePoint=!0,o.jig=new sf(e.view,r,t,"Line");const a=await e.view.editor.getPoint(o);if(a.status!==b.OK)return;const l=a.value,h={...Fe("line",e.view,e),type:"line",style:{color:Et(t),lineWeight:Pe()},geometry:{type:"line",start:{x:r.x,y:r.y},end:{x:l.x,y:l.y}}};ze(e.view,h)})}}class rf extends G{constructor(e,t,i){super(e),this._view=e,this._first=t,this._second=t,this._color=i,this._preview=new Oe(this._view,`live-markup-rect-${Date.now()}`,ae)}get entity(){return null}update(e){this._second=e,this._color=ee();const t=je(Pe()),i=ao(this._first,this._second);this._preview.acapSetDraw((n,r)=>{Bi(n,r,i,this._color,t,{closed:!0})})}end(){super.end(),this._preview.acapDispose()}}class ku extends z{constructor(){super(),Be(this)}async execute(e){await Ze(e,async()=>{const t=ee(),i=await ys(e,"jig.markup.rect.firstCorner");if(!i)return;const n=new I(d.t("jig.markup.rect.secondCorner"));n.useBasePoint=!0,n.jig=new rf(e.view,i,t);const r=await e.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=await gs(e,{kind:"rect",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y}}),c={...Fe("rect",e.view,e,{text:a==null?void 0:a.text}),type:"rect",geometry:{type:"rect",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y},callout:a}};ze(e.view,c)})}}const xu=new Set(["approved","rejected","revised","for-review","custom"]);class Su extends z{constructor(){super(),Be(this)}async execute(e){await Ze(e,async()=>{const t=new le(d.t("jig.markup.stamp.kind"));t.allowEmpty=!1,t.allowSpaces=!1,t.defaultValue="approved",t.useDefaultValue=!0;const i=await e.view.editor.getString(t);if(i.status!==b.OK)return;const n=(i.stringResult??"approved").trim().toLowerCase();let r;(n==="custom"||!xu.has(n))&&(r=await yo(e,"jig.markup.stamp.imageUrl",""));const o=await yo(e,"jig.markup.stamp.caption",""),a=new I(d.t("jig.markup.stamp.point")),l=await e.view.editor.getPoint(a);if(l.status!==b.OK)return;const c=l.value;if(n!=="custom"&&!xu.has(n)){const f={...Fe("symbol",e.view,e,{text:o||void 0}),type:"symbol",style:us(),geometry:{type:"symbol",position:{x:c.x,y:c.y},symbolId:n,imageUrl:r||void 0}};ze(e.view,f);return}const m={...Fe("stamp",e.view,e,{text:o||void 0}),type:"stamp",style:us(),geometry:{type:"stamp",position:{x:c.x,y:c.y},stampId:n,imageUrl:r||void 0}};ze(e.view,m)})}}class Pu extends z{constructor(){super(),Be(this)}async execute(e){await Ze(e,async()=>{const t=new I(d.t("jig.markup.text.point")),i=await e.view.editor.getPoint(t);if(i.status!==b.OK)return;const n=i.value,r=e.view,o=`live-markup-text-${Date.now()}`,a=new M.AcTrHtmlBadge({id:o,color:ee(),text:"",fontSize:tt(),worldPosition:n,layer:ae,layoutId:r.activeLayoutBtrId});r.htmlTransientManager.add(a),r.isHtmlDirty=!0;let l="Note";try{l=await hs({textElement:a.element,element:a.element},{multiline:!1})||"Note"}finally{r.htmlTransientManager.remove(o),r.isHtmlDirty=!0}const h={...Fe("text",r,e,{text:l}),type:"text",geometry:{type:"text",position:{x:n.x,y:n.y}}};ze(e.view,h)})}}let fo=!0;function of(){return fo}function Au(s,e){fo=e,s.htmlTransientManager.setVisible(e,an),s.htmlTransientManager.setVisible(e,ae),s.isHtmlDirty=!0}class Cu extends z{constructor(){super(),this.mode=F.Review,this.recordsUndoStack=!1}async execute(e){const t=e.view;Au(t,!fo)}}class bo extends Wt{constructor(e,t,i,n=1,r=!1){super(e,t,Math.max(0,n)),this._basePoint=new u.AcGePoint3d(i),this._fitMode=r}update(e){const t=new u.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z);if(this.batchPreview.useBatchPreview&&this.copyCount>1){this.batchPreview.updatePlacements(this._view,t,this._fitMode);return}super.update(e)}buildTransforms(e){const t=new u.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z);return(this.previewEntries.length>0?this.previewEntries:[{entity:{objectId:""},copyFactor:1}]).map(n=>{const r=Nn(t,n.copyFactor,this.copyCount,this._fitMode);return{objectId:n.entity.objectId,matrix:new u.AcGeMatrix3d().makeTranslation(r.x,r.y,r.z)}})}}const en=class en extends z{constructor(){super(),this.mode=F.Write}addKeyword(e,t){e.keywords.add(d.t(`jig.copy.keywords.${t}.display`),d.t(`jig.copy.keywords.${t}.global`),d.t(`jig.copy.keywords.${t}.local`))}computeDisplacement(e,t){return new u.AcGePoint3d(t).sub(e)}scaleDisplacement(e,t,i,n){return Nn(e,t,i,n)}appendCopies(e,t){t.length!==0&&(e.doc.database.tables.blockTable.modelSpace.appendEntity(t),e.view.addEntity(t))}buildCopies(e,t,i=1,n=!1){const r=[];for(let o=1;o<=i;o++){const a=e.map(h=>h.clone()).filter(h=>!!h),l=this.scaleDisplacement(t,o,i,n),c=new u.AcGeMatrix3d().makeTranslation(l.x,l.y,l.z);a.forEach(h=>h.transformBy(c)),r.push(...a)}return r}async promptCopyMode(e){const t=new ne(d.t("jig.copy.modePrompt"));t.allowNone=!0,this.addKeyword(t,"single"),this.addKeyword(t,"multiple");const i=t.keywords.findByGlobalName(e);i&&(t.keywords.default=i);const n=await k.instance.editor.getKeywords(t);if(n.status===b.None)return e;if(n.status!==b.OK)return;const r=n.stringResult??"";return r==="Single"||r==="Multiple"?r:e}async promptArrayPlacement(e,t,i){const n=new kr(d.t("jig.copy.arrayItemCount"),2);n.lowerLimit=2,n.allowNegative=!1,n.allowZero=!1;const r=await k.instance.editor.getInteger(n);if(r.status!==b.OK)return;const o=r.value??2,a=Math.max(1,o-1);for(;;){const l=new I(d.t("jig.copy.arraySecondPointOrFit"));this.addKeyword(l,"fit"),l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=i,l.jig=new bo(e.view,t,i,a);const c=await k.instance.editor.getPoint(l);if(c.status===b.OK)return{copyCount:a,endPoint:new u.AcGePoint3d(c.value),fitMode:!1};if(c.status===b.Keyword&&c.stringResult==="Fit"){const h=new I(d.t("jig.copy.arrayFitSecondPoint"));h.useBasePoint=!0,h.useDashedLine=!0,h.basePoint=i,h.jig=new bo(e.view,t,i,a,!0);const p=await k.instance.editor.getPoint(h);if(p.status===b.OK)return{copyCount:a,endPoint:new u.AcGePoint3d(p.value),fitMode:!0}}return}}async executeCopyLoop(e,t,i,n,r=!1){for(;;){const o=new I(d.t(r?"jig.copy.displacementOrArray":"jig.copy.secondPointOrArray"));this.addKeyword(o,"array"),o.useBasePoint=!0,o.useDashedLine=!0,o.basePoint=i,o.allowNone=!0,o.jig=new bo(e.view,t,i);const a=await k.instance.editor.getPoint(o);if(a.status===b.OK){const l=this.buildCopies(t,this.computeDisplacement(i,a.value));if(this.appendCopies(e,l),n==="Single")return;continue}if(a.status===b.Keyword&&a.stringResult==="Array"){const l=await this.promptArrayPlacement(e,t,i);if(!l)continue;const c=this.buildCopies(t,this.computeDisplacement(i,l.endPoint),l.copyCount,l.fitMode);if(this.appendCopies(e,c),n==="Single")return;continue}return}}async execute(e){const t=e.view.selectionSet,i=await Rn(e,{promptKey:"copy"});if(!i)return;const n=i.entities.map(l=>e.doc.database.openEntityForRead(l.objectId)).filter(l=>!!l);if(n.length===0){t.clear();return}let r=en._defaultMode,o,a=!1;for(;!o;){const l=new I(d.t("jig.copy.basePointOrOptions"));l.allowNone=!0,this.addKeyword(l,"displacement"),this.addKeyword(l,"mode"),r!=="Multiple"&&this.addKeyword(l,"multiple");const c=await k.instance.editor.getPoint(l);if(c.status===b.OK){o=new u.AcGePoint3d(c.value);break}if(c.status===b.None){o=new u.AcGePoint3d(0,0,0),a=!0;break}if(c.status!==b.Keyword){t.clear();return}const h=c.stringResult??"";if(h==="Displacement"){o=new u.AcGePoint3d(0,0,0),a=!0;break}if(h==="Multiple"){r="Multiple";continue}if(h!=="Mode"){t.clear();return}const p=await this.promptCopyMode(r);if(!p){t.clear();return}r=p,en._defaultMode=p}await this.executeCopyLoop(e,n,o,r,a),t.clear()}};en._defaultMode="Multiple";let ws=en;class _u extends z{async execute(e){const t=e.view.selectionSet,i=await ic(e,"erase");i&&(e.doc.entityService.eraseEntities(i),t.clear())}}class Eu extends z{async execute(e){const t=e.view.selectionSet;let i=t.count>0?t.ids:[];if(i.length===0){const r=new xt(d.sysCmdPrompt("hideobjects")),o=await k.instance.editor.getSelection(r);if(o.status!==b.OK||!o.value||o.value.count===0)return;i=o.value.ids}const n=Dh(e,i);n>0&&this.showMessage(`${n} ${d.t("jig.hideobjects.hidden")}`,"success")}}class Lu extends Wt{constructor(e,t,i){super(e,t),this._basePoint=new u.AcGePoint3d(i)}buildTransforms(e){const t=new u.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z),i=new u.AcGeMatrix3d().makeTranslation(t.x,t.y,t.z);return(this.previewEntries.length>0?this.previewEntries:[{entity:{objectId:""},copyFactor:1}]).map(r=>({objectId:r.entity.objectId,matrix:i}))}}class Tu extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.view.selectionSet,i=await Rn(e,{promptKey:"move"});if(!i)return;const{entities:n}=i;let r,o;const a=m=>{m.keywords.add(d.t("jig.move.keywords.displacement.display"),d.t("jig.move.keywords.displacement.global"),d.t("jig.move.keywords.displacement.local"))};class l{constructor(g){this.machine=g}buildPrompt(){const g=new I(d.t("jig.move.basePointOrDisplacement"));return a(g),g.allowNone=!0,g}async handleResult(g){return g.status===b.OK?(r=new u.AcGePoint3d(g.value),this.machine.setState(new c(this.machine)),"continue"):g.status===b.None?(this.machine.setState(new h),"continue"):g.status===b.Keyword&&g.stringResult==="Displacement"?(this.machine.setState(new h),"continue"):"finish"}}class c{constructor(g){this.machine=g}buildPrompt(){const g=new I(d.t("jig.move.secondPointOrDisplacement"));return a(g),r&&(g.useBasePoint=!0,g.useDashedLine=!0,g.basePoint=r,g.jig=new Lu(e.view,n,r)),g.allowNone=!0,g}async handleResult(g){if(g.status===b.OK&&r){const f=new u.AcGePoint3d(g.value);return o=new u.AcGePoint3d(f).sub(r),"finish"}return g.status===b.Keyword&&g.stringResult==="Displacement"?(this.machine.setState(new h),"continue"):"finish"}}class h{buildPrompt(){const g=new I(d.t("jig.move.displacement"));return g.useBasePoint=!0,g.useDashedLine=!0,g.basePoint=new u.AcGePoint3d(0,0,0),g.jig=new Lu(e.view,n,g.basePoint),g.allowNone=!0,g}async handleResult(g){return g.status===b.OK&&(o=new u.AcGePoint3d(g.value)),"finish"}}const p=new We;if(p.setState(new l(p)),await p.run(m=>k.instance.editor.getPoint(m)),!o){t.clear();return}e.doc.entityService.translateEntities(n,o),t.clear()}}function af(s){return s instanceof u.AcDbCurve}function Iu(s,e,t){try{const i=s.getOffsetSideAtPoint(t),n=s.getOffsetCurves(e*i);return n.forEach(r=>Ir.copyDisplayTraits(s,r)),n}catch{return[]}}class lf extends G{constructor(e,t,i){super(e),this._previewCurves=[],this._renderedIds=[],this._view=e,this._curve=t,this._distance=i}update(e){this.clearRendered(),this._previewCurves=Iu(this._curve,this._distance,e)}render(){this._previewCurves.length!==0&&(this._view.addTransientEntity(this._previewCurves),this._renderedIds=this._previewCurves.map(e=>e.objectId))}end(){this.clearRendered()}clearRendered(){this._renderedIds.forEach(e=>this._view.removeTransientEntity(e)),this._renderedIds=[]}}class Vi extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=(h,p="info")=>{this.showMessage(h,p)},i=e.doc.database.tables.blockTable;let n,r;class o{constructor(p){this.machine=p}buildPrompt(){const p=Vi._lastDistance,m=new be(d.t("jig.offset.distance"));return m.useBasePoint=!1,m.useDashedLine=!0,m.allowZero=!1,m.allowNegative=!1,p!=null&&(m.defaultValue=p,m.useDefaultValue=!0,m.allowNone=!0),m}handleResult(p){return!(p instanceof Se)||p.status!==b.OK||p.value==null?"finish":!Number.isFinite(p.value)||u.AcGeTol.isNonPositive(p.value)?(t(d.t("jig.offset.invalidDistance"),"warning"),"finish"):(n=p.value,Vi._lastDistance=p.value,this.machine.setState(new a(this.machine)),"continue")}}class a{constructor(p){this.machine=p}buildPrompt(){const p=new He(d.t("jig.offset.selectObject"));return p.allowNone=!0,p.allowObjectOnLockedLayer=!0,p.setRejectMessage(d.t("jig.offset.invalidSelection")),p}handleResult(p){if(!(p instanceof On)||p.status===b.None||p.status!==b.OK||!p.objectId)return"finish";const m=e.doc.database.openEntityForRead(p.objectId);return af(m)?(r=m,this.machine.setState(new l(this.machine)),"continue"):(t(d.t("jig.offset.invalidSelection"),"warning"),"continue")}}class l{constructor(p){this.machine=p}buildPrompt(){const p=new I(d.t("jig.offset.sidePoint"));if(p.allowNone=!0,p.disableOSnap=!0,r&&n!=null){const m=new lf(e.view,r,n);m.update({...e.view.curPos,z:0}),m.render(),p.jig=m}return p}handleResult(p){if(!(p instanceof Bn)||p.status!==b.OK||!p.value||!r||n==null)return"finish";const m=Iu(r,n,new u.AcGePoint3d(p.value));return m.length===0?t(d.t("jig.offset.offsetFailed"),"warning"):i.modelSpace.appendEntity(m),r=void 0,this.machine.setState(new a(this.machine)),"continue"}}const c=new We;c.setState(new o(c)),await c.run(h=>h instanceof be?k.instance.editor.getDistance(h):h instanceof He?k.instance.editor.getEntity(h):k.instance.editor.getPoint(h))}}class vs extends Vl{}class Mu extends Wt{constructor(e,t,i,n=0){super(e,t),this._lastAngleRad=0,this._basePoint=new u.AcGePoint3d(i),this._referenceAngleDeg=n}get entity(){return this.previewEntities[0]??null}update(e){const t=(e-this._referenceAngleDeg)*Math.PI/180;if(this.batchPreview.useBatchPreview){if(u.AcGeTol.equalToZero(t-this._lastAngleRad))return;this.batchPreview.updateMatrix(this._view,$t(this._basePoint,t)),this._lastAngleRad=t;return}this._lastAngleRad=t,super.update(e)}buildTransforms(e){const t=(e-this._referenceAngleDeg)*Math.PI/180,i=$t(this._basePoint,t);return this.previewEntries.map(n=>({objectId:n.entity.objectId,matrix:i}))}}const Oo=class Oo extends z{constructor(){super(),this.mode=F.Write}addKeyword(e,t){e.keywords.add(d.t(`jig.rotate.keywords.${t}.display`),d.t(`jig.rotate.keywords.${t}.global`),d.t(`jig.rotate.keywords.${t}.local`))}warnInvalidInput(e){this.notify(d.t(`jig.rotate.invalid.${e}`),"warning")}computeAngleDeg(e,t){const i=t.x-e.x,n=t.y-e.y;if(u.AcGeTol.isPositive(Math.hypot(i,n)))return Math.atan2(n,i)*180/Math.PI}async promptReferenceAngle(e,t,i){for(;;){const n=new xe(d.t("jig.rotate.referenceAngleOrPoints"));this.addKeyword(n,"points"),n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=i,n.allowNegative=!0,n.allowZero=!0,n.useDefaultValue=!0,n.defaultValue=0,n.jig=new vs(e.view,t);const r=await k.instance.editor.getAngle(n);if(r.status===b.OK)return r.value??0;if(r.status===b.Keyword&&r.stringResult==="Points"){const o=new I(d.t("jig.rotate.firstReferencePoint"));o.jig=new vs(e.view,t);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)return;const l=new I(d.t("jig.rotate.secondReferencePoint"));l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(a.value),l.jig=new vs(e.view,t);const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK)return;const h=this.computeAngleDeg(a.value,c.value);if(h==null){this.warnInvalidInput("referencePoints");continue}return h}return}}async promptRotationAngle(e,t,i){let n=!1;for(;;){const r=new xe(d.t("jig.rotate.rotationAngleOrOptions"));this.addKeyword(r,"copy"),this.addKeyword(r,"reference"),r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=i,r.allowNegative=!0,r.allowZero=!0,r.allowNone=!0,r.jig=new Mu(e.view,t,i);const o=await k.instance.editor.getAngle(r);if(o.status===b.OK)return{copyMode:n,angleRad:(o.value??0)*Math.PI/180};if(o.status!==b.Keyword)return;const a=o.stringResult??"";if(a==="Copy"){n=!0;continue}if(a!=="Reference")return;const l=await this.promptReferenceAngle(e,t,i);if(l==null)return;const c=new xe(d.t("jig.rotate.newAngle"));c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=i,c.allowNegative=!0,c.allowZero=!0,c.allowNone=!0,c.jig=new Mu(e.view,t,i,l);const h=await k.instance.editor.getAngle(c);return h.status!==b.OK?void 0:{copyMode:n,angleRad:((h.value??0)-l)*Math.PI/180}}}async execute(e){const t=e.view.selectionSet,i=await Rn(e,{promptKey:"rotate"});if(!i)return;const{entities:n}=i,r=new I(d.t("jig.rotate.basePoint"));r.jig=new vs(e.view,n),r.allowNone=!0;const o=await k.instance.editor.getPoint(r);if(o.status!==b.OK){t.clear();return}const a=new u.AcGePoint3d(o.value),l=await this.promptRotationAngle(e,n,a);if(!l){t.clear();return}const c=$t(a,l.angleRad),h=e.doc.entityService;l.copyMode?h.cloneAndTransform(n,c):h.transformEntities(n,c),t.clear()}};Oo.createRotationMatrix=$t;let ks=Oo;class Du extends z{async execute(e){const t=Oh(e);if(t>0){this.showMessage(`${t} ${d.t("jig.hideobjects.restored")}`,"success");return}this.showMessage(d.t("jig.hideobjects.nothingToRestore"),"info")}}const Le=class Le{constructor(e){this.disposed=!1,Le.ensureStyles();const t=e.host??document.body,i=e.titleId??`ml-ui-dialog-title-${Le.nextTitleId++}`;this.closeOnEscape=e.closeOnEscape??!0,this.previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null,this.backdrop=document.createElement("div"),this.backdrop.className="ml-ui-dialog-backdrop",gr(e.theme??fr(t),this.backdrop),(e.closeOnBackdrop??!0)&&this.backdrop.addEventListener("mousedown",o=>{o.target===this.backdrop&&this.close()}),this.dialog=document.createElement("div"),this.dialog.className=["ml-ui-dialog",e.dialogClassName].filter(Boolean).join(" "),this.dialog.setAttribute("role","dialog"),this.dialog.setAttribute("aria-modal","true"),this.dialog.setAttribute("aria-labelledby",i),this.dialog.tabIndex=-1,this.dialog.addEventListener("mousedown",o=>o.stopPropagation());const n=document.createElement("div");n.className="ml-ui-dialog-header",this.titleEl=document.createElement("div"),this.titleEl.id=i,this.titleEl.className="ml-ui-dialog-title",this.titleEl.textContent=e.title;const r=document.createElement("button");r.type="button",r.className="ml-ui-dialog-close",r.setAttribute("aria-label",e.closeLabel??"Close"),r.textContent="×",r.addEventListener("click",()=>this.close()),n.appendChild(this.titleEl),n.appendChild(r),this.bodyEl=document.createElement("div"),this.bodyEl.className="ml-ui-dialog-body",this.footerEl=document.createElement("div"),this.footerEl.className="ml-ui-dialog-footer",this.dialog.appendChild(n),this.dialog.appendChild(this.bodyEl),this.dialog.appendChild(this.footerEl),this.backdrop.appendChild(this.dialog),t.appendChild(this.backdrop),this.onKeyDown=o=>{if(o.key==="Escape"){if(!this.closeOnEscape)return;o.preventDefault(),this.close();return}o.key==="Tab"&&this.trapFocus(o)},window.addEventListener("keydown",this.onKeyDown)}show(){return this.openPromise||(this.openPromise=new Promise(e=>{this.resolve=e})),this.openPromise}close(){var e,t;this.disposed||(this.disposed=!0,window.removeEventListener("keydown",this.onKeyDown),this.backdrop.parentNode&&this.backdrop.parentNode.removeChild(this.backdrop),(e=this.previouslyFocused)==null||e.focus(),(t=this.resolve)==null||t.call(this),this.resolve=void 0)}focusAfterOpen(e){queueMicrotask(()=>e.focus())}trapFocus(e){const t=this.getFocusableElements();if(t.length===0){e.preventDefault(),this.dialog.focus();return}const i=t[0],n=t[t.length-1],r=document.activeElement;if(e.shiftKey){(r===i||!this.dialog.contains(r))&&(e.preventDefault(),n.focus());return}(r===n||!this.dialog.contains(r))&&(e.preventDefault(),i.focus())}getFocusableElements(){const e=["a[href]","button:not([disabled])","textarea:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(this.dialog.querySelectorAll(e)).filter(t=>!t.hasAttribute("disabled")&&t.getAttribute("aria-hidden")!=="true"&&t.tabIndex>=0&&t.offsetParent!==null)}static ensureStyles(){if(Le.stylesInjected)return;if(document.getElementById(Le.styleId)){Le.stylesInjected=!0;return}const e=document.createElement("style");e.id=Le.styleId,e.textContent=`
574
+ `,document.head.appendChild(e)}formatNumber(e,t){var n;const i=(n=k.instance.curDocument)==null?void 0:n.database;if(!i)switch(t){case"angle":return e.toFixed(2);case"distance":case"point":default:return e.toFixed(3)}switch(t){case"angle":return i.formatter.formatAngle(e*Math.PI/180,{applyAngbaseAngdir:!1});case"distance":case"point":default:return i.formatter.formatLength(e)}}hasKeywords(e){var i;return(((i=e.keywords)==null?void 0:i.toArray())??[]).length>0}buildKeywordOptions(e){var n;const t=new ne(e.message);return t.appendKeywordsToMessage=e.appendKeywordsToMessage,t.valueDefaultDisplayText=e.getDefaultValueDisplayText(),(((n=e.keywords)==null?void 0:n.toArray())??[]).forEach(r=>{const o=t.keywords.add(r.displayName,r.globalName,r.localName,r.enabled,r.visible);e.keywords.default===r&&(t.keywords.default=o)}),t}copyKeywords(e,t){var n;t.appendKeywordsToMessage=e.appendKeywordsToMessage,(((n=e.keywords)==null?void 0:n.toArray())??[]).forEach(r=>{const o=t.keywords.add(r.displayName,r.globalName,r.localName,r.enabled,r.visible);e.keywords.default===r&&(t.keywords.default=o)})}getEntityById(e){return k.instance.curDocument.database.tables.blockTable.getEntityById(e)}isEntityOnLockedLayer(e){var i;const t=e.layer;return t?!!((i=k.instance.curDocument.database.tables.layerTable.getAt(t))!=null&&i.isLocked):!1}isEntityClassAllowed(e,t){var r;const i=new Set;e.type&&i.add(e.type);const n=(r=e.constructor)==null?void 0:r.name;n&&i.add(n);for(const o of i)if(t.isClassAllowed(o))return!0;return!1}startKeywordSession(e,t){if(!this.hasKeywords(e))return;const i=this.buildKeywordOptions(e);return{promise:this._commandLine.getKeywords(i,t),cancel:()=>this._commandLine.cancelActiveSession()}}startPromptInputSession(e,t,i,n){const r=this.buildKeywordOptions(e),o="allowNone"in e?e.allowNone:!1;return{promise:this._commandLine.getPromptInput(r,a=>this.parseCommandLineInput(a,t,i,e),{mode:this.resolvePromptInputMode(t),allowNone:o,allowTyping:n}),cancel:()=>this._commandLine.cancelActiveSession()}}resolvePromptInputMode(e){return e instanceof Vn?"string":"geometric"}resolvePointInputContext(e){const t=this.resolvePromptDefaults(e);return{referencePoint:t.useBasePoint&&t.basePoint?t.basePoint:this.lastPoint??void 0,cursorPoint:this.view.screenToWorld(this.view.viewportToCanvas(this.view.curMousePos))}}parseCommandLineInput(e,t,i,n){const r=e.trim();if(!r)return null;const o=t instanceof Si||i===2?this.resolvePointInputContext(n):void 0;return t.parseCommandLine(r,o)}isPromptKeyword(e){return e instanceof Ai}mapPromptError(e,t){if(t.none&&this.isPromptNone(e))return t.none();if(t.cancel&&this.isPromptCancelled(e))return t.cancel();if(t.keyword&&this.isPromptKeyword(e))return t.keyword(e.keyword)}withKeywordResult(e,t){return e.stringResult=t,e}mapPromptErrorToResult(e,t,i){const n=(i==null?void 0:i.none)??!0,r=(i==null?void 0:i.cancel)??!0,o=(i==null?void 0:i.keyword)??!0;return this.mapPromptError(e,{none:n?()=>t(b.None):void 0,cancel:r?()=>t(b.Cancel):void 0,keyword:o?a=>this.withKeywordResult(t(b.Keyword),a):void 0})}async executePrompt(e,t,i,n){try{const r=await e();return t(r)}catch(r){const o=this.mapPromptErrorToResult(r,i,n);if(o)return o;throw r}}resolvePromptDefaultValue(e){return"useDefaultValue"in e&&"defaultValue"in e&&e.useDefaultValue?{useDefaultValue:!0,defaultValue:e.defaultValue}:{useDefaultValue:!1}}async getPoint(e){return this.executePrompt(()=>this.getPointInternal(e),t=>new Rn(b.OK,t),t=>new Rn(t))}getNumberTyped(e,t){const i=()=>({value:0,raw:{x:""}});return this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:i})}resolveDistanceBasePoint(e){if(e.useBasePoint&&e.basePoint)return{x:e.basePoint.x,y:e.basePoint.y}}createDistanceDynamicValue(e){return t=>{const i=t.x-e.x,n=t.y-e.y,r=Math.sqrt(i*i+n*n);return{value:r,raw:{x:this.formatNumber(r,"distance")}}}}async getDistanceTwoPoint(e,t){let i,n;const r=o=>i?this.createDistanceDynamicValue(i)(o):{value:0,raw:{x:""}};return await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:r,onFloatingInputCreated:o=>{n=o},onCommit:(o,a)=>i?!0:a?(i={x:a.x,y:a.y},n==null||n.setBasePoint(i,{showBaseLineOnly:!e.useDashedLine}),!1):!0})}async getDistance(e){const t=new cy(e),i=this.tryGetScriptedNumber(t,e);if(i!=null)return new Pe(b.OK,i);const n=this.resolveDistanceBasePoint(e);return this.executePrompt(async()=>n?await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:this.createDistanceDynamicValue(n)}):await this.getDistanceTwoPoint(e,t),r=>new Pe(b.OK,r),r=>new Pe(r))}async getAngle(e){const t=new ly(e),i=this.tryGetScriptedNumber(t,e);if(i!=null)return new Pe(b.OK,i);const n=e.useBasePoint&&e.basePoint?e.basePoint:this.lastPoint;if(!n)return this.executePrompt(()=>this.getNumberTyped(e,t),o=>new Pe(b.OK,o),o=>new Pe(o));const r=o=>{const a=o.x-n.x,l=o.y-n.y,c=Math.atan2(l,a),h=e.baseAngle*Math.PI/180;let p=c-h;for(;p<=-Math.PI;)p+=Math.PI*2;for(;p>Math.PI;)p-=Math.PI*2;const m=p*180/Math.PI;return{value:m,raw:{x:this.formatNumber(m,"angle")}}};return this.executePrompt(()=>this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:r}),o=>new Pe(b.OK,o),o=>new Pe(o))}async getDouble(e){const t=new dy(e),i=this.tryGetScriptedNumber(t,e);return i!=null?new Pe(b.OK,i):this.executePrompt(()=>this.getNumberTyped(e,t),n=>new Pe(b.OK,n),n=>new Pe(n))}async getInteger(e){const t=this.tryGetScriptedNumber(new $l(e),e);return t!=null?new Nn(b.OK,t):this.executePrompt(()=>this.getNumberTyped(e,new $l(e)),i=>new Nn(b.OK,i),i=>new Nn(i))}async getString(e){const t=this.tryGetScriptedValue(new Vn(e),e);return t!=null?new Fe(b.OK,t):this.executePrompt(async()=>{const i=()=>({value:"",raw:{x:""}}),n=new Vn(e);return await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:n,getDynamicValue:i})},i=>new Fe(b.OK,i),i=>new Fe(i))}async getKeywords(e){return this.executePrompt(async()=>{const t=this.tryGetScriptedValue(new Tr(e),e);return t??new Promise((i,n)=>{const r=o=>{this._activeRejector===r&&(this._activeRejector=null),this._commandLine.cancelActiveSession(),n(o??new Error("cancelled"))};this._activeRejector=r,this._commandLine.getKeywords(e,!0).then(o=>{if(this._activeRejector===r&&(this._activeRejector=null),!o){n(e.allowNone?new Ci:new Error("cancelled"));return}i(o)},o=>{this._activeRejector===r&&(this._activeRejector=null),n(o)})})},t=>new Fe(b.OK,t),t=>new Fe(t),{keyword:!1})}async getSelection(e){return this.executePrompt(()=>new Promise((t,i)=>{this.active=!0,this.entitySelectionActive=!0;const n=this.startKeywordSession(e,!0);n||this._commandLine.setPrompt(e.message);const r=new Pi(this.view,{parent:this.view.canvas,message:e.message}),o=new Set;let a=null,l=null,c=null,h=null;const p=_=>{if(!a||!c||!l)return;const C=this.view.screenToWorld(this.view.viewportToCanvas({x:_.clientX,y:_.clientY})),O=this.view.viewportToCanvas({x:_.clientX,y:_.clientY}),B=this.view.worldToScreen(a),I=this.view.worldToScreen(C),N=Math.min(B.x,I.x),G=Math.min(B.y,I.y),$=Math.abs(B.x-I.x),X=Math.abs(B.y-I.y),Y=this.view.getSelectionMode(l,O),Q=this.view.getSelectionActionFromEvent(_,"add"),se=this.view.getSelectionPreviewStyle(Y,Q);Object.assign(c.style,{left:`${N}px`,top:`${G}px`,width:`${$}px`,height:`${X}px`,borderStyle:se.borderStyle,background:se.background}),c.style.setProperty("--line-color",se.lineColor)},m=()=>{h&&p(h)};let g=!1;const f=_=>{w(),i(_??new Error("cancelled"))},w=()=>{g||(g=!0,this.active=!1,this.entitySelectionActive=!1,this._activeRejector===f&&(this._activeRejector=null),r==null||r.dispose(),c==null||c.remove(),n==null||n.cancel(),this._commandLine.clear(),document.removeEventListener("keydown",v),this.view.canvas.removeEventListener("mousedown",S),this.view.canvas.removeEventListener("mousemove",P),this.view.canvas.removeEventListener("mouseup",A),this.view.canvas.removeEventListener("contextmenu",x),this.view.events.viewChanged.removeEventListener(m),this.view.events.viewResize.removeEventListener(m))};this._activeRejector=f,n==null||n.promise.then(_=>{if(!g){if(!_){f();return}f(new Ai(_))}});const v=_=>{if(_.key==="Escape"){f();return}_.key==="Enter"&&(w(),t([...o]))},x=_=>{this.shouldUseRightClickEnter()&&_.preventDefault()},S=_=>{if(_.button===2){this.shouldUseRightClickEnter()&&(_.preventDefault(),w(),t([...o]));return}_.button===0&&(l=this.view.viewportToCanvas({x:_.clientX,y:_.clientY}),a=this.view.screenToWorld(l),c=document.createElement("div"),c.className="ml-jig-preview-rect",this.view.container.appendChild(c))},P=_=>{_.buttons===1&&(!a||!c||!l||(h=_,p(_)))},A=_=>{if(_.button!==0||!a||!l)return;const C=this.view.screenToWorld(this.view.viewportToCanvas({x:_.clientX,y:_.clientY})),O=this.view.viewportToCanvas({x:_.clientX,y:_.clientY});c==null||c.remove(),c=null,h=null;const B=this.view.getSelectionActionFromEvent(_,"add");if(this.view.isSelectionClick(l,O)){const I=this.view.pick(C);I.length>0?this.view.applySelection([I[0].id],B):B==="replace"&&this.view.selectionSet.clear()}else{const I=new d.AcGeBox2d().expandByPoint(a).expandByPoint(C),N=this.view.getSelectionMode(l,O);this.view.selectByBoxWithMode(I,N,B)}o.clear();for(const I of this.view.selectionSet.ids)o.add(I);e.singleOnly&&B!=="remove"&&o.size>0&&(w(),t([...o])),a=null,l=null};document.addEventListener("keydown",v),this.view.canvas.addEventListener("mousedown",S),this.view.canvas.addEventListener("mousemove",P),this.view.canvas.addEventListener("mouseup",A),this.view.canvas.addEventListener("contextmenu",x),this.view.events.viewChanged.addEventListener(m),this.view.events.viewResize.addEventListener(m)}),t=>new xi(b.OK,new On(t)),t=>new xi(t),{none:!1})}async getEntity(e){let t;return this.executePrompt(()=>new Promise((i,n)=>{this.active=!0,this.entitySelectionActive=!0;const r=this.startKeywordSession(e,!0),o=new Pi(this.view,{parent:this.view.canvas,message:e.message});r||this._commandLine.setPrompt(e.message);let a=!1;const l=f=>{c(),n(f??new Error("cancelled"))},c=()=>{var f;a||(a=!0,this.active=!1,this.entitySelectionActive=!1,this._activeRejector===l&&(this._activeRejector=null),(f=e.jig)==null||f.end(),document.removeEventListener("keydown",m),this.view.canvas.removeEventListener("mousedown",h),this.view.canvas.removeEventListener("click",p),this.view.canvas.removeEventListener("contextmenu",g),o==null||o.dispose(),r==null||r.cancel(),this._commandLine.clear())};this._activeRejector=l,r==null||r.promise.then(f=>{if(!a){if(!f){l();return}l(new Ai(f))}});const h=f=>{if(f.button===2){this.shouldUseRightClickEnter()&&e.allowNone&&(f.preventDefault(),c(),i(null));return}},p=f=>{if(f.button!==0)return;const w=this.view.screenToWorld(this.view.viewportToCanvas({x:f.clientX,y:f.clientY})),v=this.view.pick(w,void 0,!0);if(v.length==0){this._commandLine.showMessage(e.rejectMessage,"warning");return}const x=this.getEntityById(v[0].id);if(!x){this._commandLine.showMessage(e.rejectMessage,"warning");return}if(!e.allowObjectOnLockedLayer&&this.isEntityOnLockedLayer(x)){this._commandLine.showMessage(e.rejectMessage,"warning");return}if(!this.isEntityClassAllowed(x,e)){this._commandLine.showMessage(e.rejectMessage,"warning");return}t={x:w.x,y:w.y,z:0},c(),i(v[0].id)},m=f=>{if(f.key==="Escape"){l();return}f.key==="Enter"&&e.allowNone&&(c(),i(null))},g=f=>{this.shouldUseRightClickEnter()&&f.preventDefault()};document.addEventListener("keydown",m),this.view.canvas.addEventListener("mousedown",h),this.view.canvas.addEventListener("click",p),this.view.canvas.addEventListener("contextmenu",g)}),i=>new zn(b.OK,i||void 0,t),i=>new zn(i),{none:!1})}async getBox(e){return this.executePrompt(async()=>{const t=e.firstCornerMessage||u.t("main.inputManager.firstCorner"),i=new T(t);this.copyKeywords(e,i),i.useDashedLine=e.useDashedLine,i.useBasePoint=e.useBasePoint,i.disableOSnap=e.disableOSnap,i.allowNone=e.allowNone;const n=await this.getPoint(i);if(n.status!==b.OK)return new jn(n.status,void 0,n.stringResult);const r=n.value,o=this.view.worldToScreen(r),a=document.createElement("div");a.className="ml-jig-preview-rect",this.view.container.appendChild(a);const l=()=>{a.remove()},c=f=>{const w=this.view.worldToScreen(f),v=Math.min(w.x,o.x),x=Math.min(w.y,o.y),S=Math.abs(w.x-o.x),P=Math.abs(w.y-o.y);Object.assign(a.style,{left:`${v}px`,top:`${x}px`,width:`${S}px`,height:`${P}px`})},h=e.secondCornerMessage||u.t("main.inputManager.secondCorner"),p=new T(h);this.copyKeywords(e,p),p.useDashedLine=e.useDashedLine,p.useBasePoint=e.useBasePoint,p.disableOSnap=e.disableOSnap;const m=await this.getPointInternal(p,l,c),g=new d.AcGeBox2d().expandByPoint(r).expandByPoint(m);return new jn(b.OK,g)},t=>t,t=>new jn(t))}async getPointInternal(e,t,i){const n=this.tryGetScriptedPoint(e);if(n!=null)return t==null||t(),Promise.resolve(n);const r=a=>({value:{x:a.x,y:a.y,z:0},raw:{x:this.formatNumber(a.x,"point"),y:this.formatNumber(a.y,"point")}}),o=new Si(e);return this.makeFloatingInputPromise({inputCount:2,promptOptions:e,disableOSnap:e.disableOSnap,cleanup:t,handler:o,getDynamicValue:r,drawPreview:i})}tryGetScriptedPoint(e){const t=this.dequeueScriptInput();if(t===void 0)return;const i=t.trim();if(!i&&e.allowNone)throw new Ci;const r=new Si(e).parseCommandLine(t,this.resolvePointInputContext(e));if(r!=null)return this.lastPoint={x:r.x,y:r.y},r;throw this.tryResolveScriptedKeyword(i,e),new Error(`Invalid point input '${t}'`)}tryResolveScriptedKeyword(e,t){if(!e||!(t!=null&&t.keywords))return;const i=t.keywords.findByName(e);if(i)throw new Ai(i.globalName)}tryGetScriptedValue(e,t){const i=this.dequeueScriptInput();if(i===void 0)return;const n=i.trim();if(!n&&t&&"allowNone"in t&&t.allowNone)throw new Ci;if(e instanceof Vn){this.tryResolveScriptedKeyword(n,t);const o=e.parse(i);if(o!=null)return o;throw new Error(`Invalid scripted input '${i}'`)}const r=this.parseCommandLineInput(i,e,e instanceof Si?2:1,t??new We(""));if(r!=null)return r;throw this.tryResolveScriptedKeyword(n,t),new Error(`Invalid scripted input '${i}'`)}tryGetScriptedNumber(e,t){return this.tryGetScriptedValue(e,t)}dequeueScriptInput(){if(this._scriptInputs.length)return this._scriptInputs.shift()}isPromptCancelled(e){return e instanceof Error&&e.message==="cancelled"}isPromptNone(e){return e instanceof Ci}getShortcutMenuMode(){const e=d.acdbHostApplicationServices().workingDatabase,t=d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.SHORTCUTMENU,e),i=Math.trunc(Number(t));return Number.isNaN(i)?0:i&3}shouldUseRightClickEnter(){const e=this.getShortcutMenuMode();return e===0?!0:e===1?this.active:!1}updateModifierStateFromEvent(e){const t={ctrlKey:!!e.ctrlKey,shiftKey:!!e.shiftKey,altKey:!!e.altKey,metaKey:!!e.metaKey},i=this._modifierState,n=i.ctrlKey!==t.ctrlKey||i.shiftKey!==t.shiftKey||i.altKey!==t.altKey||i.metaKey!==t.metaKey;return n&&(this._modifierState=t),n}handleCtrlToggleKey(e){return e.key!=="Control"||e.repeat||e.type!=="keydown"?!1:(this._ctrlArcFlip=!this._ctrlArcFlip,!0)}resolvePromptDefaults(e){const t="basePoint"in e,i="useBasePoint"in e,n="useDashedLine"in e,r="baseAngle"in e,o=t&&e.basePoint?e.basePoint:void 0,a=i?e.useBasePoint:!1,l=n?!e.useDashedLine:!1,c=r?e.baseAngle:void 0;return{message:e.getDisplayMessage(),jig:e.jig,basePoint:o,useBasePoint:a,showBaseLineOnly:l,baseAngle:c}}async makeFloatingInputPromise(e){return new Promise((t,i)=>{var _;this.active=!0,this.entitySelectionActive=!1;let n=!1;const r=C=>{const O=e.handler.parse(C.x,C.y);return{isValid:O!=null,value:O??void 0}},o=this.resolvePromptDefaults(e.promptOptions),a=this.startPromptInputSession(e.promptOptions,e.handler,e.inputCount??1,!0);let l;o.useBasePoint&&o.basePoint&&(l=o.basePoint);const c=o.useBasePoint&&o.basePoint?o.basePoint:this.lastPoint??void 0,h="allowNone"in e.promptOptions?e.promptOptions.allowNone:!1,p=this.resolvePromptDefaultValue(e.promptOptions),m=new Mr(this.view,{parent:this.view.canvas,inputCount:e.inputCount,message:o.message,disableOSnap:e.disableOSnap,showBaseLineOnly:o.showBaseLineOnly,basePoint:l,orthoReferencePoint:c,baseAngle:o.baseAngle,allowPrompt:e.allowPrompt!==!1,allowNone:h,useDefaultValue:p.useDefaultValue,defaultValue:p.defaultValue,validate:r,getDynamicValue:e.getDynamicValue,drawPreview:C=>{var O;if(o.jig){const B=e.getDynamicValue(C);o.jig.update(B.value),o.jig.render()}(O=e.drawPreview)==null||O.call(e,C)},onCommit:(C,O)=>{let B=!1;return(!e.onCommit||e.onCommit(C,O))&&(f(C),B=!0),B&&m.lastPoint&&(this.lastPoint={x:m.lastPoint.x,y:m.lastPoint.y}),B},onCancel:()=>w(),onNone:()=>v()});(_=e.onFloatingInputCreated)==null||_.call(e,m);const g=()=>{var C,O;n||(n=!0,this.active=!1,this.entitySelectionActive=!1,this._activeRejector===w&&(this._activeRejector=null),(C=e.cleanup)==null||C.call(e),(O=o.jig)==null||O.end(),document.removeEventListener("keydown",S),document.removeEventListener("keydown",P),document.removeEventListener("keyup",P),this.view.canvas.removeEventListener("contextmenu",A),m.dispose(),a.cancel(),this._commandLine.clear())},f=C=>{g(),t(C)},w=C=>{g(),i(C??new Error("cancelled"))};this._activeRejector=w;const v=()=>{w(new Ci)},x=C=>{w(new Ai(C))},S=C=>{C.key==="Escape"&&w()},P=C=>{const O=this.handleCtrlToggleKey(C),B=this.updateModifierStateFromEvent(C);(O||B)&&m.requestPreviewRefresh()},A=C=>{this.shouldUseRightClickEnter()&&(C.preventDefault(),v())};document.addEventListener("keydown",S),document.addEventListener("keydown",P),document.addEventListener("keyup",P),this.view.canvas.addEventListener("contextmenu",A),m.showAt(this.view.canvasToViewport(this.view.curMousePos)),a.promise.then(C=>{if(!n)switch(C.kind){case"value":if(e.handler instanceof Si){const O=C.value;O&&Number.isFinite(O.x)&&Number.isFinite(O.y)&&(this.lastPoint={x:O.x,y:O.y})}f(C.value);break;case"keyword":x(C.keyword);break;case"none":h?v():w();break}})})}};Ji.stylesInjected=!1;let Gn=Ji;class Xl{constructor(e){this.events={sysVarChanged:new d.AcCmEventManager,commandWillStart:new d.AcCmEventManager,commandEnded:new d.AcCmEventManager},this._view=e,this._cursorManager=new Ml(e),this._inputManager=new Gn(e)}get isActive(){return this._inputManager.isActive}get isEntitySelectionActive(){return this._inputManager.isEntitySelectionActive}getInputModifiers(){return this._inputManager.modifiers}getInputToggles(){return this._inputManager.toggles}resetInputToggles(){this._inputManager.resetToggles()}cancelActiveInput(){this._inputManager.cancelActiveInput()}enqueueScriptInputs(e){this._inputManager.enqueueScriptInputs(e)}clearScriptInputs(){this._inputManager.clearScriptInputs()}hasScriptInputs(){return this._inputManager.hasScriptInputs()}drainScriptInputs(){return this._inputManager.drainScriptInputs()}showMessage(e,t="info",i){this._inputManager.showMessage(e,t,i)}peekScriptInput(){return this._inputManager.peekScriptInput()}consumeScriptInput(){return this._inputManager.consumeScriptInput()}get currentCursor(){return this._currentCursor}restoreCursor(){this._previousCursor!=null&&this.setCursor(this._previousCursor)}setCursor(e){this._cursorManager.setCursor(e),this._previousCursor=this._currentCursor,this._currentCursor=e}async withCursor(e,t){const i=this._currentCursor;this.setCursor(e);try{return await Promise.resolve(t())}finally{i!==void 0?this.setCursor(i):this.restoreCursor()}}setCursorColor(e){this._cursorManager.setCursorColor(e)}syncCursorBackground(e){this._cursorManager.syncBackgroundColor(e)}async getPoint(e){return await this._inputManager.getPoint(e)}async getAngle(e){return await this._inputManager.getAngle(e)}async getDistance(e){return await this._inputManager.getDistance(e)}async getDouble(e){return await this._inputManager.getDouble(e)}async getInteger(e){return await this._inputManager.getInteger(e)}async getString(e){return await this._inputManager.getString(e)}async getKeywords(e){return await this._inputManager.getKeywords(e)}async getEntity(e){return await this._inputManager.getEntity(e)}async getSelection(e){return await this._inputManager.getSelection(e)}async getBox(e){return await this._inputManager.getBox(e)}selectAll(e){try{const t=k.instance.curDocument.database.tables.blockTable.modelSpace,i=[];for(const n of t.newIterator())(!e||e.matches(n))&&i.push(n.objectId);return new xi(b.OK,new On(i))}catch{return new xi(b.Error)}}}class Dr{constructor(e,t,i=1){if(this._handleIds=[],this.copyCount=Math.max(0,i),this.copyCount===0||t.length===0){this.useBatchPreview=!1;return}for(let n=0;n<this.copyCount;n++){const r=e.createEntityPreview(t);if(!r){this._handleIds.forEach(o=>e.removeEntityPreview(o)),this._handleIds.length=0,this.useBatchPreview=!1;return}this._handleIds.push(r),e.updateEntityPreview(r,new d.AcGeMatrix3d)}this.useBatchPreview=this._handleIds.length===this.copyCount}updateMatrix(e,t){!this.useBatchPreview||this._handleIds.length!==1||e.updateEntityPreview(this._handleIds[0],t)}updatePlacements(e,t,i){this.useBatchPreview&&this._handleIds.forEach((n,r)=>{const o=r+1,a=Kn(t,o,this.copyCount,i);e.updateEntityPreview(n,new d.AcGeMatrix3d().makeTranslation(a.x,a.y,a.z))})}dispose(e){this._handleIds.forEach(t=>e.removeEntityPreview(t)),this._handleIds.length=0}}function Kn(s,e,t,i){const n=i&&t>0?e/t:e;return new d.AcGePoint3d(s.x*n,s.y*n,s.z*n)}class ql extends R{constructor(e,t){super(e),this._transientsPublished=!1,this._view=e,this.batchPreview=new Dr(e,t.map(i=>i.objectId)),this.previewEntities=this.batchPreview.useBatchPreview?[]:t.map(i=>i.clone()).filter(i=>!!i)}update(e){}render(){this.batchPreview.useBatchPreview||this.previewEntities.length!==0&&(this._transientsPublished||(this._view.addTransientEntity(this.previewEntities),this._transientsPublished=!0))}end(){this.batchPreview.dispose(this._view),this.previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}}class $t extends R{constructor(e,t,i=1){super(e),this._transientsPublished=!1,this._lastTransforms=[],this._view=e,this.copyCount=i,this.batchPreview=new Dr(e,t.map(n=>n.objectId),i),this.previewEntries=this.batchPreview.useBatchPreview?[]:$t.createPreviewEntries(t,i)}get previewEntities(){return this.previewEntries.map(e=>e.entity)}update(e){const t=this.buildTransforms(e);if(this.batchPreview.useBatchPreview){this.copyCount===1&&t.length>0&&this.batchPreview.updateMatrix(this._view,t[0].matrix);return}this._lastTransforms=t}render(){this.batchPreview.useBatchPreview||this.previewEntries.length!==0&&(this._transientsPublished||(this._view.addTransientEntity(this.previewEntities),this._transientsPublished=!0),this._lastTransforms.length>0&&this._view.updateTransientPreviewTransforms(this._lastTransforms))}end(){this.batchPreview.dispose(this._view),this.previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}static createPreviewEntries(e,t){const i=[];for(let n=1;n<=t;n++)e.map(r=>r.clone()).filter(r=>!!r).forEach(r=>{i.push({entity:r,copyFactor:n})});return i}}class Ye{constructor(e){this.state=e}setState(e){this.state=e}async run(e){for(;this.state;)try{const t=this.state.buildPrompt(),i=await e(t);if(await this.state.handleResult(i)==="finish")break}catch{break}}}class my{constructor(e=[]){this._typedValues=[...e]}get typedValues(){return[...this._typedValues]}matches(e){if(this._typedValues.length===0)return!0;let t="equals";for(const i of this._typedValues){if(i.code===d.AcDbDxfCode.Operator){t=this.parseOperator(i.value);continue}if(!this.matchTypedValue(e,i,t))return!1;t="equals"}return!0}parseOperator(e){switch(String(e??"").trim()){case"!=":case"<>":return"notEquals";case">":return"greaterThan";case">=":return"greaterThanOrEqual";case"<":return"lessThan";case"<=":return"lessThanOrEqual";case"=":case"==":default:return"equals"}}matchTypedValue(e,t,i){const n=this.resolveEntityValue(e,t.code);return n==null?!1:this.compare(n,t.value,i)}resolveEntityValue(e,t){var i;switch(t){case d.AcDbDxfCode.Start:return e.dxfTypeName||e.type;case d.AcDbDxfCode.LayerName:return e.layer;case d.AcDbDxfCode.ColorName:return(i=e.color)==null?void 0:i.toString();case d.AcDbDxfCode.LinetypeName:return e.lineType;case d.AcDbDxfCode.LineWeight:return Number(e.lineWeight);default:return}}compare(e,t,i){const n=Number(e),r=Number(t);if(Number.isFinite(n)&&Number.isFinite(r)&&`${e}`.trim()!==""&&`${t}`.trim()!=="")switch(i){case"equals":return n===r;case"notEquals":return n!==r;case"greaterThan":return n>r;case"greaterThanOrEqual":return n>=r;case"lessThan":return n<r;case"lessThanOrEqual":return n<=r}const a=String(e).toLowerCase(),l=String(t).toLowerCase();switch(i){case"equals":return a===l;case"notEquals":return a!==l;case"greaterThan":return a>l;case"greaterThanOrEqual":return a>=l;case"lessThan":return a<l;case"lessThanOrEqual":return a<=l}}}class Jl{constructor(e,t,i,n=500,r=500){this.host=e,this.hoverEvent=t,this.unhoverEvent=i,this.hoverDelay=n,this.pauseDelay=r,this.hoverTimer=null,this.pauseTimer=null,this.hoveredId=null}handleMouseMove(e,t){if(this.clearHoverTimer(),this.hoveredId){this.hoverAt(e,t);return}this.hoverTimer=setTimeout(()=>{this.hoverAt(e,t)},this.hoverDelay)}clear(){this.setHoveredId(null),this.clearHoverTimer(),this.clearPauseTimer()}dispose(){this.clearHoverTimer(),this.clearPauseTimer()}hoverAt(e,t){const i=this.host.pick({x:e,y:t});i.length>0?this.setHoveredId(i[0].id):this.clear()}setHoveredId(e){this.hoveredId!==e&&(this.hoveredId&&(this.unhoverEvent.dispatch({id:this.hoveredId,x:this.host.curMousePos.x,y:this.host.curMousePos.y}),this.host.onUnhover(this.hoveredId)),this.hoveredId=e,e&&(this.startPauseTimer(e),this.host.onHover(e)))}startPauseTimer(e){this.clearPauseTimer(),this.pauseTimer=setTimeout(()=>{this.hoverEvent.dispatch({id:e,x:this.host.curMousePos.x,y:this.host.curMousePos.y})},this.pauseDelay)}clearHoverTimer(){this.hoverTimer&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}clearPauseTimer(){this.pauseTimer&&(clearTimeout(this.pauseTimer),this.pauseTimer=null)}}function Or(s,e="replace"){return s.shiftKey?"remove":s.ctrlKey||s.metaKey?"add":e}function Ql(s){return Or(s,"add")}var ye=(s=>(s[s.SELECTION=0]="SELECTION",s[s.PAN=1]="PAN",s))(ye||{});class ec{constructor(e,t){this.events={mouseMove:new d.AcCmEventManager,viewResize:new d.AcCmEventManager,viewChanged:new d.AcCmEventManager,hover:new d.AcCmEventManager,unhover:new d.AcCmEventManager,renderFrame:new d.AcCmEventManager},this._container=t,this._canvas=e;const i=e.getBoundingClientRect();this._bbox=new d.AcGeBox3d,this._width=i.width,this._height=i.height,this._curPos=new d.AcGePoint2d,this._curMousePos=new d.AcGePoint2d,this._selectionSet=new On,this._editor=new Xl(this),this._osnapResolver=new ft(this),this._canvas.addEventListener("mousemove",a=>this.onMouseMove(a)),this._canvas.addEventListener("mousedown",a=>{a.button===1&&this._editor.setCursor(Le.Grab)}),this._canvas.addEventListener("mouseup",a=>{a.button===1&&this._editor.restoreCursor()});const n=Ko.debounce(()=>this.onWindowResize(),0,{leading:!1,trailing:!0}),r=new ResizeObserver(n);r.observe(this._container);const o=this._container.parentElement;o&&r.observe(o),this._selectionBoxSize=4,this._hoverController=new Jl(this,this.events.hover,this.events.unhover)}get editor(){return this._editor}get selectionBoxSize(){return this._selectionBoxSize}set selectionBoxSize(e){this._selectionBoxSize=e}hasEntity(e){return!1}updateEntityVisibility(e){return!1}setEntitySceneVisible(e,t){return!1}getEntityVisible(e){}async withMode(e,t){const i=this.mode;this.mode=e;try{return await Promise.resolve(t())}finally{this.mode=i}}setCursor(e){this._editor.setCursor(e)}getSelectionMode(e,t){return t.x>=e.x?"window":"crossing"}getSelectionActionFromEvent(e,t="replace"){return Or(e,t)}isSelectionClick(e,t,i=2){const n=t.x-e.x,r=t.y-e.y;return Math.hypot(n,r)<i}getSelectionPreviewStyle(e,t){return{borderStyle:e==="window"?"solid":"dashed",lineColor:t==="remove"?"var(--ml-ui-danger, #ff4d4f)":e==="window"?"var(--ml-ui-canvas-line, #00ff5a)":"var(--ml-ui-accent-alt, #00d1ff)",background:"var(--ml-ui-canvas-fill-mix, var(--ml-ui-canvas-fill, rgba(64, 158, 255, 0.12)))"}}applySelection(e,t){if(t==="replace"){this.selectionSet.clear();const i=e.filter(n=>!this.selectionSet.has(n));i.length>0&&this.selectionSet.add(i);return}if(e.length!==0)if(t==="add"){const i=e.filter(n=>!this.selectionSet.has(n));i.length>0&&this.selectionSet.add(i)}else{const i=e.filter(n=>this.selectionSet.has(n));i.length>0&&this.selectionSet.delete(i)}}selectByBoxWithMode(e,t,i="add"){const n=this.collectSelectionIdsByBox(e,t);this.applySelection(n,i)}collectSelectionIdsByBox(e,t){const i=this.search(e,{selectionMode:t}),n=[];return i.forEach(r=>{Sn(r)&&n.push(r.id)}),n}setCalculateSizeCallback(e){this._calculateSizeCallback=e}get width(){return this._width}set width(e){this._width=e}get height(){return this._height}set height(e){this._height=e}get bbox(){return this._bbox}get canvas(){return this._canvas}get container(){return this._container}viewportToCanvas(e){const t=this._canvas.getBoundingClientRect();return new d.AcGePoint2d(e.x-t.left,e.y-t.top)}canvasToViewport(e){const t=this._canvas.getBoundingClientRect();return new d.AcGePoint2d(e.x+t.left,e.y+t.top)}canvasToContainer(e){const t=this._canvas.getBoundingClientRect(),i=this._container.getBoundingClientRect();return new d.AcGePoint2d(e.x+(t.left-i.left),e.y+(t.top-i.top))}viewportToContainer(e){const t=this._container.getBoundingClientRect();return new d.AcGePoint2d(e.x-t.left,e.y-t.top)}get aspect(){return this._width/this._height}get curPos(){return this._curPos}get curMousePos(){return this._curMousePos}get selectionSet(){return this._selectionSet}get osnapResolver(){return this._osnapResolver}onWindowResize(){if(this._calculateSizeCallback){const{width:e,height:t}=this._calculateSizeCallback();this._width=Math.max(1,Math.floor(e)),this._height=Math.max(1,Math.floor(t))}else this._width=Math.max(1,Math.floor(this._canvas.clientWidth)),this._height=Math.max(1,Math.floor(this._canvas.clientHeight));this.events.viewResize.dispatch({width:this._width,height:this._height})}clearHover(){this._hoverController.clear()}onMouseMove(e){this._curMousePos=this.viewportToCanvas({x:e.clientX,y:e.clientY});const t=this.screenToWorld(this._curMousePos);this._curPos.copy(t),this.events.mouseMove.dispatch({x:t.x,y:t.y}),this.mode==0&&(this._editor.isActive||this._hoverController.handleMouseMove(t.x,t.y))}}function Yt(s,e){return new d.AcGeMatrix3d().makeTranslation(s.x,s.y,s.z).multiply(new d.AcGeMatrix3d().makeRotationZ(e)).multiply(new d.AcGeMatrix3d().makeTranslation(-s.x,-s.y,-s.z))}const Br=new Set;function tc(s,e="drawing"){const t=s==null?void 0:s.trim();return t&&(t.split(/[\\/]/).pop()??t).replace(/\.[^.]+$/,"").trim()||e}function jr(s,e,t="drawing"){const i=tc(s,t),n=e.startsWith(".")?e:`.${e}`;let r=0,o=`${i}${n}`;for(;Br.has(o);)r+=1,o=`${i}-${r+1}${n}`;return Br.add(o),o}function yy(){Br.clear()}const gy=64,Ke=class Ke{static clearCache(){this._cache.clear(),this._cacheDocId=void 0}static bindDocListener(){this._docListenerBound||(this._docListenerBound=!0,k.instance.events.documentActivated.addEventListener(()=>{this.clearCache()}))}capture(e,t=gy){Ke.bindDocListener();const i=e.trim();if(!i)return;const n=k.instance.curDocument,r=n==null?void 0:n.database,o=k.instance.curView;if(!r||!o)return;const a=n.database.tables.blockTable.modelSpace.objectId;Ke._cacheDocId!==a&&(Ke._cache.clear(),Ke._cacheDocId=a);const l=r.tables.blockTable.getAt(i);if(!l||l.isXref)return;const c=`${a}\0${l.objectId}\0${t}`,h=Ke._cache.get(c);if(h)return h;const p=this.fromStoredIcon(l);if(p)return Ke._cache.set(c,p),p;const m=this.fromGeometry(l,o,t);return m&&Ke._cache.set(c,m),m}fromStoredIcon(e){var t;if((t=e.previewIcon)!=null&&t.length)return d.acdbPreviewIconToDataUrl(e.previewIcon)}fromGeometry(e,t,i){const n=t.renderer;let r=null;try{const o=new d.AcDbBlockReference(e.name);o.database=e.database;const a=o.worldDraw(n);if(a)r=a;else{const c=new d.AcCmColor;c.setForeground(),r=d.AcDbRenderingCache.instance.draw(n,e,c,[],!1)}if(!r)return;r.syncDraw();const l=n.renderEntityPreview(r,{width:i,height:i,margin:1.15,localLineResolutionOnly:!0,viewportSize:{width:t.width,height:t.height},onRestored:()=>{t.isDirty=!0}});return l?l.canvas.toDataURL("image/png"):void 0}catch(o){console.warn("[BlockPreview] Failed to capture",e.name,o);return}finally{r==null||r.dispose()}}};Ke._cache=new Map,Ke._docListenerBound=!1;let Fr=Ke;class ic{convert(){const e=k.instance.curDocument,t=e.database.dxfOut(void 0,6),i=this.getBaseName(e.fileName||e.docTitle);this.createFileAndDownloadIt(t,`${i}.dxf`)}createFileAndDownloadIt(e,t){const i=typeof e=="string"?e:new Uint8Array(e),n=new Blob([i],{type:"application/dxf;charset=utf-8"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}getBaseName(e){return((e==null?void 0:e.trim())||"drawing").replace(/\.[^.]+$/,"")||"drawing"}}class nc extends z{async execute(e){await this.withBusyIndicator(()=>{new ic().convert()},u.t("main.message.exportingDxf"))}}class sc{async convert(e,t){const i=k.instance.curView;await i.waitUntilIdle()||console.warn("[PNGOUT] Timed out waiting for scene idle; exporting current geometry");const r=i.activeLayoutView,o=i.renderer,a=o.internalRenderer,l=i.internalScene,c=i.internalCamera;if(!l||!c||!r){console.error("[PNGOUT] Scene or camera not available");return}const h=i.width/Math.max(i.height,1),p=e?this.getBoundsAspect(e):h;let m=Math.max(1,Math.round(i.width)),g=Math.max(1,Math.round(i.height));if(t&&t>0){const $=this.resolveOutputSize(t,p);m=$.width,g=$.height}const f=e?{width:m,height:g}:this.resolveRenderSizeForCenterCrop(m,g,h),w=f.width,v=f.height,x=!e&&(w!==m||v!==g),S=c.zoom,P=c.position.clone(),A=c.left,_=c.right,C=c.top,O=c.bottom,B=a.getScissorTest(),I=a.getPixelRatio(),N=a.getRenderTarget();let G;try{e&&r.applyExportCamera(e,w,v),a.setPixelRatio(1),o.updateLineResolution(w,v),G=new L.WebGLRenderTarget(w,v,{minFilter:L.LinearFilter,magFilter:L.LinearFilter,format:L.RGBAFormat,type:L.UnsignedByteType}),a.setRenderTarget(G),a.setViewport(0,0,w,v),a.setScissorTest(!1),r.renderObject(l);const $=new Uint8Array(w*v*4);a.readRenderTargetPixels(G,0,0,w,v,$);const X=this.flipPixelsVertically($,w,v),Y=x?this.cropPixelsCentered(X,w,v,m,g):X,Q=this.createCanvasFromPixels(Y,m,g);this.createFileAndDownloadIt(Q)}finally{a.setRenderTarget(N),G==null||G.dispose(),c.zoom=S,c.position.copy(P),c.left=A,c.right=_,c.top=C,c.bottom=O,c.updateProjectionMatrix(),a.setPixelRatio(I),o.setSize(i.width,i.height),a.setScissorTest(B),o.syncCameraZoom(S),r.render(i.cadScene),i.isDirty=!0}}resolveOutputSize(e,t){const i=Math.max(1,Math.round(e)),n=Number.isFinite(t)&&t>Number.EPSILON?t:1;return n>=1?{width:i,height:Math.max(1,Math.round(i/n))}:{width:Math.max(1,Math.round(i*n)),height:i}}resolveRenderSizeForCenterCrop(e,t,i){const n=Number.isFinite(i)&&i>Number.EPSILON?i:1,r=e/Math.max(t,1);return Math.abs(r-n)<1e-6?{width:e,height:t}:n>r?{width:Math.max(e,Math.ceil(t*n)),height:t}:{width:e,height:Math.max(t,Math.ceil(e/n))}}cropPixelsCentered(e,t,i,n,r){if(t===n&&i===r)return e;const o=Math.floor((t-n)/2),a=Math.floor((i-r)/2),l=new Uint8Array(n*r*4);for(let c=0;c<r;c++){const h=((c+a)*t+o)*4,p=h+n*4,m=c*n*4;l.set(e.subarray(h,p),m)}return l}getBoundsAspect(e){const t=new d.AcGeVector2d;e.getSize(t);const i=Math.max(Math.abs(t.x),Number.EPSILON),n=Math.max(Math.abs(t.y),Number.EPSILON);return i/n}flipPixelsVertically(e,t,i){const n=new Uint8Array(t*i*4);for(let r=0;r<i;r++){const o=(i-1-r)*t*4,a=r*t*4;for(let l=0;l<t*4;l++)n[a+l]=e[o+l]}return n}createCanvasFromPixels(e,t,i){const n=document.createElement("canvas");n.width=t,n.height=i;const r=n.getContext("2d"),o=r.createImageData(t,i);return o.data.set(e),r.putImageData(o,0,0),n}createFileAndDownloadIt(e){const t=k.instance.curDocument,i=jr(t.fileName||t.docTitle,"png"),n=e.toDataURL("image/png"),r=document.createElement("a");r.href=n,r.download=i,document.body.appendChild(r),r.click(),document.body.removeChild(r)}}const rc=1024;class oc extends z{async execute(e){const t=new sc,i=k.instance.curView;this.syncActiveLayoutViewSize(i);const n=new Bn(u.t("jig.pngout.boundsFirstCorner"),u.t("jig.pngout.boundsSecondCorner"));n.disableOSnap=!0,n.allowNone=!0;const r=await k.instance.editor.getBox(n);let o;if(r.status===b.OK&&r.value)o=r.value;else if(r.status===b.None)o=this.getCurrentDrawingBounds();else return;const a=new ie(u.t("jig.pngout.longSidePrompt"));a.allowNone=!0,a.allowNegative=!1,a.allowZero=!1,a.defaultValue=rc,a.useDefaultValue=!0;const l=await k.instance.editor.getDouble(a);if(l.status===b.Cancel||l.status===b.Error)return;const c=l.status===b.OK&&l.value!==void 0?l.value:rc;await t.convert(o,c)}getCurrentDrawingBounds(){const t=k.instance.curDocument.database.extents;return new d.AcGeBox2d(new d.AcGePoint2d(t.min.x,t.min.y),new d.AcGePoint2d(t.max.x,t.max.y))}syncActiveLayoutViewSize(e){const t=e.activeLayoutView;t&&t.resize(e.width,e.height)}}class ac{export(e,t){const i=this.capture(e,t);return i.ok?this.downloadDataUrl(i.dataUrl)?{ok:!0,exportedCount:i.exportedCount,skippedCount:i.skippedCount}:{ok:!1,reason:"download-failed"}:i.reason==="no-entities"?{ok:!1,reason:"no-bounds"}:i.reason==="download-failed"?{ok:!1,reason:"capture-failed"}:{ok:!1,reason:i.reason}}capture(e,t){if(e.length===0)return{ok:!1,reason:"no-entities"};const i=k.instance.curView,n=i.cadScene,o=n.findPreviewableEntityIds(e,"all").length,a=e.length-o,l=n.computeEntityPreviewBounds2d(e,1.1,"all")??null;if(!l)return console.warn("[ENTPREVIEW] Failed to compute preview bounds",e),{ok:!1,reason:"no-bounds"};const c=this.resolveOutputSize(t,this.getBoundsAspect(l)),h=c.width,p=c.height,m=n.createEntityPreviewRoot(e,{scope:"all"});if(!m)return console.warn("[ENTPREVIEW] Failed to build preview geometry",`${e.length} requested entity ids`),{ok:!1,reason:"no-preview-root"};const g=i.renderer;try{const f=g.renderEntityPreview(m,{width:h,height:p,bounds:l,margin:1,viewportSize:{width:i.width,height:i.height},localLineResolutionOnly:!0,onRestored:()=>{i.isDirty=!0}});return f?{ok:!0,dataUrl:f.canvas.toDataURL("image/png"),exportedCount:o,skippedCount:a}:{ok:!1,reason:"capture-failed"}}catch(f){return console.error("[ENTPREVIEW] Failed to render preview image",f),{ok:!1,reason:"capture-failed"}}finally{M.disposePreviewSubset(m)}}resolveOutputSize(e,t){const i=Math.max(1,Math.round(e)),n=Number.isFinite(t)&&t>Number.EPSILON?t:1;return n>=1?{width:i,height:Math.max(1,Math.round(i/n))}:{width:Math.max(1,Math.round(i*n)),height:i}}getBoundsAspect(e){const t=new d.AcGeVector2d;e.getSize(t);const i=Math.max(Math.abs(t.x),Number.EPSILON),n=Math.max(Math.abs(t.y),Number.EPSILON);return i/n}downloadDataUrl(e){try{const t=k.instance.curDocument,i=jr(t.fileName||t.docTitle,"png","entity-preview"),n=document.createElement("a");return n.href=e,n.download=i,document.body.appendChild(n),n.click(),document.body.removeChild(n),!0}catch(t){return console.error("[ENTPREVIEW] Failed to download preview PNG",t),!1}}}const lc=512;class cc extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.selectionSet;let i=t.count>0?t.ids:[];if(i.length===0){const c=new Pt(u.sysCmdPrompt("entout")),h=await k.instance.editor.getSelection(c);if(h.status!==b.OK||!h.value||h.value.count===0)return;i=h.value.ids}const n=new ie(u.t("jig.entout.longSidePrompt"));n.allowNone=!0,n.allowNegative=!1,n.allowZero=!1,n.defaultValue=lc,n.useDefaultValue=!0;const r=await k.instance.editor.getDouble(n);if(r.status===b.Cancel||r.status===b.Error)return;const o=r.status===b.OK&&r.value!==void 0?r.value:lc,a=k.instance.curView;this.syncActiveLayoutViewSize(a);const l=await this.withBusyIndicator(()=>new ac().export(i,o),u.t("main.message.exportingEntityPreview"));if(l.ok){let c=`${l.exportedCount} ${u.t("jig.entout.exported")}`;l.skippedCount>0&&(c+=`, ${l.skippedCount} ${u.t("jig.entout.skipped")}`),this.showMessage(c,"success");return}this.showMessage(u.t(`jig.entout.failed.${l.reason}`),"error")}syncActiveLayoutViewSize(e){const t=e.activeLayoutView;t&&t.resize(e.width,e.height)}}class dc{constructor(e){this.events={changed:new d.AcCmEventManager},this.layers=[],this.currentLayerName="",this.handleLayerAppended=t=>{this.upsertLayerInfo(t.layer)},this.handleLayerErased=t=>{this.removeLayerInfo(t.layer.name)},this.handleLayerModified=t=>{const i=this.findLayerInfo(t.layer.name);if(!i){this.upsertLayerInfo(t.layer);return}Object.assign(i,this.toLayerInfo(t.layer)),this.notify()},this.handleSysVarChanged=t=>{t.database===this.database&&t.name.toUpperCase()==="CLAYER"&&this.syncCurrentLayerName()},this.document=e,this.database=e.database,d.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.handleSysVarChanged),this.bindDatabase()}destroy(){d.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.handleSysVarChanged),this.unbindDatabase(),this.layers=[],this.currentLayerName=""}getLayers(){return[...this.layers]}getCurrentLayerName(){return this.currentLayerName}setLayerOn(e,t){return this.getLayerService().setLayerOn(e,t,{switchCurrentLayer:!0})}setAllLayersOn(){return this.getLayerService().setAllLayersOn()>0}setAllLayersOffExceptCurrent(){return this.getLayerService().setAllLayersOffExceptCurrent()>0}setLayerColor(e,t){return this.getLayerService().setLayerColor(e,t)}setCurrentLayer(e){const t=this.getLayerService().setCurrentLayer(e);return t&&this.syncCurrentLayerName(),t}setLayerFrozen(e,t){return this.getLayerService().setLayerFrozen(e,t,{switchCurrentLayer:!0})}setLayerLocked(e,t){return this.getLayerService().setLayerLocked(e,t)}setLayerLineWeight(e,t){return this.getLayerService().setLayerLineWeight(e,t)}setLayerPlottable(e,t){return this.getLayerService().setLayerPlottable(e,t)}setLayerLinetype(e,t){return this.getLayerService().setLayerLinetype(e,t)}setLayerTransparency(e,t){return this.getLayerService().setLayerTransparency(e,t)}setLayerDescription(e,t){return this.getLayerService().setLayerDescription(e,t)}isolateSingleLayer(e){return this.getLayerService().isolateSingleLayer(e)}getLayerService(){return this.document.layerService}toLayerInfo(e){return{name:e.name,color:e.color.toString(),cssColor:e.color.cssColor||"#FFFFFF",isOn:!e.isOff,isFrozen:e.isFrozen,isLocked:te.isLayerLocked(e)}}rebuildLayerCache(){this.layers=[];for(const e of this.database.tables.layerTable.newIterator())this.layers.push(this.toLayerInfo(e))}findLayerInfo(e){return this.layers.find(t=>t.name===e)}removeLayerInfo(e){const t=this.layers.findIndex(i=>i.name===e);t!==-1&&(this.layers.splice(t,1),this.notify())}upsertLayerInfo(e){const t=this.findLayerInfo(e.name),i=this.toLayerInfo(e);t?Object.assign(t,i):this.layers.push(i),this.notify()}syncCurrentLayerName(e=!0){const t=this.database.clayer||"";this.currentLayerName!==t&&(this.currentLayerName=t,e&&this.notify())}notify(){this.events.changed.dispatch({layers:this.getLayers(),currentLayerName:this.currentLayerName})}bindDatabase(){this.rebuildLayerCache(),this.currentLayerName=this.database.clayer||"",this.notify(),this.database.events.layerAppended.addEventListener(this.handleLayerAppended),this.database.events.layerErased.addEventListener(this.handleLayerErased),this.database.events.layerModified.addEventListener(this.handleLayerModified)}unbindDatabase(){this.database.events.layerAppended.removeEventListener(this.handleLayerAppended),this.database.events.layerErased.removeEventListener(this.handleLayerErased),this.database.events.layerModified.removeEventListener(this.handleLayerModified)}}class zr{constructor(e){this.db=e}getEntitiesByIds(e){return e.map(t=>this.db.tables.blockTable.getEntityById(t)).filter(t=>!!t)}transformEntities(e,t){let i=0;return e.forEach(n=>{const r=this.db.openEntityForWrite(n);r&&(r.transformBy(t),i++)}),i}translateEntities(e,t){const i=new d.AcGeMatrix3d().makeTranslation(t.x,t.y,t.z);return this.transformEntities(e,i)}rotateEntities(e,t,i){const n=Yt(t,i);return this.transformEntities(e,n)}cloneAndTransform(e,t,i={}){const n=i.append??!0,r=e.map(o=>o.clone()).filter(o=>!!o);return r.forEach(o=>o.transformBy(t)),n&&r.length>0&&this.db.tables.blockTable.modelSpace.appendEntity(r),r}eraseEntities(e){return this.runEntityEdit(()=>{let t=0;return e.forEach(i=>{const n=this.db.openEntityForWrite(i);n&&(n.erase(),t++)}),t})}moveEntitiesToCurrentLayer(e){var a;const t=(a=this.db.clayer)==null?void 0:a.trim(),i=t?this.db.tables.layerTable.getAt(t):void 0;if(!i)return{changedCount:0,alreadyCurrent:0,missing:0,currentLayerMissing:!0};let n=0,r=0,o=0;return new Set(e).forEach(l=>{const c=this.db.tables.blockTable.getEntityById(l);if(!c){o++;return}if(c.layer===i.name){r++;return}const h=this.db.openEntityForWrite(l);if(!h){o++;return}h.layer=i.name,n++}),{changedCount:n,alreadyCurrent:r,missing:o,currentLayerMissing:!1}}static copyDisplayTraits(e,t){t.layer=e.layer,t.color=e.color.clone(),t.lineType=e.lineType,t.lineWeight=e.lineWeight,t.linetypeScale=e.linetypeScale,t.transparency=e.transparency,t.visibility=e.visibility}runEdit(e,t){return U(this.db,e,t)}runEntityEdit(e){return U(this.db,ol,e)}}async function uc(s){const e=await k.instance.editor.getSelection(new Pt(u.sysCmdPrompt(s)));if(!(e.status!==b.OK||!e.value||e.value.count===0))return e.value.ids}async function Un(s,e={}){const t=s.view.selectionSet,i=s.doc.database.tables.blockTable,n=e.clearOnEmpty??!0;let r;if(t.count>0?r=t.ids:e.promptKey&&(r=await uc(e.promptKey)),!r||r.length===0)return;const o=[],a=[];for(const l of r){const c=i.getEntityById(l);c&&(o.push(c),a.push(l))}if(o.length===0){n&&t.clear();return}return{entities:o,ids:a}}async function hc(s,e){const t=s.view.selectionSet;if(t.count>0)return t.ids;const i=await uc(e);return i&&i.length>0?i:void 0}const fy="layerp";class Te extends z{shouldRecordUndoStack(e){return this.recordsUndoStack}onCommandWillStart(e){this.globalName.toLowerCase()!==fy&&e.doc.captureLayerPreviousState()}}class pc extends Te{constructor(){super(),this._history=[],this.mode=F.Write}async execute(e){for(this._history=[];;){const t=await this.promptMainAction();if(!t)return;if(t.type==="keyword"){t.keyword==="Name"?await this.runNameBranch(e):this.runUndo(e);continue}this.deleteLayerByEntity(e,t.objectId)}}addKeyword(e,t){e.keywords.add(u.t(`jig.laydel.keywords.${t}.display`),u.t(`jig.laydel.keywords.${t}.global`),u.t(`jig.laydel.keywords.${t}.local`))}async promptMainAction(){const e=new $e(u.t("jig.laydel.selectPrompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(u.t("jig.laydel.invalidSelection")),this.addKeyword(e,"name"),this.addKeyword(e,"undo");const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===b.Keyword&&(t.stringResult==="Name"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runNameBranch(e){for(;;){const t=await this.promptLayerNameAction();if(!t)return;if(t.type==="keyword"){t.keyword==="?"?this.listLayers(e):this.runUndo(e);continue}this.deleteLayerByName(e,t.layerName)}}async promptLayerNameAction(){const e=new ce(u.t("jig.laydel.namePrompt"));e.allowSpaces=!0,e.allowEmpty=!0,this.addKeyword(e,"list"),this.addKeyword(e,"undo");const t=await k.instance.editor.getString(e);if(t.status===b.Keyword&&(t.stringResult==="?"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult};if(t.status!==b.OK)return;const i=(t.stringResult??"").trim();if(i)return{type:"name",layerName:i}}listLayers(e){const t=new te(e.doc.database).getLayerSummaries();console.table(t),this.showMessage(u.t("jig.laydel.layerListSummary"),"info")}deleteLayerByEntity(e,t){var r;const i=e.doc.database.tables.blockTable.getEntityById(t),n=(r=i==null?void 0:i.layer)==null?void 0:r.trim();if(!n){this.showMessage(u.t("jig.laydel.invalidSelection"),"warning");return}this.deleteLayerByName(e,n)}deleteLayerByName(e,t){const i=new te(e.doc.database).deleteLayer(t);if(!i.ok)switch(i.reason){case"not_found":this.showMessage(`${u.t("jig.laydel.layerNotFound")}: ${t}`);return;case"layer_0":this.showMessage(u.t("jig.laydel.cannotDeleteZeroLayer"),"warning");return;case"current_layer":this.showMessage(u.t("jig.laydel.cannotDeleteCurrent"),"warning");return}this._history.push({layer:i.layer,entities:i.entities}),e.view.selectionSet.clear(),k.instance.regen(),this.showMessage(`${u.t("jig.laydel.deleted")}: ${i.layerName}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.showMessage(u.t("jig.laydel.nothingToUndo"),"warning");return}new te(e.doc.database).restoreDeletedLayer(t.layer,t.entities),e.view.selectionSet.clear(),k.instance.regen(),this.showMessage(`${u.t("jig.laydel.restored")}: ${t.layer.name}`,"success")}}class mc extends Te{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.view.selectionSet,i=t.count>0?t.ids:await this.promptSelection();if(!i||i.length===0)return;const n=e.doc.entityService.moveEntitiesToCurrentLayer(i);if(n.currentLayerMissing){this.showMessage(u.t("jig.laycur.currentLayerNotFound"),"warning");return}if(n.changedCount===0){this.showMessage(n.alreadyCurrent>0?u.t("jig.laycur.alreadyCurrent"):u.t("jig.laycur.noObjects"),n.alreadyCurrent>0&&n.missing===0?"info":"warning");return}e.view.selectionSet.clear(),k.instance.regen(),this.showMessage(`${u.t("jig.laycur.changed")}: ${n.changedCount} (${e.doc.database.clayer})`,"success")}async promptSelection(){var i;const e=new Pt(u.t("jig.laycur.prompt")),t=await k.instance.editor.getSelection(e);if(t.status===b.OK)return((i=t.value)==null?void 0:i.ids)??[]}}const by={viewportMode:"Freeze",blockSelectionMode:"None"},Qe=class Qe extends Te{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=F.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=Qe._settings.viewportMode!=="Vpfreeze";;){const t=await this.promptSelection();if(!t)return;if(t.type==="keyword"){t.keyword==="Settings"?await this.runSettings():this.runUndo(e);continue}this.freezeEntityLayer(e,t.objectId)}}addKeyword(e,t){e.keywords.add(u.t(`jig.layfrz.keywords.${t}.display`),u.t(`jig.layfrz.keywords.${t}.global`),u.t(`jig.layfrz.keywords.${t}.local`))}async promptSelection(){const e=new $e(u.t("jig.layfrz.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(u.t("jig.layfrz.invalidSelection")),this.addKeyword(e,"settings"),this.addKeyword(e,"undo");const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===b.Keyword&&(t.stringResult==="Settings"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runSettings(){for(;;){const e=new ne(u.t("jig.layfrz.settingsPrompt"));e.allowNone=!0,this.addKeyword(e,"viewports"),this.addKeyword(e,"blockSelection");const t=await k.instance.editor.getKeywords(e);if(t.status!==b.OK)return;const i=t.stringResult;if(!i)return;i==="Viewports"?await this.promptViewportMode():await this.promptBlockSelectionMode()}}async promptViewportMode(){const e=new ne(u.t("jig.layfrz.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(u.t("jig.layfrz.keywords.freeze.display"),u.t("jig.layfrz.keywords.freeze.global"),u.t("jig.layfrz.keywords.freeze.local")),i=e.keywords.add(u.t("jig.layfrz.keywords.vpfreeze.display"),u.t("jig.layfrz.keywords.vpfreeze.global"),u.t("jig.layfrz.keywords.vpfreeze.local"));e.keywords.default=Qe._settings.viewportMode==="Vpfreeze"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;r&&(Qe._settings.viewportMode=r,r==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.showMessage(u.t("jig.layfrz.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new ne(u.t("jig.layfrz.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(u.t("jig.layfrz.keywords.block.display"),u.t("jig.layfrz.keywords.block.global"),u.t("jig.layfrz.keywords.block.local")),i=e.keywords.add(u.t("jig.layfrz.keywords.entity.display"),u.t("jig.layfrz.keywords.entity.global"),u.t("jig.layfrz.keywords.entity.local")),n=e.keywords.add(u.t("jig.layfrz.keywords.none.display"),u.t("jig.layfrz.keywords.none.global"),u.t("jig.layfrz.keywords.none.local"));e.keywords.default=Qe._settings.blockSelectionMode==="Block"?t:Qe._settings.blockSelectionMode==="Entity"?i:n;const r=await k.instance.editor.getKeywords(e);if(r.status!==b.OK)return;const o=r.stringResult;o&&(Qe._settings.blockSelectionMode=o,this.showMessage(u.t("jig.layfrz.nestedSelectionLimited")))}freezeEntityLayer(e,t){const n=new te(e.doc.database).freezeLayerByEntity(t);if(!n.ok){switch(n.reason){case"invalid_selection":this.showMessage(u.t("jig.layfrz.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${u.t("jig.layfrz.layerNotFound")}: ${n.layerName}`,"warning");return;case"cannot_change_current":this.showMessage(u.t("jig.layfrz.cannotFreezeCurrent"),"warning");return;case"already_frozen":this.showMessage(`${u.t("jig.layfrz.alreadyFrozen")}: ${n.layerName}`,"info");return}return}Qe._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.showMessage(u.t("jig.layfrz.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:n.layerName,wasFrozen:n.previousFrozen??!1}),e.view.selectionSet.clear(),this.showMessage(`${u.t("jig.layfrz.frozen")}: ${n.layerName}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.showMessage(u.t("jig.layfrz.nothingToUndo"),"warning");return}if(!new te(e.doc.database).setLayerFrozenByName(t.layerName,t.wasFrozen)){this.showMessage(`${u.t("jig.layfrz.layerNotFound")}: ${t.layerName}`,"warning");return}e.view.selectionSet.clear(),this.showMessage(`${u.t("jig.layfrz.restored")}: ${t.layerName}`,"success")}};Qe._settings={...by};let Hn=Qe;const wy={isolationMode:"Off",offMode:"Off"},Ce=class Ce extends Te{constructor(){super(),this._vpfreezeHintShown=!1,this._lockFadeHintShown=!1,this.mode=F.Write}async execute(e){this._vpfreezeHintShown=Ce._settings.offMode!=="Vpfreeze",this._lockFadeHintShown=Ce._settings.isolationMode!=="LockAndFade";const t=e.view.selectionSet.ids;if(t.length>0){this.isolateSelectedObjectLayers(e,t);return}for(;;){const i=await this.promptSelection();if(!i)return;if(i.type==="keyword"){await this.runSettings();continue}this.isolateSelectedObjectLayers(e,i.objectIds);return}}addKeyword(e,t){e.keywords.add(u.t(`jig.layiso.keywords.${t}.display`),u.t(`jig.layiso.keywords.${t}.global`),u.t(`jig.layiso.keywords.${t}.local`))}async promptSelection(){var i;const e=new Pt(u.t("jig.layiso.prompt"));this.addKeyword(e,"settings");const t=await k.instance.editor.getSelection(e);if(t.status===b.OK)return{type:"selection",objectIds:((i=t.value)==null?void 0:i.ids)??[]};if(t.status===b.Keyword&&t.stringResult==="Settings")return{type:"keyword",keyword:t.stringResult}}async runSettings(){const e=new ne(u.t("jig.layiso.settingsPrompt"));e.allowNone=!0;const t=e.keywords.add(u.t("jig.layiso.keywords.off.display"),u.t("jig.layiso.keywords.off.global"),u.t("jig.layiso.keywords.off.local")),i=e.keywords.add(u.t("jig.layiso.keywords.lockAndFade.display"),u.t("jig.layiso.keywords.lockAndFade.global"),u.t("jig.layiso.keywords.lockAndFade.local"));e.keywords.default=Ce._settings.isolationMode==="LockAndFade"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;if(r){if(Ce._settings.isolationMode=r,r==="Off"){await this.promptOffMode();return}this._lockFadeHintShown=!0,this.showMessage(u.t("jig.layiso.lockFadeFallback"))}}async promptOffMode(){const e=new ne(u.t("jig.layiso.offModePrompt"));e.allowNone=!0;const t=e.keywords.add(u.t("jig.layiso.keywords.off.display"),u.t("jig.layiso.keywords.off.global"),u.t("jig.layiso.keywords.off.local")),i=e.keywords.add(u.t("jig.layiso.keywords.vpfreeze.display"),u.t("jig.layiso.keywords.vpfreeze.global"),u.t("jig.layiso.keywords.vpfreeze.local"));e.keywords.default=Ce._settings.offMode==="Vpfreeze"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;r&&(Ce._settings.offMode=r,r==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.showMessage(u.t("jig.layiso.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}isolateSelectedObjectLayers(e,t){const i=new te(e.doc.database),{layerNames:n,missingLayerNames:r}=i.collectLayerNamesFromEntities(t);if(r.length>0&&this.showMessage(`${u.t("jig.layiso.layerNotFound")}: ${r.join(", ")}`,"warning"),n.length===0){this.showMessage(u.t("jig.layiso.noLayers"),"warning");return}const o=e.doc.isolateLayers(n,Ce._settings.isolationMode);if(!o){this.showMessage(u.t("jig.layiso.noLayers"),"warning");return}Ce._settings.isolationMode==="Off"&&Ce._settings.offMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.showMessage(u.t("jig.layiso.vpfreezeFallback")),this._vpfreezeHintShown=!0),Ce._settings.isolationMode==="LockAndFade"&&!this._lockFadeHintShown&&(this.showMessage(u.t("jig.layiso.lockFadeFallback")),this._lockFadeHintShown=!0),e.view.selectionSet.clear(),this.showMessage(`${u.t("jig.layiso.isolated")}: ${n.join(", ")} (${u.t("jig.layiso.affectedLayers")}: ${o.affectedLayerCount})`,"success")}};Ce._settings={...wy};let Wn=Ce;class yc extends Te{constructor(){super(),this.mode=F.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.lockEntityLayer(e,t)}}async promptSelection(){const e=new $e(u.t("jig.laylck.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(u.t("jig.laylck.invalidSelection"));const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return t.objectId}lockEntityLayer(e,t){const i=new te(e.doc.database).lockLayerByEntity(t);if(!i.ok)switch(i.reason){case"invalid_selection":this.showMessage(u.t("jig.laylck.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${u.t("jig.laylck.layerNotFound")}: ${i.layerName}`,"warning");return;case"already_locked":this.showMessage(`${u.t("jig.laylck.alreadyLocked")}: ${i.layerName}`,"info");return}e.view.selectionSet.clear(),this.showMessage(`${u.t("jig.laylck.locked")}: ${i.layerName}`,"success")}}class gc extends Te{constructor(){super(),this.mode=F.Write}async execute(e){const t=new te(e.doc.database).setAllLayersOn();if(e.view.selectionSet.clear(),t===0){this.showMessage(u.t("jig.layon.alreadyOn"));return}this.showMessage(`${u.t("jig.layon.turnedOn")}: ${t}`,"success")}}const vy={viewportMode:"Off",blockSelectionMode:"None"},et=class et extends Te{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=F.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=et._settings.viewportMode!=="Vpfreeze";;){const t=await this.promptSelection();if(!t)return;if(t.type==="keyword"){t.keyword==="Settings"?await this.runSettings():this.runUndo(e);continue}this.turnOffEntityLayer(e,t.objectId)}}addKeyword(e,t){e.keywords.add(u.t(`jig.layoff.keywords.${t}.display`),u.t(`jig.layoff.keywords.${t}.global`),u.t(`jig.layoff.keywords.${t}.local`))}async promptSelection(){const e=new $e(u.t("jig.layoff.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(u.t("jig.layoff.invalidSelection")),this.addKeyword(e,"settings"),this.addKeyword(e,"undo");const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===b.Keyword&&(t.stringResult==="Settings"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runSettings(){for(;;){const e=new ne(u.t("jig.layoff.settingsPrompt"));e.allowNone=!0,this.addKeyword(e,"viewports"),this.addKeyword(e,"blockSelection");const t=await k.instance.editor.getKeywords(e);if(t.status!==b.OK)return;const i=t.stringResult;if(!i)return;i==="Viewports"?await this.promptViewportMode():await this.promptBlockSelectionMode()}}async promptViewportMode(){const e=new ne(u.t("jig.layoff.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(u.t("jig.layoff.keywords.off.display"),u.t("jig.layoff.keywords.off.global"),u.t("jig.layoff.keywords.off.local")),i=e.keywords.add(u.t("jig.layoff.keywords.vpfreeze.display"),u.t("jig.layoff.keywords.vpfreeze.global"),u.t("jig.layoff.keywords.vpfreeze.local"));e.keywords.default=et._settings.viewportMode==="Vpfreeze"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;r&&(et._settings.viewportMode=r,r==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.showMessage(u.t("jig.layoff.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new ne(u.t("jig.layoff.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(u.t("jig.layoff.keywords.block.display"),u.t("jig.layoff.keywords.block.global"),u.t("jig.layoff.keywords.block.local")),i=e.keywords.add(u.t("jig.layoff.keywords.entity.display"),u.t("jig.layoff.keywords.entity.global"),u.t("jig.layoff.keywords.entity.local")),n=e.keywords.add(u.t("jig.layoff.keywords.none.display"),u.t("jig.layoff.keywords.none.global"),u.t("jig.layoff.keywords.none.local"));e.keywords.default=et._settings.blockSelectionMode==="Block"?t:et._settings.blockSelectionMode==="Entity"?i:n;const r=await k.instance.editor.getKeywords(e);if(r.status!==b.OK)return;const o=r.stringResult;o&&(et._settings.blockSelectionMode=o,this.showMessage(u.t("jig.layoff.nestedSelectionLimited")))}turnOffEntityLayer(e,t){const n=new te(e.doc.database).turnOffLayerByEntity(t);if(!n.ok){switch(n.reason){case"invalid_selection":this.showMessage(u.t("jig.layoff.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${u.t("jig.layoff.layerNotFound")}: ${n.layerName}`,"warning");return;case"cannot_change_current":this.showMessage(u.t("jig.layoff.cannotTurnOffCurrent"),"warning");return;case"already_off":this.showMessage(`${u.t("jig.layoff.alreadyOff")}: ${n.layerName}`,"info");return}return}et._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.showMessage(u.t("jig.layoff.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:n.layerName,wasOff:n.previousOff??!1}),e.view.selectionSet.clear(),this.showMessage(`${u.t("jig.layoff.turnedOff")}: ${n.layerName}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.showMessage(u.t("jig.layoff.nothingToUndo"),"warning");return}if(!new te(e.doc.database).setLayerOffByName(t.layerName,t.wasOff)){this.showMessage(`${u.t("jig.layoff.layerNotFound")}: ${t.layerName}`,"warning");return}e.view.selectionSet.clear(),this.showMessage(`${u.t("jig.layoff.restored")}: ${t.layerName}`,"success")}};et._settings={...vy};let $n=et;class fc extends Te{constructor(){super(),this.mode=F.Write}async execute(e){e.doc.restoreLayerPreviousState()?this.showMessage(u.t("jig.layerp.restored"),"success"):this.showMessage(u.t("jig.layerp.noPreviousState")),e.view.selectionSet.clear()}}class bc extends Te{constructor(){super(),this.mode=F.Write}async execute(e){const t=new te(e.doc.database).thawAllLayers();if(e.view.selectionSet.clear(),t===0){this.showMessage(u.t("jig.laythw.alreadyThawed"));return}this.showMessage(`${u.t("jig.laythw.thawed")}: ${t}`,"success")}}class wc extends Te{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.doc.unisolateLayers();if(t===void 0){this.showMessage(u.t("jig.layuniso.noPrevious"),"warning");return}if(e.view.selectionSet.clear(),t===0){this.showMessage(u.t("jig.layuniso.nothingRestored"));return}this.showMessage(`${u.t("jig.layuniso.restored")}: ${t}`,"success")}}class vc extends Te{constructor(){super(),this.mode=F.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.unlockEntityLayer(e,t)}}async promptSelection(){const e=new $e(u.t("jig.layulk.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(u.t("jig.layulk.invalidSelection"));const t=await k.instance.editor.getEntity(e);if(t.status===b.OK&&t.objectId)return t.objectId}unlockEntityLayer(e,t){const i=new te(e.doc.database).unlockLayerByEntity(t);if(!i.ok)switch(i.reason){case"invalid_selection":this.showMessage(u.t("jig.layulk.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${u.t("jig.layulk.layerNotFound")}: ${i.layerName}`,"warning");return;case"already_unlocked":this.showMessage(`${u.t("jig.layulk.alreadyUnlocked")}: ${i.layerName}`,"info");return}e.view.selectionSet.clear(),this.showMessage(`${u.t("jig.layulk.unlocked")}: ${i.layerName}`,"success")}}class kc extends z{async execute(e){ee.emit("close-layer-manager",{})}}class xc extends Te{constructor(){super(),this.mode=F.Write}async execute(e){for(;;){const t=await this.promptMainKeyword();if(!t)return;switch(t){case"?":this.listLayers(e);break;case"Make":await this.runMake(e);break;case"Set":await this.runSet(e);break;case"New":await this.runNew(e);break;case"On":await this.runOnOff(e,!1);break;case"Off":await this.runOnOff(e,!0);break;case"Color":await this.runColor(e);break;case"Freeze":await this.runFreeze(e,!0);break;case"Thaw":await this.runFreeze(e,!1);break;case"Lock":await this.runLock(e,!0);break;case"Unlock":await this.runLock(e,!1);break;case"Description":await this.runDescription(e);break}}}layerService(e){return new te(e.doc.database)}async promptMainKeyword(){const e=new ne(u.t("jig.layer.main"));e.allowNone=!0,this.addKeyword(e,"list"),this.addKeyword(e,"make"),this.addKeyword(e,"set"),this.addKeyword(e,"new"),this.addKeyword(e,"on"),this.addKeyword(e,"off"),this.addKeyword(e,"color"),this.addKeyword(e,"freeze"),this.addKeyword(e,"thaw"),this.addKeyword(e,"lock"),this.addKeyword(e,"unlock"),this.addKeyword(e,"description");const t=await k.instance.editor.getKeywords(e);if(t.status===b.OK)return t.stringResult}addKeyword(e,t){e.keywords.add(u.t(`jig.layer.keywords.${t}.display`),u.t(`jig.layer.keywords.${t}.global`),u.t(`jig.layer.keywords.${t}.local`))}listLayers(e){const t=this.layerService(e).getLayerSummaries();console.table(t),this.showMessage(`${u.t("jig.layer.listSummary")} (${t.length})`,"info")}async promptLayerNames(e,t){const i=new ce(e);i.allowSpaces=!1;const n=await k.instance.editor.getString(i);if(n.status!==b.OK)return;const o=this.layerService(t).parseLayerNameInput(n.stringResult??"");if(!o.length){this.showMessage(u.t("jig.layer.emptyInput"),"warning");return}return o}async promptSingleLayerName(e){const t=new ce(e);t.allowSpaces=!0;const i=await k.instance.editor.getString(t);return i.status!==b.OK?void 0:(i.stringResult??"").trim()||void 0}async runNew(e){const t=await this.promptLayerNames(u.t("jig.layer.newPrompt"),e);if(!t)return;const{created:i,existed:n}=this.layerService(e).createLayers(t);i>0&&this.showMessage(`${u.t("jig.layer.created")}: ${i}`,"success"),n.length>0&&this.showMessage(`${u.t("jig.layer.alreadyExists")}: ${n.join(", ")}`,"warning")}async runSet(e){const t=await this.promptSingleLayerName(u.t("jig.layer.setPrompt"));t&&(this.layerService(e).setCurrentLayer(t)||this.showMessage(`${u.t("jig.layer.notFound")}: ${t}`,"warning"))}async runMake(e){const t=await this.promptSingleLayerName(u.t("jig.layer.makePrompt"));t&&this.layerService(e).makeLayer(t)}async runOnOff(e,t){const i=await this.promptLayerNames(t?u.t("jig.layer.offPrompt"):u.t("jig.layer.onPrompt"),e);if(!i)return;const n=this.layerService(e),{missing:r}=n.resolveLayers(i);r.length>0&&this.showMessage(`${u.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const{skippedCurrent:o}=n.setLayersVisibility(i,t);o.length>0&&this.showMessage(u.t("jig.layer.cannotChangeCurrent"),"warning")}async runFreeze(e,t){const i=await this.promptLayerNames(t?u.t("jig.layer.freezePrompt"):u.t("jig.layer.thawPrompt"),e);if(!i)return;const n=this.layerService(e),{missing:r}=n.resolveLayers(i);r.length>0&&this.showMessage(`${u.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const{skippedCurrent:o}=n.setLayersFrozen(i,t);o.length>0&&this.showMessage(u.t("jig.layer.cannotChangeCurrent"),"warning")}async runLock(e,t){const i=await this.promptLayerNames(t?u.t("jig.layer.lockPrompt"):u.t("jig.layer.unlockPrompt"),e);if(!i)return;const n=this.layerService(e),{missing:r}=n.resolveLayers(i);r.length>0&&this.showMessage(`${u.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning"),n.setLayersLocked(i,t)}async runColor(e){const t=await this.promptLayerNames(u.t("jig.layer.colorLayerPrompt"),e);if(!t)return;const i=this.layerService(e),{layers:n,missing:r}=i.resolveLayers(t);if(r.length>0&&this.showMessage(`${u.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning"),n.length===0)return;const o=new ce(u.t("jig.layer.colorValuePrompt"));o.allowSpaces=!1;const a=await k.instance.editor.getString(o);if(a.status!==b.OK)return;const l=i.parseColorInput(a.stringResult??"");if(!l){this.showMessage(u.t("jig.layer.invalidColor"),"warning");return}i.setLayersColor(t,l)}async runDescription(e){const t=await this.promptSingleLayerName(u.t("jig.layer.descriptionLayerPrompt"));if(!t)return;const i=new ce(u.t("jig.layer.descriptionValuePrompt"));i.allowSpaces=!0,i.allowEmpty=!0;const n=await k.instance.editor.getString(i);n.status===b.OK&&(this.layerService(e).setLayerDescription(t,n.stringResult??"")||this.showMessage(`${u.t("jig.layer.notFound")}: ${t}`,"warning"))}}const ky={x:0,y:0,z:1},xy={x:0,y:0,z:-1};function Nr(s,e){return Math.atan2(e.y-s.y,e.x-s.x)*180/Math.PI}function Sc(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=t===1?Math.atan2(n,i):Math.atan2(n,-i);return d.AcGeMathUtil.normalizeAngle(r)}function bt(s){if(!s)return;const e=s.clockwise?-1:1,t={x:s.center.x,y:s.center.y,z:0};return{center:t,radius:s.radius,startAngle:Sc(t,{x:s.startPoint.x,y:s.startPoint.y},e),endAngle:Sc(t,{x:s.endPoint.x,y:s.endPoint.y},e),normalSign:e}}function Pc(s){return s===1?ky:xy}function Ac(s){return s.normal.z>=0?1:-1}function _i(s){return new d.AcDbArc(s.center,s.radius,s.startAngle,s.endAngle,Pc(s.normalSign))}function Cc(s,e){s.center=e.center,s.radius=e.radius,s.startAngle=e.startAngle,s.endAngle=e.endAngle,s.normal=Pc(e.normalSign)}function ze(s){return{center:{x:s.x,y:s.y,z:0},radius:1e-6,startAngle:0,endAngle:Math.PI/2,normalSign:1}}function _c(s,e,t,i=!1){return bt(d.AcGeCircArc2d.tryCreateByThreePoints(s,e,t,i))}function Ec(s,e,t,i){return bt(d.AcGeCircArc2d.tryCreateByCenterStartEnd(s,e,t,i===-1))}function Yn(s,e,t,i){return bt(d.AcGeCircArc2d.tryCreateByCenterStartProjectedEnd(s,e,t,i===-1))}function Ei(s,e,t){return bt(d.AcGeCircArc2d.tryCreateByCenterStartSweep(s,e,t))}function Li(s,e,t){return bt(d.AcGeCircArc2d.tryCreateByCenterStartChord(s,e,t))}function Rr(s,e,t){return bt(d.AcGeCircArc2d.tryCreateByStartEndAngle(s,e,t))}function Vr(s,e,t){return bt(d.AcGeCircArc2d.tryCreateByStartEndDirection(s,e,t))}function Gr(s,e,t){return bt(d.AcGeCircArc2d.tryCreateByStartEndRadius(s,e,t))}class Ti extends R{constructor(e,t,i){super(e),this._builder=t,this._arc=_i(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==Ac(this._arc)){this.end(),this._arc=_i(t);return}Cc(this._arc,t)}}}class Zt extends R{constructor(e,t,i){super(e),this._builder=t,this._arc=_i(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==Ac(this._arc)){this.end(),this._arc=_i(t);return}Cc(this._arc,t)}}}const Sy={"3p":"threePoint","3point":"threePoint",threepoint:"threePoint",startcenter:"startCenter",sc:"startCenter",startcenterend:"startCenterEnd",sce:"startCenterEnd",startcenterangle:"startCenterAngle",sca:"startCenterAngle",startcenterlength:"startCenterLength",startcenterchordlength:"startCenterLength",scl:"startCenterLength",startend:"startEnd",se:"startEnd",startendangle:"startEndAngle",sea:"startEndAngle",startenddirection:"startEndDirection",sed:"startEndDirection",startendradius:"startEndRadius",ser:"startEndRadius",center:"centerStart",c:"centerStart",centerstart:"centerStart",cs:"centerStart",centerstartend:"centerStartEnd",cse:"centerStartEnd",centerstartangle:"centerStartAngle",csa:"centerStartAngle",centerstartlength:"centerStartLength",centerstartchordlength:"centerStartLength",csl:"centerStartLength"};class Lc extends z{constructor(){super(),this.mode=F.Write}async execute(e){k.instance.editor.resetInputToggles();const t=this.consumeEntryMode();if(t!=="default"){await this.executeEntryMode(e,t);return}const i=new T(u.t("jig.arc.startPointOrCenter"));this.addKeyword(i,"center");const n=await k.instance.editor.getPoint(i);if(n.status===b.Keyword){n.stringResult==="Center"&&await this.runCenterStartFlow(e);return}n.status===b.OK&&await this.runStartFlow(e,n.value)}async executeEntryMode(e,t){switch(t){case"threePoint":await this.runExactThreePointFlow(e);return;case"startCenter":await this.runStartCenterFlowFromEntry(e);return;case"startCenterEnd":await this.runExactStartCenterFlow(e,"end");return;case"startCenterAngle":await this.runExactStartCenterFlow(e,"angle");return;case"startCenterLength":await this.runExactStartCenterFlow(e,"chordLength");return;case"startEnd":await this.runStartEndFlowFromEntry(e);return;case"startEndAngle":await this.runExactStartEndFlow(e,"angle");return;case"startEndDirection":await this.runExactStartEndFlow(e,"direction");return;case"startEndRadius":await this.runExactStartEndFlow(e,"radius");return;case"centerStart":await this.runCenterStartFlow(e);return;case"centerStartEnd":await this.runExactCenterStartFlow(e,"end");return;case"centerStartAngle":await this.runExactCenterStartFlow(e,"angle");return;case"centerStartLength":await this.runExactCenterStartFlow(e,"chordLength");return}}consumeEntryMode(){const e=k.instance.editor.peekScriptInput();if(e==null)return"default";const t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""),i=Sy[t];return i?(k.instance.editor.consumeScriptInput(),i):"default"}addKeyword(e,t){e.keywords.add(u.t(`jig.arc.keywords.${t}.display`),u.t(`jig.arc.keywords.${t}.global`),u.t(`jig.arc.keywords.${t}.local`))}appendArc(e,t){e.doc.database.tables.blockTable.modelSpace.appendEntity(_i(t))}warnInvalidGeometry(e){this.notify(u.t(`jig.arc.invalid.${e}`),"warning")}async promptStartPoint(){const e=new T(u.t("jig.arc.startPoint")),t=await k.instance.editor.getPoint(e);return t.status===b.OK?t.value:void 0}async promptCenterPoint(e){const t=new T(u.t("jig.arc.centerPoint"));e&&(t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new d.AcGePoint3d(e));const i=await k.instance.editor.getPoint(t);return i.status===b.OK?i.value:void 0}async promptEndPoint(e){const t=new T(u.t("jig.arc.endPoint"));e&&(t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new d.AcGePoint3d(e));const i=await k.instance.editor.getPoint(t);return i.status===b.OK?i.value:void 0}async promptSecondPoint(e){const t=new T(u.t("jig.arc.secondPoint"));t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new d.AcGePoint3d(e);const i=await k.instance.editor.getPoint(t);return i.status===b.OK?i.value:void 0}async runExactThreePointFlow(e){const t=await this.promptStartPoint();if(!t)return;const i=await this.promptSecondPoint(t);i&&await this.finishThreePointArc(e,t,i)}async runStartCenterFlowFromEntry(e){const t=await this.promptStartPoint();t&&await this.runStartCenterFlow(e,t)}async runExactStartCenterFlow(e,t){const i=await this.promptStartPoint();if(!i)return;const n=await this.promptCenterPoint(i);if(!n)return;if(t==="end"){await this.finishExactCenterStartEnd(e,n,i);return}if(t==="angle"){const c=new Se(u.t("jig.arc.includedAngle"));c.allowNegative=!0,c.allowZero=!1,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new d.AcGePoint3d(n),c.baseAngle=Nr(n,i),c.jig=new Zt(e.view,g=>Ei(n,i,this.applyCtrlDirectionValue(this.degToRad(g))),ze(i));const h=await k.instance.editor.getAngle(c),p=h.status===b.OK?h.value:void 0;if(p==null)return;const m=Ei(n,i,this.applyCtrlDirectionValue(this.degToRad(p)));m?this.appendArc(e,m):this.warnInvalidGeometry("angle");return}const r=new be(u.t("jig.arc.chordLength"));r.allowNegative=!0,r.allowZero=!1,r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new d.AcGePoint3d(i),r.jig=new Zt(e.view,c=>Li(n,i,this.applyCtrlDirectionValue(c)),ze(i));const o=await k.instance.editor.getDistance(r),a=o.status===b.OK?o.value:void 0;if(a==null)return;const l=Li(n,i,this.applyCtrlDirectionValue(a));l?this.appendArc(e,l):this.warnInvalidGeometry("chordLength")}async runExactCenterStartFlow(e,t){const i=await this.promptCenterPoint();if(!i)return;const n=await this.promptStartPointFromCenter(i);if(!n)return;if(t==="end"){await this.finishExactCenterStartEnd(e,i,n);return}if(t==="angle"){const c=new Se(u.t("jig.arc.includedAngle"));c.allowNegative=!0,c.allowZero=!1,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new d.AcGePoint3d(i),c.baseAngle=Nr(i,n),c.jig=new Zt(e.view,g=>Ei(i,n,this.applyCtrlDirectionValue(this.degToRad(g))),ze(n));const h=await k.instance.editor.getAngle(c),p=h.status===b.OK?h.value:void 0;if(p==null)return;const m=Ei(i,n,this.applyCtrlDirectionValue(this.degToRad(p)));m?this.appendArc(e,m):this.warnInvalidGeometry("angle");return}const r=new be(u.t("jig.arc.chordLength"));r.allowNegative=!0,r.allowZero=!1,r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new d.AcGePoint3d(n),r.jig=new Zt(e.view,c=>Li(i,n,this.applyCtrlDirectionValue(c)),ze(n));const o=await k.instance.editor.getDistance(r),a=o.status===b.OK?o.value:void 0;if(a==null)return;const l=Li(i,n,this.applyCtrlDirectionValue(a));l?this.appendArc(e,l):this.warnInvalidGeometry("chordLength")}async runExactStartEndFlow(e,t){const i=await this.promptStartPoint();if(!i)return;const n=await this.promptEndPoint(i);if(!n)return;if(t==="angle"){const c=new Se(u.t("jig.arc.includedAngle"));c.allowNegative=!0,c.allowZero=!1,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new d.AcGePoint3d(i),c.baseAngle=Nr(i,n),c.jig=new Zt(e.view,g=>Rr(i,n,this.applyCtrlDirectionValue(this.degToRad(g))),ze(i));const h=await k.instance.editor.getAngle(c),p=h.status===b.OK?h.value:void 0;if(p==null)return;const m=Rr(i,n,this.applyCtrlDirectionValue(this.degToRad(p)));m?this.appendArc(e,m):this.warnInvalidGeometry("angle");return}if(t==="direction"){const c=new T(u.t("jig.arc.tangentDirection"));c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new d.AcGePoint3d(i),c.jig=new Ti(e.view,f=>Vr(i,n,Math.atan2(f.y-i.y,f.x-i.x)),ze(i));const h=await k.instance.editor.getPoint(c),p=h.status===b.OK?h.value:void 0;if(!p)return;const m=Math.atan2(p.y-i.y,p.x-i.x),g=Vr(i,n,m);g?this.appendArc(e,g):this.warnInvalidGeometry("direction");return}const r=new be(u.t("jig.arc.radius"));r.allowNegative=!0,r.allowZero=!1,r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new d.AcGePoint3d(i),r.jig=new Zt(e.view,c=>Gr(i,n,this.applyCtrlDirectionValue(c)),ze(i));const o=await k.instance.editor.getDistance(r),a=o.status===b.OK?o.value:void 0;if(a==null)return;const l=Gr(i,n,this.applyCtrlDirectionValue(a));l?this.appendArc(e,l):this.warnInvalidGeometry("radius")}async runStartEndFlowFromEntry(e){const t=await this.promptStartPoint();t&&await this.runStartEndFlow(e,t)}async promptStartPointFromCenter(e){const t=new T(u.t("jig.arc.startPoint"));t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new d.AcGePoint3d(e);const i=await k.instance.editor.getPoint(t);return i.status===b.OK?i.value:void 0}async finishExactCenterStartEnd(e,t,i){const n=new T(u.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new d.AcGePoint3d(i),n.jig=new Ti(e.view,a=>Yn(t,i,a,this.applyCtrlDirectionSign(1)),ze(i));const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK)return;const o=Yn(t,i,r.value,this.applyCtrlDirectionSign(1));o?this.appendArc(e,o):this.warnInvalidGeometry("center")}getArcDirectionFactor(){return k.instance.editor.getInputToggles().ctrlArcFlip?-1:1}applyCtrlDirectionSign(e){return e*this.getArcDirectionFactor()}applyCtrlDirectionValue(e){return e*this.getArcDirectionFactor()}isCtrlDirectionFlipped(){return k.instance.editor.getInputToggles().ctrlArcFlip}async runStartFlow(e,t){const i=new T(u.t("jig.arc.secondPointOrOptions"));this.addKeyword(i,"center"),this.addKeyword(i,"end"),i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new d.AcGePoint3d(t);const n=await k.instance.editor.getPoint(i);if(n.status===b.OK){await this.finishThreePointArc(e,t,n.value);return}if(n.status===b.Keyword){if(n.stringResult==="Center"){await this.runStartCenterFlow(e,t);return}n.stringResult==="End"&&await this.runStartEndFlow(e,t)}}async finishThreePointArc(e,t,i){const n=new T(u.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new d.AcGePoint3d(t),n.jig=new Ti(e.view,a=>_c(t,i,a,this.isCtrlDirectionFlipped()),ze(t));const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK)return;const o=_c(t,i,r.value,this.isCtrlDirectionFlipped());o?this.appendArc(e,o):this.warnInvalidGeometry("threePoint")}async runCenterStartFlow(e){const t=new T(u.t("jig.arc.centerPoint")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK)return;const n=i.value,r=new T(u.t("jig.arc.startPoint"));r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new d.AcGePoint3d(n);const o=await k.instance.editor.getPoint(r);o.status===b.OK&&await this.finishCenterStartFlow(e,n,o.value)}async runStartCenterFlow(e,t){const i=new T(u.t("jig.arc.centerPoint"));i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new d.AcGePoint3d(t);const n=await k.instance.editor.getPoint(i);n.status===b.OK&&await this.finishCenterStartFlow(e,n.value,t)}async finishCenterStartFlow(e,t,i){const n=new T(u.t("jig.arc.endPointOrOptions"));this.addKeyword(n,"angle"),this.addKeyword(n,"chordLength"),n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new d.AcGePoint3d(i),n.jig=new Ti(e.view,o=>Yn(t,i,o,this.applyCtrlDirectionSign(1)),ze(i));const r=await k.instance.editor.getPoint(n);if(r.status===b.OK){const o=Yn(t,i,r.value,this.applyCtrlDirectionSign(1));o?this.appendArc(e,o):this.warnInvalidGeometry("center");return}if(r.status===b.Keyword){if(r.stringResult==="Angle"){const o=new ie(u.t("jig.arc.includedAngle"));o.allowZero=!1,o.allowNegative=!0;const a=await k.instance.editor.getDouble(o);if(a.status!==b.OK)return;const l=Ei(t,i,this.applyCtrlDirectionValue(this.degToRad(a.value)));l?this.appendArc(e,l):this.warnInvalidGeometry("angle");return}if(r.stringResult==="ChordLength"){const o=new be(u.t("jig.arc.chordLength"));o.allowZero=!1,o.allowNegative=!0,o.useBasePoint=!0,o.useDashedLine=!0,o.basePoint=new d.AcGePoint3d(i);const a=await k.instance.editor.getDistance(o);if(a.status!==b.OK)return;const l=Li(t,i,this.applyCtrlDirectionValue(a.value));l?this.appendArc(e,l):this.warnInvalidGeometry("chordLength")}}}async runStartEndFlow(e,t){const i=new T(u.t("jig.arc.endPoint"));i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new d.AcGePoint3d(t);const n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new T(u.t("jig.arc.centerPointOrOptions"));this.addKeyword(o,"angle"),this.addKeyword(o,"direction"),this.addKeyword(o,"radius"),o.useBasePoint=!0,o.useDashedLine=!0,o.basePoint=new d.AcGePoint3d(t),o.jig=new Ti(e.view,l=>Ec(l,t,r,this.applyCtrlDirectionSign(1)),ze(t));const a=await k.instance.editor.getPoint(o);if(a.status===b.OK){const l=Ec(a.value,t,r,this.applyCtrlDirectionSign(1));l?this.appendArc(e,l):this.warnInvalidGeometry("center");return}if(a.status===b.Keyword){if(a.stringResult==="Angle"){const l=new ie(u.t("jig.arc.includedAngle"));l.allowZero=!1,l.allowNegative=!0;const c=await k.instance.editor.getDouble(l);if(c.status!==b.OK)return;const h=Rr(t,r,this.applyCtrlDirectionValue(this.degToRad(c.value)));h?this.appendArc(e,h):this.warnInvalidGeometry("angle");return}if(a.stringResult==="Direction"){const l=new T(u.t("jig.arc.tangentDirection"));l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new d.AcGePoint3d(t);const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK)return;const h=c.value,p=Math.atan2(h.y-t.y,h.x-t.x),m=Vr(t,r,p);m?this.appendArc(e,m):this.warnInvalidGeometry("direction");return}if(a.stringResult==="Radius"){const l=new be(u.t("jig.arc.radius"));l.allowZero=!1,l.allowNegative=!0,l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new d.AcGePoint3d(t);const c=await k.instance.editor.getDistance(l);if(c.status!==b.OK)return;const h=Gr(t,r,this.applyCtrlDirectionValue(c.value));h?this.appendArc(e,h):this.warnInvalidGeometry("radius")}}}degToRad(e){return e*Math.PI/180}}function Tc(s){return{center:{x:s.x,y:s.y,z:0},radius:1e-6}}function Kr(s,e){s.keywords.add(u.t(`jig.circle.keywords.${e}.display`),u.t(`jig.circle.keywords.${e}.global`),u.t(`jig.circle.keywords.${e}.local`))}function Py(s,e){s.center=e.center,s.radius=e.radius}function Ur(s){if(s)return{center:{x:s.center.x,y:s.center.y,z:0},radius:s.radius}}function Ic(s,e){return Ur(d.AcGeCircArc2d.tryCreateCircle(s,e))}function Mc(s,e){return Ur(d.AcGeCircArc2d.tryCreateCircleByDiameter(s,e))}function Dc(s,e,t){return Ur(d.AcGeCircArc2d.tryCreateCircleByThreePoints(s,e,t))}class Hr extends R{constructor(e,t){super(e),this._circle=new d.AcDbCircle(t,0)}get entity(){return this._circle}update(e){this._circle.radius=e}}class Oc extends R{constructor(e,t,i){super(e),this._circle=new d.AcDbCircle(i.center,i.radius),this._builder=t}get entity(){return this._circle}update(e){const t=this._builder(e);t&&Py(this._circle,t)}}class Bc extends z{constructor(){super(),this.mode=F.Write}async execute(e){let t;class i{constructor(p,m){this.cmd=p,this.machine=m}buildPrompt(){const p=new T(u.t("jig.circle.centerOrOptions"));return Kr(p,"threeP"),Kr(p,"twoP"),p}async handleResult(p){if(p.status===b.OK)return t=await this.cmd.runCenterFlow(e,p.value),"finish";if(p.status!==b.Keyword)return"finish";const m=p.stringResult??"";return m==="3P"?(this.machine.setState(new o(this.cmd,this.machine)),"continue"):m==="2P"?(this.machine.setState(new n(this.cmd,this.machine)),"continue"):"finish"}}class n{constructor(p,m){this.cmd=p,this.machine=m}buildPrompt(){return new T(u.t("jig.circle.twoPointFirst"))}async handleResult(p){return p.status!==b.OK?"finish":(this.machine.setState(new r(this.cmd,p.value)),"continue")}}class r{constructor(p,m){this.cmd=p,this.firstPoint=m}buildPrompt(){const p=new T(u.t("jig.circle.twoPointSecond"));return p.useBasePoint=!0,p.useDashedLine=!0,p.basePoint=new d.AcGePoint3d(this.firstPoint),p.jig=new Oc(e.view,m=>Mc(this.firstPoint,m),Tc(this.firstPoint)),p}async handleResult(p){return p.status===b.OK&&(t=this.cmd.createFromTwoPoints(this.firstPoint,p.value)),"finish"}}class o{constructor(p,m){this.cmd=p,this.machine=m}buildPrompt(){return new T(u.t("jig.circle.threePointFirst"))}async handleResult(p){return p.status!==b.OK?"finish":(this.machine.setState(new a(this.cmd,this.machine,p.value)),"continue")}}class a{constructor(p,m,g){this.cmd=p,this.machine=m,this.firstPoint=g}buildPrompt(){const p=new T(u.t("jig.circle.threePointSecond"));return p.useBasePoint=!0,p.useDashedLine=!0,p.basePoint=new d.AcGePoint3d(this.firstPoint),p}async handleResult(p){return p.status!==b.OK?"finish":(this.machine.setState(new l(this.cmd,this.firstPoint,p.value)),"continue")}}class l{constructor(p,m,g){this.cmd=p,this.firstPoint=m,this.secondPoint=g}buildPrompt(){const p=new T(u.t("jig.circle.threePointThird"));return p.useBasePoint=!0,p.useDashedLine=!0,p.basePoint=new d.AcGePoint3d(this.secondPoint),p.jig=new Oc(e.view,m=>Dc(this.firstPoint,this.secondPoint,m),Tc(this.firstPoint)),p}async handleResult(p){return p.status===b.OK&&(t=this.cmd.createFromThreePoints(this.firstPoint,this.secondPoint,p.value)),"finish"}}const c=new Ye;c.setState(new i(this,c)),await c.run(h=>k.instance.editor.getPoint(h)),t&&e.doc.database.tables.blockTable.modelSpace.appendEntity(new d.AcDbCircle(t.center,t.radius))}async runCenterFlow(e,t){const i=new be(u.t("jig.circle.radiusOrDiameter"));Kr(i,"diameter"),i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new d.AcGePoint3d(t),i.jig=new Hr(e.view,t);const n=await k.instance.editor.getDistance(i);if(n.status===b.OK)return Ic(t,n.value??0);if(n.status===b.Keyword&&n.stringResult==="Diameter")return await this.promptDiameterCircle(e,t)}async promptDiameterCircle(e,t){const i=new be(u.t("jig.circle.diameter"));i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new d.AcGePoint3d(t),i.jig=new Hr(e.view,t);const n=await k.instance.editor.getDistance(i);if(n.status!==b.OK)return;const r=(n.value??0)/2;return Ic(t,r)}createFromTwoPoints(e,t){return Mc(e,t)}createFromThreePoints(e,t,i){return Dc(e,t,i)}}class jc extends R{constructor(e,t,i,n){super(e),this._dimBlockName="*UDIM",this._db=t,new d.AcDbDataGenerator(t).createArrowBlock(),this._dim=new d.AcDbAlignedDimension(i,n,i),this._dim.rotation=0}get entity(){return this._dim}update(e){this._dim.dimLinePoint=e,this._dim.rotation=this.calculateAngle(this._dim.xLine1Point,this._dim.xLine2Point),this._dim.dimensionText=this._dim.xLine1Point.distanceTo(this._dim.xLine2Point).toFixed(3);const t=this._dimBlockName;this._db.tables.blockTable.remove(t),this._db.tables.blockTable.add(this._dim.createDimBlock(t)),this._dim.dimBlockId=t}end(){super.end(),this._db.tables.blockTable.remove(this._dimBlockName)}calculateAngle(e,t){const i=t.x-e.x,n=t.y-e.y;return Math.atan2(n,i)}}class Fc extends z{constructor(){super(),this.mode=F.Review}async execute(e){const t=new T(u.t("jig.dimlinear.xLine1Point")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK)return;const n=i.value,r=new T(u.t("jig.dimlinear.xLine2Point"));r.useBasePoint=!0;const o=await k.instance.editor.getPoint(r);if(o.status!==b.OK)return;const a=o.value,l=new T(u.t("jig.dimlinear.dimLinePoint"));l.jig=new jc(e.view,e.doc.database,n,a);const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK)return;const h=c.value,p=e.doc.database,m=new d.AcDbAlignedDimension(n,a,h),g=this.getAvaiableDimBlockName(p);p.tables.blockTable.add(m.createDimBlock(g)),m.dimBlockId=g,p.tables.blockTable.modelSpace.appendEntity(m)}getAvaiableDimBlockName(e){const t=e.tables.blockTable.newIterator();let i=0;for(const n of t){const r=n.name;if(!r.startsWith("*D"))continue;const o=Number(r.slice(2));Number.isInteger(o)&&o>i&&(i=o)}return`*D${i+1}`}}class Zn extends R{constructor(e,t){super(e),this._line=new d.AcDbLine(t,t)}get entity(){return this._line}update(e){this._line.endPoint=e}}class At extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.doc.database,i=[],n=[],r=()=>!!At._lastEndpoint,o=()=>At._lastEndpoint?new d.AcGePoint3d(At._lastEndpoint):void 0,a=()=>{const x=c();x&&(At._lastEndpoint=new d.AcGePoint3d(x))},l=x=>{i.push(new d.AcGePoint3d(x))},c=()=>i[i.length-1],h=x=>{const S=c();if(!S)return;const P=new d.AcDbLine(new d.AcGePoint3d(S),x);t.tables.blockTable.modelSpace.appendEntity(P),n.push(P),e.view.addEntity(P),l(x)},p=()=>{if(n.length<=0||i.length<=1)return;const x=n.pop();x==null||x.erase(),x&&e.view.removeEntity(x),i.pop()},m=()=>{if(i.length<=1)return;const x=i[0],S=c();if(!S)return;x.x===S.x&&x.y===S.y&&x.z===S.z||h(x)},g=new T(r()?u.t("jig.line.firstPointOrContinue"):u.t("jig.line.firstPoint"));r()&&g.keywords.add(u.t("jig.line.keywords.continue.display"),u.t("jig.line.keywords.continue.global"),u.t("jig.line.keywords.continue.local"));const f=await k.instance.editor.getPoint(g);if(f.status===b.OK)l(f.value);else if(f.status===b.Keyword&&f.stringResult==="Continue"&&r())l(o());else return;class w{buildPrompt(){const S=new T(u.t("jig.line.nextPointWithOptions"));S.keywords.add(u.t("jig.line.keywords.undo.display"),u.t("jig.line.keywords.undo.global"),u.t("jig.line.keywords.undo.local")),i.length>1&&S.keywords.add(u.t("jig.line.keywords.close.display"),u.t("jig.line.keywords.close.global"),u.t("jig.line.keywords.close.local"));const P=c();return P&&(S.useDashedLine=!0,S.useBasePoint=!0,S.basePoint=new d.AcGePoint3d(P),S.jig=new Zn(e.view,P)),S.allowNone=!0,S}async handleResult(S){if(S.status===b.OK)return h(S.value),"continue";if(S.status===b.Keyword){const P=S.stringResult??"";return P==="Undo"?(p(),"continue"):P==="Close"&&i.length>1?(m(),"finish"):"continue"}return"finish"}}const v=new Ye;v.setState(new w),await v.run(x=>k.instance.editor.getPoint(x)),a()}}const Wr={x:0,y:0,z:1};function Xn(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function Ay(s,e){return{x:(s.x+e.x)/2,y:(s.y+e.y)/2,z:0}}function zc(s,e){const t=Math.hypot(s,e);if(!(!Number.isFinite(t)||d.AcGeTol.isNonPositive(t)))return{x:s/t,y:e/t,z:0}}function Cy(s){return{x:-s.y,y:s.x,z:0}}function $r(s){return s*Math.PI/180}function _y(s){return s*180/Math.PI}function Ey(s){return _y(Math.atan2(s.y,s.x))}function qn(s,e,t){const i=$r(s);return Math.atan2(e*Math.sin(i),t*Math.cos(i))}function Ly(s,e){return zc(e.x-s.x,e.y-s.y)}function Jn(s,e,t,i,n=0,r=d.TAU){if(!Number.isFinite(t)||!Number.isFinite(i)||d.AcGeTol.isNonPositive(t)||d.AcGeTol.isNonPositive(i))return;const o=Ty(n,r);return t>=i?{center:{x:s.x,y:s.y,z:0},majorAxis:e,majorRadius:t,minorRadius:i,startAngle:o.startAngle,endAngle:o.endAngle}:{center:{x:s.x,y:s.y,z:0},majorAxis:Cy(e),majorRadius:i,minorRadius:t,startAngle:o.startAngle,endAngle:o.endAngle}}function Ty(s,e){const t=Math.abs(e-s);return Math.abs(t-d.TAU)<1e-10||Math.abs(t-2*d.TAU)<1e-10?{startAngle:0,endAngle:0}:{startAngle:s,endAngle:e}}function Nc(s){return new d.AcDbEllipse(s,Wr,{x:1,y:0,z:0},1e-6,1e-6,0,d.TAU)}function Rc(s,e){s.center=e.center,s.normal=Wr,s.majorAxisRadius=e.majorRadius,s.minorAxisRadius=e.minorRadius,s.startAngle=e.startAngle,s.endAngle=e.endAngle;const t=s;t._geo&&(t._geo.majorAxis=e.majorAxis)}class Iy extends R{constructor(e,t,i){super(e),this._builder=t,this._ellipse=Nc(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&Rc(this._ellipse,t)}}class Yr extends R{constructor(e,t,i){super(e),this._builder=t,this._ellipse=Nc(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&Rc(this._ellipse,t)}}class Vc extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=new T(u.t("jig.ellipse.axisEndpointOrOptions"));this.addKeyword(t,"arc"),this.addKeyword(t,"center");const i=await k.instance.editor.getPoint(t);if(i.status===b.Keyword){const n=i.stringResult??"";n==="Center"?await this.runCenterFlow(e,!1):n==="Arc"&&await this.runArcEntryFlow(e);return}i.status===b.OK&&await this.runAxisEndFlow(e,i.value,!1)}addKeyword(e,t){e.keywords.add(u.t(`jig.ellipse.keywords.${t}.display`),u.t(`jig.ellipse.keywords.${t}.global`),u.t(`jig.ellipse.keywords.${t}.local`))}appendEllipse(e,t){const i=new d.AcDbEllipse(t.center,Wr,t.majorAxis,t.majorRadius,t.minorRadius,t.startAngle,t.endAngle);e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){this.notify(u.t(`jig.ellipse.invalid.${e}`),"warning")}async runArcEntryFlow(e){const t=new T(u.t("jig.ellipse.arcAxisEndpointOrCenter"));this.addKeyword(t,"center");const i=await k.instance.editor.getPoint(t);if(i.status===b.Keyword){i.stringResult==="Center"&&await this.runCenterFlow(e,!0);return}i.status===b.OK&&await this.runAxisEndFlow(e,i.value,!0)}async runCenterFlow(e,t){const i=new T(u.t("jig.ellipse.center")),n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new T(u.t("jig.ellipse.firstAxisEndpoint"));o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new d.AcGePoint3d(r),o.jig=new Zn(e.view,r);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)return;const l=Ly(r,a.value);if(!l){this.warnInvalidInput("axis");return}const c=Xn(r,a.value),h=await this.promptOtherAxis(e,r,l,c,t);h&&this.appendEllipse(e,h)}async runAxisEndFlow(e,t,i){const n=new T(u.t("jig.ellipse.secondAxisEndpoint"));n.useDashedLine=!0,n.useBasePoint=!0,n.basePoint=new d.AcGePoint3d(t),n.jig=new Zn(e.view,t);const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=o.x-t.x,l=o.y-t.y,c=zc(a,l);if(!c){this.warnInvalidInput("axis");return}const h=Ay(t,o),p=Xn(t,o)/2,m=await this.promptOtherAxis(e,h,c,p,i);m&&this.appendEllipse(e,m)}async promptOtherAxis(e,t,i,n,r){for(;;){const o=new T(u.t("jig.ellipse.otherAxisOrRotation"));this.addKeyword(o,"rotation"),o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new d.AcGePoint3d(t),o.jig=new Iy(e.view,h=>{const p=Xn(t,h);return Jn(t,i,n,p)},t);const a=await k.instance.editor.getPoint(o);if(a.status===b.Keyword){if(a.stringResult!=="Rotation")return;const h=new ie(u.t("jig.ellipse.rotationAngle"));h.allowNegative=!1,h.allowZero=!0,h.jig=new Yr(e.view,f=>{const w=n*Math.abs(Math.cos($r(f)));return Jn(t,i,n,w)},t);const p=await k.instance.editor.getDouble(h);if(p.status!==b.OK)return;const m=n*Math.abs(Math.cos($r(p.value??0))),g=Jn(t,i,n,m);if(!g){this.warnInvalidInput("rotation");continue}return r?await this.promptArcAngles(e,g):g}if(a.status!==b.OK)return;const l=Xn(t,a.value),c=Jn(t,i,n,l);if(!c){this.warnInvalidInput("otherAxis");continue}return r?await this.promptArcAngles(e,c):c}}async promptArcAngles(e,t){const i=Ey(t.majorAxis),n=new Se(u.t("jig.ellipse.arcStartAngle"));n.allowNegative=!0,n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new d.AcGePoint3d(t.center),n.baseAngle=i,n.jig=new Yr(e.view,c=>({...t,startAngle:qn(c,t.majorRadius,t.minorRadius),endAngle:d.TAU}),t.center);const r=await k.instance.editor.getAngle(n);if(r.status!==b.OK)return;const o=qn(r.value??0,t.majorRadius,t.minorRadius),a=new Se(u.t("jig.ellipse.arcEndAngle"));a.allowNegative=!0,a.useBasePoint=!0,a.useDashedLine=!0,a.basePoint=new d.AcGePoint3d(t.center),a.baseAngle=i,a.jig=new Yr(e.view,c=>({...t,startAngle:o,endAngle:qn(c,t.majorRadius,t.minorRadius)}),t.center);const l=await k.instance.editor.getAngle(a);if(l.status===b.OK)return{...t,startAngle:o,endAngle:qn(l.value??0,t.majorRadius,t.minorRadius)}}}const Bs=class Bs extends z{constructor(){super(),this.mode=F.Write}get settings(){return Bs._lastSettings}normalizeSysVarNumber(e,t){const i=Number(e);return Number.isFinite(i)?i:t}normalizePositiveSysVarNumber(e,t){const i=this.normalizeSysVarNumber(e,t);return i>0?i:t}sysVarRadiansToDegrees(e){return Math.round(e*180/Math.PI*1e6)/1e6}getSysVar(e,t,i){try{return e.getVar(t,i)}catch{return}}getDatabaseSysVarSettings(e){const t=this.settings;if(!(e instanceof d.AcDbDatabase))return t;try{const i=d.AcDbSysVarManager.instance(),n=this.getSysVar(i,d.AcDbSystemVariables.HPASSOC,e);return{...t,patternName:this.normalizePatternName(this.getSysVar(i,d.AcDbSystemVariables.HPNAME,e)??t.patternName),patternScale:this.normalizePositiveSysVarNumber(this.getSysVar(i,d.AcDbSystemVariables.HPSCALE,e),t.patternScale),patternAngleDeg:this.sysVarRadiansToDegrees(this.normalizeSysVarNumber(this.getSysVar(i,d.AcDbSystemVariables.HPANG,e),t.patternAngleDeg*Math.PI/180)),associative:n==null?t.associative:Number(n)!==0}}catch{return t}}getActiveSettings(){var e;return this.getDatabaseSysVarSettings((e=k.instance.curDocument)==null?void 0:e.database)}setActiveSysVar(e,t){var n;const i=(n=k.instance.curDocument)==null?void 0:n.database;i&&d.AcDbSysVarManager.instance().setVar(e,t,i)}normalizePatternName(e){const t=e.trim().toUpperCase();return t.length>0?t:d.HATCH_PATTERN_SOLID}styleToKeyword(e){switch(e){case d.AcDbHatchStyle.Outer:return"Outer";case d.AcDbHatchStyle.Ignore:return"Ignore";case d.AcDbHatchStyle.Normal:default:return"Normal"}}keywordToStyle(e){switch(e){case"Outer":return d.AcDbHatchStyle.Outer;case"Ignore":return d.AcDbHatchStyle.Ignore;case"Normal":default:return d.AcDbHatchStyle.Normal}}buildEdgesFromPolyline(e){var r;if(!e.closed||e.numberOfVertices<2)return[];const t=(r=e._geo)==null?void 0:r.vertices,i=t&&t.length>1?t.map(o=>({x:o.x,y:o.y,bulge:o.bulge})):Array.from({length:e.numberOfVertices},(o,a)=>{const l=e.getPoint2dAt(a);return{x:l.x,y:l.y,bulge:0}});if(i.length<2)return[];const n=[];for(let o=0;o<i.length;o++){const a=i[o],l=i[(o+1)%i.length],c=a.bulge??0;Math.abs(c)>1e-12?n.push(new d.AcGeCircArc2d(a,l,c)):n.push(new d.AcGeLine2d(a,l))}return n}buildEdgesFromEntity(e){if(e instanceof d.AcDbPolyline)return this.buildEdgesFromPolyline(e);if(e instanceof d.AcDbCircle){const t=e.center;return[new d.AcGeCircArc2d({x:t.x,y:t.y},e.radius,0,Math.PI*2,!1)]}if(e instanceof d.AcDbArc){if(!e.closed)return[];const t=e.center;return[new d.AcGeCircArc2d({x:t.x,y:t.y},e.radius,e.startAngle,e.endAngle,!1)]}return e instanceof d.AcDbLine?[new d.AcGeLine2d(e.startPoint,e.endPoint)]:[]}collectLoopsFromIds(e,t){const i=e.doc.database.tables.blockTable.modelSpace,n=[];return t.forEach(r=>{const o=i.getIdAt(r);o&&n.push(...this.buildEdgesFromEntity(o))}),this.buildLoopsFromEdges(n)}collectLoopsFromAllBoundaries(e){const t=e.doc.database.tables.blockTable.modelSpace,i=[];for(const n of t.newIterator())i.push(...this.buildEdgesFromEntity(n));return this.buildLoopsFromEdges(i)}buildLoopsFromEdges(e){if(e.length===0)return[];const t=[1e-6,1e-5,1e-4,.001];let i=[];for(const n of t){const r=d.AcGeLoop2d.buildFromEdges(e,n).filter(o=>o.closed&&o.numberOfEdges>0);r.length>i.length&&(i=r)}return i}signedArea(e){if(e.length<3)return 0;let t=0;for(let i=0,n=e.length-1;i<e.length;n=i++){const r=e[n],o=e[i];t+=r.x*o.y-o.x*r.y}return t*.5}isPointOnSegment(e,t,i,n,r,o,a=1e-8){const l=r-i,c=o-n,h=e-i,p=t-n;if(Math.abs(l*p-c*h)>a)return!1;const g=h*l+p*c;if(g<-a)return!1;const f=l*l+c*c;return!(g-f>a)}isPointInPolygon(e,t){if(t.length<3)return!1;for(let n=0,r=t.length-1;n<t.length;r=n++){const o=t[r],a=t[n];if(this.isPointOnSegment(e.x,e.y,o.x,o.y,a.x,a.y))return!0}let i=!1;for(let n=0,r=t.length-1;n<t.length;r=n++){const o=t[n].x,a=t[n].y,l=t[r].x,c=t[r].y;a>e.y!=c>e.y&&e.x<(l-o)*(e.y-a)/(c-a+Number.EPSILON)+o&&(i=!i)}return i}buildLoopInfos(e){const t=[];e.forEach(i=>{const n=i.getPoints(128).map(r=>({x:r.x,y:r.y}));n.length<3||t.push({loop:i,points:n,area:Math.abs(this.signedArea(n)),parent:null,children:[]})});for(let i=0;i<t.length;i++){const n=t[i].points[0];let r=null,o=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++)i!==a&&(t[a].area<=t[i].area||this.isPointInPolygon(n,t[a].points)&&t[a].area<o&&(o=t[a].area,r=a));t[i].parent=r,r!=null&&t[r].children.push(i)}return t}resolveLoopsForPickPoint(e,t){const i=this.buildLoopInfos(t);if(!i.length)return[];const n=i.map((a,l)=>this.isPointInPolygon(e,a.points)?l:-1).filter(a=>a>=0);if(!n.length)return[];n.sort((a,l)=>i[a].area-i[l].area);const r=n[0],o=new Set([r]);return this.settings.style!==d.AcDbHatchStyle.Ignore&&i[r].children.forEach(a=>o.add(a)),[...o].map(a=>i[a].loop)}appendHatch(e,t){if(!t.length)return!1;const i=new d.AcDbHatch;e.doc.database instanceof d.AcDbDatabase&&(i.database=e.doc.database);const n=this.getDatabaseSysVarSettings(e.doc.database),r=this.normalizePatternName(n.patternName),o=r===d.HATCH_PATTERN_SOLID;return i.patternName=r,i.patternType=d.AcDbHatchPatternType.Predefined,i.patternScale=n.patternScale,i.patternAngle=n.patternAngleDeg*Math.PI/180,i.hatchStyle=n.style,i.isSolidFill=o,this.configureHatch(i),t.forEach(a=>i.add(a)),e.doc.database.tables.blockTable.modelSpace.appendEntity(i),!0}configureHatch(e){}async promptPatternName(){const e=new ce(u.t("jig.hatch.patternName"));e.allowEmpty=!1;const t=this.getActiveSettings();e.defaultValue=t.patternName,e.useDefaultValue=!0;const i=await k.instance.editor.getString(e);if(i.status!==b.OK)return;const n=this.normalizePatternName(i.stringResult??e.defaultValue);this.settings.patternName=n,this.setActiveSysVar(d.AcDbSystemVariables.HPNAME,n)}async promptPatternScale(){const e=new ie(u.t("jig.hatch.scale"));e.allowNone=!0,e.allowNegative=!1,e.allowZero=!1;const t=this.getActiveSettings();e.defaultValue=t.patternScale,e.useDefaultValue=!0;const i=await k.instance.editor.getDouble(e);if(i.status!==b.OK)return;const n=i.value??e.defaultValue;n>0&&(this.settings.patternScale=n,this.setActiveSysVar(d.AcDbSystemVariables.HPSCALE,n))}async promptPatternAngle(){const e=new ie(u.t("jig.hatch.angle"));e.allowNone=!0,e.allowNegative=!0,e.allowZero=!0;const t=this.getActiveSettings();e.defaultValue=t.patternAngleDeg,e.useDefaultValue=!0;const i=await k.instance.editor.getDouble(e);if(i.status!==b.OK)return;const n=i.value??e.defaultValue;this.settings.patternAngleDeg=n,this.setActiveSysVar(d.AcDbSystemVariables.HPANG,n*Math.PI/180)}async promptStyle(){const e=this.getActiveSettings(),t=this.styleToKeyword(e.style),i=new ne(u.t("jig.hatch.style"));i.allowNone=!0;const n=i.keywords.add(u.t("jig.hatch.keywords.normal.display"),u.t("jig.hatch.keywords.normal.global"),u.t("jig.hatch.keywords.normal.local")),r=i.keywords.add(u.t("jig.hatch.keywords.outer.display"),u.t("jig.hatch.keywords.outer.global"),u.t("jig.hatch.keywords.outer.local")),o=i.keywords.add(u.t("jig.hatch.keywords.ignore.display"),u.t("jig.hatch.keywords.ignore.global"),u.t("jig.hatch.keywords.ignore.local"));i.keywords.default=t==="Outer"?r:t==="Ignore"?o:n;const a=await k.instance.editor.getKeywords(i);(a.status===b.OK||a.status===b.Keyword)&&a.stringResult&&(this.settings.style=this.keywordToStyle(a.stringResult))}async promptAssociative(){const e=this.getActiveSettings(),t=new ne(u.t("jig.hatch.associative"));t.allowNone=!0;const i=t.keywords.add(u.t("jig.hatch.keywords.yes.display"),u.t("jig.hatch.keywords.yes.global"),u.t("jig.hatch.keywords.yes.local")),n=t.keywords.add(u.t("jig.hatch.keywords.no.display"),u.t("jig.hatch.keywords.no.global"),u.t("jig.hatch.keywords.no.local"));t.keywords.default=e.associative?i:n;const r=await k.instance.editor.getKeywords(t);if(r.status===b.OK||r.status===b.Keyword){const o=r.stringResult==="Yes";this.settings.associative=o,this.setActiveSysVar(d.AcDbSystemVariables.HPASSOC,o?1:0)}}async doSelectObjects(e){const t=new Pt(u.t("jig.hatch.select")),i=await k.instance.editor.getSelection(t);if(i.status!==b.OK||!i.value)return!1;const n=this.collectLoopsFromIds(e,i.value.ids);return n.length?this.appendHatch(e,n):!1}async doPickPoints(e){const t=this.collectLoopsFromAllBoundaries(e);if(!t.length)return!1;let i=!1;for(;;){const n=new T(u.t("jig.hatch.pickPoint"));n.allowNone=!0;const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK||!r.value)break;const o=this.resolveLoopsForPickPoint(r.value,t);o.length&&this.appendHatch(e,o)&&(i=!0)}return i}async execute(e){let t=!0;for(;t;){const i=new $e(u.t("jig.hatch.prompt"));i.allowNone=!0,i.setRejectMessage(u.t("jig.hatch.invalidBoundary")),i.addAllowedClass("Polyline"),i.addAllowedClass("Circle"),i.addAllowedClass("Arc"),i.addAllowedClass("Line"),i.keywords.add(u.t("jig.hatch.keywords.pick.display"),u.t("jig.hatch.keywords.pick.global"),u.t("jig.hatch.keywords.pick.local")),i.keywords.add(u.t("jig.hatch.keywords.select.display"),u.t("jig.hatch.keywords.select.global"),u.t("jig.hatch.keywords.select.local")),i.keywords.add(u.t("jig.hatch.keywords.pattern.display"),u.t("jig.hatch.keywords.pattern.global"),u.t("jig.hatch.keywords.pattern.local")),i.keywords.add(u.t("jig.hatch.keywords.scale.display"),u.t("jig.hatch.keywords.scale.global"),u.t("jig.hatch.keywords.scale.local")),i.keywords.add(u.t("jig.hatch.keywords.angle.display"),u.t("jig.hatch.keywords.angle.global"),u.t("jig.hatch.keywords.angle.local")),i.keywords.add(u.t("jig.hatch.keywords.style.display"),u.t("jig.hatch.keywords.style.global"),u.t("jig.hatch.keywords.style.local")),i.keywords.add(u.t("jig.hatch.keywords.associative.display"),u.t("jig.hatch.keywords.associative.global"),u.t("jig.hatch.keywords.associative.local"));const n=await k.instance.editor.getEntity(i);if(n.status===b.OK&&n.objectId){const r=this.collectLoopsFromIds(e,[n.objectId]);if(!r.length)continue;this.appendHatch(e,r);continue}if(n.status===b.Keyword){const r=n.stringResult??"";r==="PickPoints"?await this.doPickPoints(e):r==="SelectObjects"?await this.doSelectObjects(e):r==="Pattern"?await this.promptPatternName():r==="Scale"?await this.promptPatternScale():r==="Angle"?await this.promptPatternAngle():r==="HatchStyle"?await this.promptStyle():r==="AssociativeMode"&&await this.promptAssociative();continue}t=!1}}};Bs._lastSettings={patternName:d.HATCH_PATTERN_SOLID,patternScale:1,patternAngleDeg:0,style:d.AcDbHatchStyle.Normal,associative:!0};let Qn=Bs;const My=".png,.jpg,.jpeg,.bmp,.gif,.tif,.tiff",Dy=100;function Oy(s,e){if(!s.objects.imageDefinition.has(e))return e;const t=e.lastIndexOf("."),i=t>0?e.slice(0,t):e,n=t>0?e.slice(t):"";let r=1;for(;s.objects.imageDefinition.has(`${i}_${r}${n}`);)r++;return`${i}_${r}${n}`}function By(s,e){const t=Math.max(1,s),i=Math.max(1,e),n=Math.max(t,i),r=n>0?Dy/n:1;return{width:Math.max(1,t*r),height:Math.max(1,i*r)}}async function jy(s){const e=URL.createObjectURL(s);try{return await new Promise((t,i)=>{const n=new Image;n.onload=()=>t({width:n.naturalWidth||100,height:n.naturalHeight||100}),n.onerror=()=>i(new Error("Failed to decode image")),n.src=e})}finally{URL.revokeObjectURL(e)}}function Fy(){return new Promise(s=>{const e=document.createElement("input");e.type="file",e.accept=My,e.style.display="none",document.body.appendChild(e);let t=!1;const i=o=>{t||(t=!0,e.removeEventListener("change",n),e.removeEventListener("cancel",r),e.remove(),s(o))},n=()=>{var o;return i((o=e.files)==null?void 0:o[0])},r=()=>i(void 0);e.addEventListener("change",n),e.addEventListener("cancel",r),e.click()})}class zy extends R{constructor(e,t,i,n){super(e),this._mode="point",this._position=new d.AcGePoint3d,this._scale=1,this._rotationRad=0,this._baseWidth=i,this._baseHeight=n,this._entity=new d.AcDbRasterImage,this._entity.image=t,this._entity.width=i,this._entity.height=n,this.applyGeometry()}get entity(){return this._entity}setMode(e){this._mode=e}setPosition(e){this._position=new d.AcGePoint3d(e),this.applyGeometry()}setScale(e){this._scale=e,this.applyGeometry()}setRotationRad(e){this._rotationRad=e,this.applyGeometry()}update(e){if(this._mode==="point"&&typeof e!="number"){this.setPosition(e);return}if(typeof e=="number"){if(this._mode==="scale"){this.setScale(e>0?e:this._scale);return}this._mode==="rotation"&&this.setRotationRad(e*Math.PI/180)}}applyGeometry(){this._entity.position=new d.AcGePoint3d(this._position),this._entity.width=Math.max(1e-6,this._baseWidth*this._scale),this._entity.height=Math.max(1e-6,this._baseHeight*this._scale),this._entity.rotation=this._rotationRad}}class Gc extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=await Fy();if(!t)return;let i;try{i=await jy(t)}catch{this.showMessage(u.t("jig.imageattach.decodeFailed"),"error");return}const n=By(i.width,i.height),r=new zy(e.view,t,n.width,n.height);try{r.setMode("point");const o=new T(u.t("jig.imageattach.insertionPoint"));o.jig=r;const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK||!a.value)return;const l=new d.AcGePoint3d(a.value);r.setPosition(l),r.setMode("scale");const c=new ie(u.t("jig.imageattach.scale"));c.allowNone=!0,c.allowNegative=!1,c.allowZero=!1,c.useDefaultValue=!0,c.defaultValue=1,c.jig=r;const h=await k.instance.editor.getDouble(c);if(h.status===b.Cancel||h.status===b.Error)return;const p=h.status===b.OK&&h.value!==void 0?h.value:1;if(!(p>0)){this.showMessage(u.t("jig.imageattach.invalidScale"),"warning");return}r.setScale(p),r.setMode("rotation");const m=new Se(u.t("jig.imageattach.rotation"));m.allowNone=!0,m.allowNegative=!0,m.allowZero=!0,m.useDefaultValue=!0,m.defaultValue=0,m.useBasePoint=!0,m.useDashedLine=!0,m.basePoint=l,m.jig=r;const g=await k.instance.editor.getAngle(m);if(g.status===b.Cancel||g.status===b.Error)return;const w=(g.status===b.OK&&g.value!==void 0?g.value:0)*Math.PI/180,v=e.doc.database,x=Oy(v,t.name),S=Math.max(1e-6,n.width*p),P=Math.max(1e-6,n.height*p);pt(v,"IMAGEATTACH",()=>{const A=new d.AcDbRasterImageDef;A.sourceFileName=t.name,v.objects.imageDefinition.setAt(x,A);const _=new d.AcDbRasterImage;_.position=l,_.width=S,_.height=P,_.rotation=w,_.image=t,_.imageDefId=A.objectId,v.tables.blockTable.modelSpace.appendEntity(_)})}finally{r.end()}}}const Ro=class Ro{static set(e){this._options={...e}}static consume(){const e=this._options;return this._options=null,e}static clear(){this._options=null}};Ro._options=null;let es=Ro;function Kc(s){const e=s.trim();return!e||/[\r\n]/.test(e)?!1:!e.startsWith("*")}class Ny extends R{constructor(e,t){super(e),this._mode="point",this._position=new d.AcGePoint3d,this._scaleX=1,this._scaleY=1,this._scaleZ=1,this._rotationRad=0,this._entity=new d.AcDbBlockReference(t),this.applyGeometry()}get entity(){return this._entity}setMode(e){this._mode=e}setPosition(e){this._position=new d.AcGePoint3d(e),this.applyGeometry()}setUniformScale(e){this._scaleX=e,this._scaleY=e,this._scaleZ=e,this.applyGeometry()}setScaleFactors(e,t,i){this._scaleX=e,this._scaleY=t,this._scaleZ=i,this.applyGeometry()}setRotationRad(e){this._rotationRad=e,this.applyGeometry()}update(e){if(this._mode==="point"&&typeof e!="number"){this.setPosition(e);return}if(typeof e=="number"){if(this._mode==="scale"){this.setUniformScale(e>0?e:this._scaleX);return}this._mode==="rotation"&&this.setRotationRad(e*Math.PI/180)}}applyGeometry(){this._entity.position=new d.AcGePoint3d(this._position),this._entity.scaleFactors=new d.AcGePoint3d(this._scaleX,this._scaleY,this._scaleZ),this._entity.rotation=this._rotationRad}}class Uc extends z{constructor(){super(),this.mode=F.Write}async execute(e){const i=e.doc.database.tables.blockTable,n=es.consume(),r=new ce(u.t("jig.insert.blockName")),o=await k.instance.editor.getString(r);if(o.status!==b.OK)return;const a=String(o.stringResult??"").trim();if(!Kc(a)){this.showMessage(u.t("jig.insert.invalidBlockName"),"warning");return}if(!i.has(a)){this.showMessage(`${u.t("jig.insert.blockNotFound")}: ${a}`,"warning");return}const l=i.getAt(a);if(l!=null&&l.isXref){this.showMessage(u.t("jig.insert.xrefNotAllowed"),"warning");return}const c=new Ny(e.view,a);try{do if(!await this.placeOne(e,a,c,n))return;while(n!=null&&n.repeatPlacement)}finally{c.end()}}async placeOne(e,t,i,n){const r=e.doc.database;i.setMode("point");const o=new T(u.t("jig.insert.insertionPoint"));o.jig=i;const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK||!a.value)return!1;const l=new d.AcGePoint3d(a.value);i.setPosition(l);let c=1,h=1,p=1;if(!((n==null?void 0:n.specifyScale)!==!1)&&n)c=Zr(n.scaleX,1),h=Zr(n.scaleY,c),p=Zr(n.scaleZ,c),i.setScaleFactors(c,h,p);else{i.setMode("scale");const v=new ie(u.t("jig.insert.scale"));v.allowNone=!0,v.allowNegative=!1,v.allowZero=!1,v.useDefaultValue=!0,v.defaultValue=1,v.jig=i;const x=await k.instance.editor.getDouble(v);if(x.status===b.Cancel||x.status===b.Error)return!1;const S=x.status===b.OK&&x.value!==void 0?x.value:1;if(!(S>0))return this.showMessage(u.t("jig.insert.invalidScale"),"warning"),!1;c=h=p=S,i.setUniformScale(S)}let g=0;if(!((n==null?void 0:n.specifyRotation)!==!1)&&n)g=Number.isFinite(n.rotationDeg)?n.rotationDeg:0,i.setRotationRad(g*Math.PI/180);else{i.setMode("rotation");const v=new Se(u.t("jig.insert.rotation"));v.allowNone=!0,v.allowNegative=!0,v.allowZero=!0,v.useDefaultValue=!0,v.defaultValue=0,v.useBasePoint=!0,v.useDashedLine=!0,v.basePoint=l,v.jig=i;const x=await k.instance.editor.getAngle(v);if(x.status===b.Cancel||x.status===b.Error)return!1;g=x.status===b.OK&&x.value!==void 0?x.value:0}const w=g*Math.PI/180;return pt(r,"INSERT",()=>{const v=new d.AcDbBlockReference(t);v.position=l,v.scaleFactors=new d.AcGePoint3d(c,h,p),v.rotation=w,r.tables.blockTable.modelSpace.appendEntity(v)}),!0}}function Zr(s,e){return s!==void 0&&s>0?s:e}class Hc extends R{constructor(e,t,i){if(super(e),this._mline=new d.AcDbMLine,this._points=t,this._resolveState=i,t.length>0){const n=this._resolveState();Xr(this._mline,t,n.styleName,n.justification,n.scale,!1,n.elementOffsets)}}get entity(){return this._mline}update(e){if(this._points.length<=0)return;const t=[...this._points,new d.AcGePoint3d(e)],i=this._resolveState();Xr(this._mline,t,i.styleName,i.justification,i.scale,!1,i.elementOffsets)}}class Wc extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.doc.database;let i=d.AcDbMLineJustification.Zero,n=t.cmlscale??1,r=t.cmlstyle||"STANDARD";const o=[];let a=!1;const l=()=>{const A=t.objects.mlineStyle.getAt(r);return Ky((A==null?void 0:A.elements)??[],i,n)},c=A=>o.push(new d.AcGePoint3d(A)),h=()=>{o.length>1&&o.pop()},p=()=>{if(o.length<=1)return;const A=o[0],_=o[o.length-1];Hy(A,_)||c(A),a=!0},m=async()=>{const A=new ne(u.t("jig.mline.justificationPrompt"));A.allowNone=!0,A.keywords.add(u.t("jig.mline.keywords.top.display"),u.t("jig.mline.keywords.top.global"),u.t("jig.mline.keywords.top.local")),A.keywords.add(u.t("jig.mline.keywords.zero.display"),u.t("jig.mline.keywords.zero.global"),u.t("jig.mline.keywords.zero.local")),A.keywords.add(u.t("jig.mline.keywords.bottom.display"),u.t("jig.mline.keywords.bottom.global"),u.t("jig.mline.keywords.bottom.local"));const _=await k.instance.editor.getKeywords(A);if(_.status===b.None)return!0;if(_.status!==b.Keyword)return!1;const C=_.stringResult??"";return C==="Top"?i=d.AcDbMLineJustification.Top:C==="Bottom"?i=d.AcDbMLineJustification.Bottom:i=d.AcDbMLineJustification.Zero,!0},g=async()=>{const A=new ie(u.t("jig.mline.scalePrompt"));A.allowNone=!0,A.allowZero=!0,A.allowNegative=!0,A.useDefaultValue=!0,A.defaultValue=n;const _=await k.instance.editor.getDouble(A);return _.status===b.None?!0:_.status!==b.OK?!1:(n=_.value??n,!0)},f=()=>{const A=[...t.objects.mlineStyle.entries()].map(([_])=>_);if(A.length<=0){this.showMessage(u.t("jig.mline.styleListEmpty"),"warning");return}this.showMessage(`${u.t("jig.mline.styleListHeader")} ${A.join(", ")}`,"info")},w=async()=>{for(;;){const A=new ce(u.t("jig.mline.stylePrompt"));A.allowEmpty=!1,A.allowSpaces=!1;const _=await k.instance.editor.getString(A);if(_.status!==b.OK)return!1;const C=(_.stringResult??"").trim();if(C){if(C==="?"){f();continue}return r=C,!0}}},v=async A=>A==="Justification"?await m():A==="Scale"?await g():A==="Style"?await w():!0;for(;;){const A=new T(u.t("jig.mline.startPointWithOptions"));A.keywords.add(u.t("jig.mline.keywords.justification.display"),u.t("jig.mline.keywords.justification.global"),u.t("jig.mline.keywords.justification.local")),A.keywords.add(u.t("jig.mline.keywords.scale.display"),u.t("jig.mline.keywords.scale.global"),u.t("jig.mline.keywords.scale.local")),A.keywords.add(u.t("jig.mline.keywords.style.display"),u.t("jig.mline.keywords.style.global"),u.t("jig.mline.keywords.style.local"));const _=await k.instance.editor.getPoint(A);if(_.status===b.OK){c(_.value);break}if(_.status!==b.Keyword||!await v(_.stringResult??""))return}class x{buildPrompt(){const _=new T(u.t("jig.mline.nextPointWithOptions"));return _.keywords.add(u.t("jig.mline.keywords.justification.display"),u.t("jig.mline.keywords.justification.global"),u.t("jig.mline.keywords.justification.local")),_.keywords.add(u.t("jig.mline.keywords.scale.display"),u.t("jig.mline.keywords.scale.global"),u.t("jig.mline.keywords.scale.local")),_.keywords.add(u.t("jig.mline.keywords.style.display"),u.t("jig.mline.keywords.style.global"),u.t("jig.mline.keywords.style.local")),_.keywords.add(u.t("jig.mline.keywords.undo.display"),u.t("jig.mline.keywords.undo.global"),u.t("jig.mline.keywords.undo.local")),o.length>1&&_.keywords.add(u.t("jig.mline.keywords.close.display"),u.t("jig.mline.keywords.close.global"),u.t("jig.mline.keywords.close.local")),_.useDashedLine=!0,_.useBasePoint=!0,_.basePoint=new d.AcGePoint3d(o[o.length-1]),_.jig=new Hc(e.view,o,()=>({justification:i,scale:n,styleName:r,elementOffsets:l()})),_.allowNone=!0,_}async handleResult(_){if(_.status===b.OK)return c(_.value),"continue";if(_.status!==b.Keyword)return"finish";const C=_.stringResult??"";return C==="Undo"?(h(),"continue"):C==="Close"&&o.length>1?(p(),"finish"):await v(C)?"continue":"finish"}}const S=new Ye;if(S.setState(new x),await S.run(A=>k.instance.editor.getPoint(A)),o.length<2)return;const P=new d.AcDbMLine;Xr(P,o,r,i,n,a,l()),t.tables.blockTable.modelSpace.appendEntity(P),t.cmlstyle=r,t.cmlscale=n}}function Xr(s,e,t,i,n,r,o){if(e.length<=0){s.clearSegments();return}if(s.styleName=t,s.styleObjectHandle="",s.justification=i,s.scale=n,s.styleCount=o.length,s.closed=r,s.startPosition=e[0],e.length<2){s.clearSegments();return}s.segments=Ry(e,o)}function Ry(s,e){const t=Vy(s);return s.slice(1).map((i,n)=>{const r=n+1,o=Gy(t,r);return{position:i,direction:t[Math.min(r,t.length-1)],miterDirection:o.direction,elements:e.map(a=>({parameterCount:1,parameters:[a*o.offsetScale],fillCount:0,fillParameters:[]}))}})}function Vy(s){const e=[];for(let t=0;t<s.length-1;t++){const i=s[t],n=s[t+1],r=qr({x:n.x-i.x,y:n.y-i.y,z:n.z-i.z});e.push(r??{x:1,y:0,z:0})}return e}function Gy(s,e){if(s.length<=0)return{direction:{x:0,y:1,z:0},offsetScale:1};if(e<=0)return{direction:ts(s[0]),offsetScale:1};if(e>=s.length)return{direction:ts(s[s.length-1]),offsetScale:1};const t=ts(s[e-1]),i=ts(s[e]),n=qr({x:t.x+i.x,y:t.y+i.y,z:t.z+i.z});if(!n)return{direction:i,offsetScale:1};const r=Math.abs(Uy(n,i));return d.AcGeTol.isNonPositive(r)?{direction:n,offsetScale:1}:{direction:n,offsetScale:1/r}}function Ky(s,e,t){if(s.length<=0)return[];let i=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(const o of s)o.offset<i&&(i=o.offset),o.offset>n&&(n=o.offset);let r=0;return e===d.AcDbMLineJustification.Top?r=-n:e===d.AcDbMLineJustification.Bottom&&(r=-i),s.map(o=>(o.offset+r)*t)}function ts(s){return qr({x:-s.y,y:s.x,z:0})??{x:0,y:1,z:0}}function qr(s){const e=Math.sqrt(s.x*s.x+s.y*s.y+s.z*s.z);if(d.AcGeTol.isPositive(e))return{x:s.x/e,y:s.y/e,z:s.z/e}}function Uy(s,e){return s.x*e.x+s.y*e.y+s.z*e.z}function Hy(s,e){return d.DEFAULT_TOL.equalPoint3d(s,e)}class $c extends z{constructor(){super(),this.mtextEditor=new He,this.mode=F.Write}async execute(e){const t=new Bn(u.t("main.inputManager.firstCorner"),u.t("main.inputManager.secondCorner"));t.useBasePoint=!1,t.useDashedLine=!1;const i=await k.instance.editor.getBox(t);if(i.status!==b.OK||!i.value)return;const n=i.value,r=Math.max(Math.abs(n.max.x-n.min.x),1e-4),o=e.view,a=this.pixelsToWorldY(o,24),l={x:n.min.x,y:n.max.y,z:0},c=Array.from(new Set(k.instance.avaiableFonts.flatMap(g=>g.name).map(g=>g.trim()).filter(g=>g.length>0))),h=await this.mtextEditor.open({view:o,location:l,width:r,textHeight:a,toolbarFontFamilies:c});if(!h||!h.contents.trim())return;const m=new d.AcDbMText;m.location=h.location,m.contents=h.contents,m.width=h.width,m.height=h.height,m.lineSpacingFactor=h.lineSpacingFactor,m.attachmentPoint=h.attachmentPoint,e.doc.database.tables.blockTable.modelSpace.appendEntity(m)}pixelsToWorldY(e,t){const i=e.screenToWorld({x:0,y:0}),n=e.screenToWorld({x:0,y:t});return Math.max(Math.abs(n.y-i.y),1e-4)}}class Yc extends z{constructor(){super(),this.mode=F.Write}async execute(e){for(;;){const t=new T(u.t("jig.point.point")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK||!i.value)return;const n=new d.AcDbPoint;n.position=new d.AcGePoint3d(i.value),e.doc.database.tables.blockTable.modelSpace.appendEntity(n)}}}const Wy=3,$y=1024;function Yy(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function Jr(s,e){s.reset(!1),e.forEach((t,i)=>s.addVertexAt(i,t)),s.closed=!0}function Zc(s,e,t,i){const n=Yy(s,t);if(d.AcGeTol.isNonPositive(n))return;const r=Math.PI*2/e,o=Math.atan2(t.y-s.y,t.x-s.x),a=i==="Inscribed"?n:n/Math.cos(Math.PI/e);if(!Number.isFinite(a)||d.AcGeTol.isNonPositive(a))return;const l=i==="Inscribed"?o:o+r/2,c=[];for(let h=0;h<e;h++){const p=l+h*r;c.push(new d.AcGePoint2d(s.x+a*Math.cos(p),s.y+a*Math.sin(p)))}return c}function Xc(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=Math.hypot(i,n);if(d.AcGeTol.isNonPositive(r))return;const o=Math.PI*2/t,a=[new d.AcGePoint2d(s),new d.AcGePoint2d(e)];let l=e.x,c=e.y,h=i,p=n;for(let m=2;m<t;m++){const g=h*Math.cos(o)-p*Math.sin(o),f=h*Math.sin(o)+p*Math.cos(o);l+=g,c+=f,a.push(new d.AcGePoint2d(l,c)),h=g,p=f}return a}class Zy extends R{constructor(e,t,i,n){super(e),this._polyline=new d.AcDbPolyline,this._center=t,this._sides=i,this._modeProvider=n}get entity(){return this._polyline}update(e){const t=Zc(this._center,this._sides,e,this._modeProvider());t&&Jr(this._polyline,t)}}class Xy extends R{constructor(e,t,i){super(e),this._polyline=new d.AcDbPolyline,this._firstPoint=t,this._sides=i}get entity(){return this._polyline}update(e){const t=Xc(this._firstPoint,e,this._sides);t&&Jr(this._polyline,t)}}const Qi=class Qi extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=await this.promptSides();if(t==null)return;const i=new T(u.t("jig.polygon.centerOrEdge"));this.addKeyword(i,"edge");const n=await k.instance.editor.getPoint(i);if(n.status===b.Keyword){n.stringResult==="Edge"&&await this.runEdgeFlow(e,t);return}n.status===b.OK&&await this.runCenterFlow(e,t,n.value)}addKeyword(e,t){e.keywords.add(u.t(`jig.polygon.keywords.${t}.display`),u.t(`jig.polygon.keywords.${t}.global`),u.t(`jig.polygon.keywords.${t}.local`))}appendPolygon(e,t){const i=new d.AcDbPolyline;Jr(i,t),e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){this.notify(u.t(`jig.polygon.invalid.${e}`),"warning")}async promptSides(){for(;;){const e=Qi._lastSides,t=new ce(u.t("jig.polygon.numberOfSides"));t.allowEmpty=!0,t.allowSpaces=!1,t.defaultValue=String(e),t.useDefaultValue=!0;const i=await k.instance.editor.getString(t);if(i.status!==b.OK)return;const n=(i.stringResult??"").trim(),r=n===""?e:Number(n);if(Number.isInteger(r)&&r>=Wy&&r<=$y)return Qi._lastSides=r,r;this.warnInvalidInput("sides")}}async runCenterFlow(e,t,i){let n="Inscribed";for(;;){const r=new T(u.t("jig.polygon.radiusOrType"));this.addKeyword(r,"inscribed"),this.addKeyword(r,"circumscribed"),r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new d.AcGePoint3d(i),r.jig=new Zy(e.view,i,t,()=>n);const o=await k.instance.editor.getPoint(r);if(o.status===b.Keyword){const l=o.stringResult??"";if(l==="Inscribed"){n="Inscribed";continue}if(l==="Circumscribed"){n="Circumscribed";continue}return}if(o.status!==b.OK)return;const a=Zc(i,t,o.value,n);if(!a){this.warnInvalidInput("radius");continue}this.appendPolygon(e,a);return}}async runEdgeFlow(e,t){const i=new T(u.t("jig.polygon.edgeStart")),n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new T(u.t("jig.polygon.edgeEnd"));o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new d.AcGePoint3d(r),o.jig=new Xy(e.view,r,t);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)return;const l=Xc(r,a.value,t);if(!l){this.warnInvalidInput("edge");return}this.appendPolygon(e,l)}};Qi._lastSides=4;let is=Qi;class qc extends R{constructor(e,t,i,n,r){super(e),this._hasTemp=!1,this._polyline=new d.AcDbPolyline,this._points=t,this._bulges=i,this._currentBulge=n,this._bulgeProvider=r,this._baseCount=t.length,this._appliedBulge=this._bulges[this._baseCount-1],this.addBaseVertices()}get entity(){return this._polyline}update(e){var r;if(this._baseCount===0)return;this._hasTemp&&(this._polyline.removeVertexAt(this._baseCount),this._hasTemp=!1);const t=this._baseCount-1,n=((r=this._bulgeProvider)==null?void 0:r.call(this,e))??this._currentBulge??this._bulges[t];if(n!==this._appliedBulge){const o=this._points[t];this._polyline.removeVertexAt(t),this._polyline.addVertexAt(t,o,n),this._appliedBulge=n}this._polyline.addVertexAt(this._baseCount,new d.AcGePoint2d(e),void 0),this._hasTemp=!0}addBaseVertices(){this._points.forEach((e,t)=>this._polyline.addVertexAt(t,e,this._bulges[t]))}}class qy extends R{constructor(e,t,i){super(e),this._polyline=new d.AcDbPolyline,t.forEach((n,r)=>this._polyline.addVertexAt(r,n,i[r]))}get entity(){return this._polyline}update(e){}}class Jc extends z{constructor(){super(),this.mode=F.Write}complementBulge(e){if(d.AcGeTol.equalToZero(e))return e;const t=4*Math.atan(e),n=(Math.sign(t)||1)*(Math.PI*2-Math.abs(t));return d.AcGeTol.equalToZero(n)?e:Math.tan(n/4)}flipArcBulgeForCtrl(e){return-this.complementBulge(e)}computeArcCenterFromBulge(e,t,i){const n=t.x-e.x,r=t.y-e.y,o=Math.hypot(n,r);if(d.AcGeTol.isNonPositive(o))return;const a=(e.x+t.x)/2,l=(e.y+t.y)/2,c=-r/o,h=n/o,p=o/2*i;return{x:a+c*p,y:l+h*p}}getGeometricTangentAtPoint(e,t,i){const n=e.x-t.x,r=e.y-t.y;return i?Math.atan2(-r,n):Math.atan2(r,-n)}getArcTangentAtEnd(e,t,i){const n=this.computeArcCenterFromBulge(e,t,i);if(n)return this.getGeometricTangentAtPoint(t,n,i>=0)}getIncomingTangentRadians(e,t){if(e.length<2)return 0;const i=e[e.length-1],n=e[e.length-2],r=t[e.length-2];return r==null||d.AcGeTol.equalToZero(r)?Math.atan2(i.y-n.y,i.x-n.x):this.getArcTangentAtEnd(n,i,r)??Math.atan2(i.y-n.y,i.x-n.x)}computeBulgeFromTangentDirection(e,t,i){const n=Math.cos(i),r=Math.sin(i),o=t.x-e.x,a=t.y-e.y,l=-r,c=n,h=2*(o*l+a*c);if(d.AcGeTol.equalToZero(h))return;const p=(o*o+a*a)/h;if(!Number.isFinite(p))return;const m={x:e.x+l*p,y:e.y+c*p};return this.computeBulgeFromCenterWithTangent(e,t,m,i)}computeBulgeFromCenterWithTangent(e,t,i,n){const r=e.x-i.x,o=e.y-i.y,a=t.x-i.x,l=t.y-i.y,c=Math.cos(n),h=Math.sin(n),p=t.x-e.x,m=t.y-e.y,g=r*h-o*c;let f;d.AcGeTol.isPositive(Math.abs(g))?f=g>0:f=p*h-m*c>=0;const w=Math.atan2(o,r),v=Math.atan2(l,a);let x;if(f?(x=v-w,d.AcGeTol.isNonPositive(x)&&(x+=Math.PI*2)):(x=w-v,d.AcGeTol.isNonPositive(x)&&(x+=Math.PI*2)),!!d.AcGeTol.great(d.TAU-x,0))return f?Math.tan(x/4):-Math.tan(x/4)}computeBulgeFromTangentAndIncludedAngle(e,t,i,n){const r=Math.cos(i),o=Math.sin(i),a=t.x-e.x,l=t.y-e.y,c=-o,h=r,p=2*(a*c+l*h);if(d.AcGeTol.equalToZero(p))return;const m=(a*a+l*l)/p;if(!Number.isFinite(m))return;const g={x:e.x+c*m,y:e.y+h*m},f=this.computeBulgeFromCenterWithTangent(e,t,g,i);if(f==null)return;const w=Math.tan(n/4);if(Number.isFinite(w))return Math.sign(f)*Math.abs(w)}computeBulgeFromCenter(e,t,i){const n=e.x-i.x,r=e.y-i.y,o=t.x-i.x,a=t.y-i.y,l=n*a-r*o,c=n*o+r*a,h=Math.atan2(l,c);if(Number.isFinite(h))return Math.tan(h/4)}computeCircleCenter(e,t,i){const n=e.x,r=e.y,o=t.x,a=t.y,l=i.x,c=i.y,h=n-o,p=r-a,m=n-l,g=r-c,f=(n*n-o*o+r*r-a*a)/2,w=(n*n-l*l+r*r-c*c)/2,v=h*g-p*m;if(d.AcGeTol.equalToZero(v))return;const x=(g*f-p*w)/v,S=(-m*f+h*w)/v;return new d.AcGePoint2d(x,S)}computeBulgeFromThreePoints(e,t,i){const n=this.computeCircleCenter(e,t,i);if(n)return this.computeBulgeFromCenter(e,i,n)}computeBulgeFromRadius(e,t,i){const n=Math.abs(i),r=t.x-e.x,o=t.y-e.y,a=Math.hypot(r,o);if(a===0||a>2*n)return;const l=(e.x+t.x)/2,c=(e.y+t.y)/2,h=Math.sqrt(Math.max(0,n*n-a*a/4)),p=-o/a,m=r/a,g=i>=0?1:-1,f=l+p*h*g,w=c+m*h*g,v=new d.AcGePoint2d(f,w);return this.computeBulgeFromCenter(e,t,v)}async execute(e){k.instance.editor.resetInputToggles();const t=[],i=[];let n=!1;const r=B=>B==null?B:k.instance.editor.getInputToggles().ctrlArcFlip?this.flipArcBulgeForCtrl(B):B,o=(B,I,N)=>this.computeBulgeFromCenter(B,I,N),a=(B,I,N)=>this.computeBulgeFromThreePoints(B,I,N),l=(B,I,N)=>this.computeBulgeFromRadius(B,I,N),c=()=>this.getIncomingTangentRadians(t,i),h=B=>{const I=f();if(I)return this.computeBulgeFromTangentDirection(I,B,c())},p=(B,I,N,G)=>this.computeBulgeFromTangentAndIncludedAngle(B,I,N,G),m=()=>new qy(e.view,t,i),g=(B,I)=>new qc(e.view,t,i,B,I),f=()=>t[t.length-1],w=B=>{t.length>0&&(i[t.length-1]=B)},v=B=>{t.push(new d.AcGePoint2d(B)),i.push(void 0)},x=()=>{t.length<=1||(t.pop(),i.pop(),i[i.length-1]=void 0)},S=B=>B!==b.OK&&B!==b.Keyword;class P{constructor(I){this.machine=I}buildPrompt(){const I=new T(u.t("jig.polyline.nextPointWithOptions"));I.keywords.add(u.t("jig.polyline.keywords.arc.display"),u.t("jig.polyline.keywords.arc.global"),u.t("jig.polyline.keywords.arc.local")),I.keywords.add(u.t("jig.polyline.keywords.undo.display"),u.t("jig.polyline.keywords.undo.global"),u.t("jig.polyline.keywords.undo.local")),I.keywords.add(u.t("jig.polyline.keywords.close.display"),u.t("jig.polyline.keywords.close.global"),u.t("jig.polyline.keywords.close.local")),I.useDashedLine=!0,I.useBasePoint=!0;const N=f();return N&&(I.basePoint=new d.AcGePoint3d(N)),I.jig=g(void 0),I.allowNone=!0,I}async handleResult(I){if(I.status===b.Keyword){const N=I.stringResult??"";if(N==="Arc")this.machine.setState(new A(this.machine));else if(N==="Undo")x();else if(N==="Close"&&t.length>1)return n=!0,w(void 0),"finish";return"continue"}return I.status===b.OK?(w(void 0),v(I.value),"continue"):"finish"}}class A{constructor(I){this.machine=I}buildPrompt(){const I=new T(u.t("jig.polyline.nextPointWithArcOptions"));I.keywords.add(u.t("jig.polyline.keywords.angle.display"),u.t("jig.polyline.keywords.angle.global"),u.t("jig.polyline.keywords.angle.local")),I.keywords.add(u.t("jig.polyline.keywords.center.display"),u.t("jig.polyline.keywords.center.global"),u.t("jig.polyline.keywords.center.local")),I.keywords.add(u.t("jig.polyline.keywords.secondPoint.display"),u.t("jig.polyline.keywords.secondPoint.global"),u.t("jig.polyline.keywords.secondPoint.local")),I.keywords.add(u.t("jig.polyline.keywords.radius.display"),u.t("jig.polyline.keywords.radius.global"),u.t("jig.polyline.keywords.radius.local")),I.keywords.add(u.t("jig.polyline.keywords.line.display"),u.t("jig.polyline.keywords.line.global"),u.t("jig.polyline.keywords.line.local")),I.keywords.add(u.t("jig.polyline.keywords.undo.display"),u.t("jig.polyline.keywords.undo.global"),u.t("jig.polyline.keywords.undo.local")),I.keywords.add(u.t("jig.polyline.keywords.close.display"),u.t("jig.polyline.keywords.close.global"),u.t("jig.polyline.keywords.close.local")),I.useDashedLine=!0,I.useBasePoint=!0;const N=f();return N&&(I.basePoint=new d.AcGePoint3d(N)),I.jig=g(void 0,G=>r(h(G))),I.allowNone=!0,I}async handleResult(I){if(I.status===b.OK){const $=h(I.value);return $===void 0||(w(r($)),v(I.value)),"continue"}if(I.status!==b.Keyword)return"finish";const N=I.stringResult??"";if(N==="Line")return this.machine.setState(new P(this.machine)),"continue";if(N==="Undo")return x(),"continue";if(N==="Close"&&t.length>1)return n=!0,w(void 0),"finish";const G=f();if(!G)return"finish";if(N==="Angle"){const $=new ie(u.t("jig.polyline.arcAngle"));$.jig=m();const X=await k.instance.editor.getDouble($);if(S(X.status))return"finish";const Y=new T(u.t("jig.polyline.arcEndPoint"));Y.useDashedLine=!0,Y.useBasePoint=!0,Y.basePoint=new d.AcGePoint3d(G);const Q=(X.value??0)*(Math.PI/180),se=c();Y.jig=g(void 0,Go=>r(p(G,Go,se,Q)));const re=await k.instance.editor.getPoint(Y);if(S(re.status))return"finish";const Ot=p(G,re.value,se,Q);return Ot===void 0||(w(r(Ot)),v(re.value)),"continue"}if(N==="Center"){const $=new T(u.t("jig.polyline.arcCenter"));$.jig=m();const X=await k.instance.editor.getPoint($);if(S(X.status))return"finish";const Y=new T(u.t("jig.polyline.arcEndPoint"));Y.useDashedLine=!0,Y.useBasePoint=!0,Y.basePoint=new d.AcGePoint3d(G),Y.jig=g(void 0,re=>r(o(G,re,X.value)));const Q=await k.instance.editor.getPoint(Y);if(S(Q.status))return"finish";const se=o(G,Q.value,X.value);return se===void 0||(w(r(se)),v(Q.value)),"continue"}if(N==="SecondPoint"){const $=new T(u.t("jig.polyline.arcSecondPoint"));$.jig=m(),$.useDashedLine=!0,$.useBasePoint=!0,$.basePoint=new d.AcGePoint3d(G);const X=await k.instance.editor.getPoint($);if(S(X.status))return"finish";const Y=new T(u.t("jig.polyline.arcEndPoint"));Y.useDashedLine=!0,Y.useBasePoint=!0,Y.basePoint=new d.AcGePoint3d(G),Y.jig=g(void 0,re=>r(a(G,X.value,re)));const Q=await k.instance.editor.getPoint(Y);if(S(Q.status))return"finish";const se=a(G,X.value,Q.value);return se===void 0||(w(r(se)),v(Q.value)),"continue"}if(N==="Radius"){const $=new ie(u.t("jig.polyline.arcRadius"));$.jig=m();const X=await k.instance.editor.getDouble($);if(S(X.status))return"finish";const Y=new T(u.t("jig.polyline.arcEndPoint"));Y.useDashedLine=!0,Y.useBasePoint=!0,Y.basePoint=new d.AcGePoint3d(G),Y.jig=g(void 0,re=>r(l(G,re,X.value??0)));const Q=await k.instance.editor.getPoint(Y);if(S(Q.status))return"finish";const se=l(G,Q.value,X.value??0);return se===void 0||(w(r(se)),v(Q.value)),"continue"}return"continue"}}const _=new T(u.t("jig.polyline.firstPoint")),C=await k.instance.editor.getPoint(_);if(C.status!==b.OK)return;v(C.value);const O=new Ye;if(O.setState(new P(O)),await O.run(B=>k.instance.editor.getPoint(B)),t.length>=2){const B=e.doc.database,I=new d.AcDbPolyline;t.forEach((N,G)=>I.addVertexAt(G,N,i[G])),n&&(I.closed=!0),B.tables.blockTable.modelSpace.appendEntity(I)}}}function Qc(s,e){const t=new d.AcGePoint3d(e).sub(s);if(d.AcGeTol.isPositive(t.length()))return t.normalize()}class Jy extends R{constructor(e,t){super(e),this._startPoint=new d.AcGePoint3d(t),this._ray=new d.AcDbRay,this._ray.basePoint=new d.AcGePoint3d(t),this._ray.unitDir=new d.AcGePoint3d(1,0,0)}get entity(){return this._ray}update(e){const t=Qc(this._startPoint,e);t&&(this._ray.basePoint=new d.AcGePoint3d(this._startPoint),this._ray.unitDir=t)}}class ed extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.doc.database,i=new T(u.t("jig.ray.startPoint")),n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=new d.AcGePoint3d(n.value);for(;;){const o=new T(u.t("jig.ray.throughPoint"));o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new d.AcGePoint3d(r),o.jig=new Jy(e.view,r);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)break;const l=Qc(r,a.value);if(!l)continue;const c=new d.AcDbRay;c.basePoint=new d.AcGePoint3d(r),c.unitDir=l,t.tables.blockTable.modelSpace.appendEntity(c)}}}const Qy=Math.tan(Math.PI/8),eg={chamferDist1:0,chamferDist2:0,filletRadius:0,width:0,elevation:0,thickness:0,rotation:0};function wt(s,e){s.keywords.add(u.t(`jig.rect.keywords.${e}.display`),u.t(`jig.rect.keywords.${e}.global`),u.t(`jig.rect.keywords.${e}.local`))}function tg(s,e){s.keywords.add(u.t(`jig.rect.keywords.${e}.display`),u.t(`jig.rect.keywords.${e}.global`),u.t(`jig.rect.keywords.${e}.local`))}function ig(s,e,t){const i=Math.cos(t),n=Math.sin(t);return new d.AcGePoint2d(s.x+e.x*i-e.y*n,s.y+e.x*n+e.y*i)}function ng(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=Math.cos(t),o=Math.sin(t);return new d.AcGePoint2d(i*r+n*o,-i*o+n*r)}function Xt(s){return Number.isFinite(s??NaN)?Math.max(0,s??0):0}function Qr(s,e){return[{point:new d.AcGePoint2d(0,0)},{point:new d.AcGePoint2d(s,0)},{point:new d.AcGePoint2d(s,e)},{point:new d.AcGePoint2d(0,e)}]}function td(s,e,t,i){const n=s>=0?1:-1,r=e>=0?1:-1,o=Math.abs(s),a=Math.abs(e),l=Math.min(Xt(t),o/2),c=Math.min(Xt(i),a/2);if(d.AcGeTol.isNonPositive(l)&&d.AcGeTol.isNonPositive(c))return Qr(s,e);const h=new d.AcGePoint2d(n*l,0),p=new d.AcGePoint2d(0,r*c),m=new d.AcGePoint2d(s-n*l,0),g=new d.AcGePoint2d(s,r*c),f=new d.AcGePoint2d(s,e-r*c),w=new d.AcGePoint2d(s-n*l,e),v=new d.AcGePoint2d(n*l,e),x=new d.AcGePoint2d(0,e-r*c);return[{point:h},{point:m},{point:g},{point:f},{point:w},{point:v},{point:x},{point:p}]}function sg(s,e,t){const i=Math.abs(s),n=Math.abs(e),r=Math.min(Xt(t),i/2,n/2);if(d.AcGeTol.isNonPositive(r))return Qr(s,e);const o=td(s,e,r,r),l=(s*e>=0?1:-1)*Qy;return o.map((c,h)=>({point:c.point,bulge:h%2===1?l:void 0}))}function rg(s,e,t){return d.AcGeTol.isPositive(t.filletRadius)?sg(s,e,t.filletRadius):d.AcGeTol.isPositive(t.chamferDist1)||d.AcGeTol.isPositive(t.chamferDist2)?td(s,e,t.chamferDist1,t.chamferDist2):Qr(s,e)}function eo(s,e,t,i){let n=0,r=0;if(t.mode==="corner"){const l=ng(e,t.secondPoint,i.rotation);n=l.x,r=l.y}else n=t.length,r=t.width;if(d.AcGeTol.equalToZero(n)||d.AcGeTol.equalToZero(r))return!1;s.reset(!1);const o=rg(n,r,i),a=Xt(i.width);return o.forEach((l,c)=>{const h=ig(e,l.point,i.rotation);d.AcGeTol.isPositive(a)?s.addVertexAt(c,h,l.bulge,a,a):s.addVertexAt(c,h,l.bulge)}),s.elevation=i.elevation,s.closed=!0,!0}class id extends R{constructor(e,t,i){super(e),this._rect=new d.AcDbPolyline,this._firstPoint=new d.AcGePoint2d(t),this._settingsProvider=i}get entity(){return this._rect}update(e){eo(this._rect,this._firstPoint,{mode:"corner",secondPoint:e},this._settingsProvider())}}class qt extends R{constructor(e,t,i,n){super(e),this._rect=new d.AcDbPolyline,eo(this._rect,t,i,n)}get entity(){return this._rect}update(e){}}function to(s){return{chamferDist1:s.chamferDist1,chamferDist2:s.chamferDist2,filletRadius:s.filletRadius,width:s.width,elevation:s.elevation,thickness:s.thickness,rotation:s.rotation}}function st(s){return Number.isFinite(s??NaN)&&d.AcGeTol.isPositive(s??0)}const en=class en extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=to(en._settings),i=await this.promptFirstCorner(t);if(!i)return;const n=await this.promptSecondInput(e,i,t);if(!n)return;const r=new d.AcDbPolyline;if(!eo(r,i,n,t)){this.warnRectMessage("invalidRect");return}d.AcGeTol.isPositive(t.thickness)&&this.warnRectMessage("thicknessNotSupported"),e.doc.database.tables.blockTable.modelSpace.appendEntity(r),en._settings=to(t)}warnRectMessage(e){this.notify(u.t(`jig.rect.${e}`),"warning")}async promptFirstCorner(e){for(;;){const t=new T(u.t("jig.rect.firstPointWithOptions"));wt(t,"chamfer"),wt(t,"elevation"),wt(t,"fillet"),wt(t,"thickness"),wt(t,"width");const i=await k.instance.editor.getPoint(t);if(i.status===b.OK)return i.value;if(i.status!==b.Keyword)return;const n=i.stringResult??"";if(n==="Chamfer"){if(!await this.promptChamfer(e))return}else if(n==="Elevation"){if(!await this.promptElevation(e))return}else if(n==="Fillet"){if(!await this.promptFillet(e))return}else if(n==="Thickness"){if(!await this.promptThickness(e))return}else if(n==="Width"&&!await this.promptWidth(e))return}}async promptSecondInput(e,t,i){let n;class r{constructor(l){this.cmd=l}buildPrompt(){const l=new T(u.t("jig.rect.otherCornerWithOptions"));return wt(l,"area"),wt(l,"dimensions"),wt(l,"rotation"),l.useDashedLine=!1,l.useBasePoint=!0,l.basePoint=new d.AcGePoint3d(t),l.jig=new id(e.view,t,()=>i),l}async handleResult(l){if(l.status===b.OK)return n={mode:"corner",secondPoint:l.value},"finish";if(l.status!==b.Keyword)return"finish";const c=l.stringResult??"";if(c==="Rotation")return await this.cmd.promptRotation(e,t,i)?"continue":"finish";if(c==="Dimensions"){const h=await this.cmd.promptDimensions(e,t,i);return h&&(n=h),"finish"}if(c==="Area"){const h=await this.cmd.promptArea(e,t,i);return h&&(n=h),"finish"}return"continue"}}const o=new Ye;return o.setState(new r(this)),await o.run(a=>k.instance.editor.getPoint(a)),n}async promptPositiveDouble(e,t){for(;;){const i=new ie(e);i.allowNegative=!1,i.allowZero=!1,t&&(i.jig=t);const n=await k.instance.editor.getDouble(i);if(n.status!==b.OK)return;if(st(n.value))return n.value;this.warnRectMessage("invalidPositive")}}async promptChamfer(e){const t=await this.promptPositiveDouble(u.t("jig.rect.chamferFirst"));if(!st(t))return!1;const i=await this.promptPositiveDouble(u.t("jig.rect.chamferSecond"));return st(i)?(e.chamferDist1=t,e.chamferDist2=i,e.filletRadius=0,!0):!1}async promptFillet(e){const t=await this.promptPositiveDouble(u.t("jig.rect.filletRadius"));return st(t)?(e.filletRadius=t,e.chamferDist1=0,e.chamferDist2=0,!0):!1}async promptWidth(e){const t=new ie(u.t("jig.rect.segmentWidth"));t.allowNegative=!1,t.allowZero=!0;const i=await k.instance.editor.getDouble(t);return i.status!==b.OK?!1:(e.width=Xt(i.value),!0)}async promptElevation(e){const t=new ie(u.t("jig.rect.elevationValue"));t.allowNegative=!0,t.allowZero=!0;const i=await k.instance.editor.getDouble(t);return i.status!==b.OK?!1:(e.elevation=i.value??0,!0)}async promptThickness(e){const t=new ie(u.t("jig.rect.thicknessValue"));t.allowNegative=!1,t.allowZero=!0;const i=await k.instance.editor.getDouble(t);return i.status!==b.OK?!1:(e.thickness=Xt(i.value),!0)}async promptRotation(e,t,i){const n=new Se(u.t("jig.rect.rotationAngle"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new d.AcGePoint3d(t),n.allowNegative=!0,n.allowZero=!0,n.jig=new qt(e.view,t,{mode:"dimensions",length:1,width:1},i);const r=await k.instance.editor.getAngle(n);return r.status!==b.OK?!1:(i.rotation=(r.value??0)*Math.PI/180,!0)}async promptDimensions(e,t,i){const n={mode:"dimensions",length:1,width:1},r=await this.promptPositiveDouble(u.t("jig.rect.dimensionLength"),new qt(e.view,t,n,i));if(!st(r))return;const o=await this.promptPositiveDouble(u.t("jig.rect.dimensionWidth"),new qt(e.view,t,{mode:"dimensions",length:r,width:1},i));if(st(o))return{mode:"dimensions",length:r,width:o}}async promptArea(e,t,i){const n=await this.promptPositiveDouble(u.t("jig.rect.areaValue"),new qt(e.view,t,{mode:"dimensions",length:1,width:1},i));if(!st(n))return;const r=new ie(u.t("jig.rect.areaLengthOrWidth"));tg(r,"rectWidth"),r.allowNegative=!1,r.allowZero=!1,r.jig=new qt(e.view,t,{mode:"dimensions",length:1,width:1},i);const o=await k.instance.editor.getDouble(r);if(o.status===b.Keyword){if(o.stringResult!=="Width")return;const l=await this.promptPositiveDouble(u.t("jig.rect.areaSpecifyWidth"),new qt(e.view,t,{mode:"dimensions",length:1,width:1},i));return st(l)?{mode:"dimensions",length:(n??0)/(l??1),width:l}:void 0}if(o.status!==b.OK||!st(o.value))return;const a=o.value;return{mode:"dimensions",length:a,width:(n??0)/a}}};en._settings=to(eg);let ns=en;const io=1,og=.005,ag=.1;function nd(s){const e=Math.max(1,s.width),t=Math.max(1,s.height),i=s.screenToWorld({x:0,y:0}),n=s.screenToWorld({x:e,y:t});return Math.hypot(n.x-i.x,n.y-i.y)}function sd(s){const t=nd(s)*og;return Number.isFinite(t)&&t>0?t:1}function Ct(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function no(s,e){const t=Math.min(s.x,e.x),i=Math.max(s.x,e.x),n=Math.min(s.y,e.y),r=Math.max(s.y,e.y);return[new d.AcGePoint2d(t,n),new d.AcGePoint2d(i,n),new d.AcGePoint2d(i,r),new d.AcGePoint2d(t,r)]}function rd(s){let e=0;const t=s.length;for(let i=0;i<t;i++){const n=s[i],r=s[(i+1)%t];e+=n.x*r.y-r.x*n.y}return e/2}function od(s){const e=s.map(t=>new d.AcGePoint2d(t.x,t.y));return e.length>=3&&rd(e)<0&&e.reverse(),e}function ad(s,e){if(s.length<2)return 0;let t=0;const i=e?s.length:s.length-1;for(let n=0;n<i;n++){const r=s[n],o=s[(n+1)%s.length];t+=Ct(r,o)}return t}function lg(s,e,t){const i=ad(s,e);let n=i>0?(t%i+i)%i:0;const r=e?s.length:s.length-1;for(let a=0;a<r;a++){const l=s[a],c=s[(a+1)%s.length],h=Ct(l,c);if(n<=h||a===r-1){const p=h>0?n/h:0;return new d.AcGePoint2d(l.x+(c.x-l.x)*p,l.y+(c.y-l.y)*p)}n-=h}const o=s[e?0:s.length-1];return new d.AcGePoint2d(o.x,o.y)}function cg(s,e){if(!e)return 1;const t=Math.sin(s*12.9898+78.233)*43758.5453;return .75+(t-Math.floor(t))*.5}function dg(s,e,t){const i=Math.max(e*.35,s*1e-4),n=[];let r=s,o=0;for(;r>i*.5;){let a=e*cg(o,t);if(a=Math.min(Math.max(a,i),r),r-a<i*.5&&(a=r),n.push(a),r-=a,o++,n.length>4096)break}return n.length===0&&n.push(s),n}function ld(s,e,t,i){if(e.length<2)return!1;const n=t?od(e):e,r=ad(n,t);if(!d.AcGeTol.isPositive(r))return!1;const o=Math.max(i.arcLength,r*1e-4),a=dg(r,o,i.variance!==!1);if(t&&a.length<3){const m=r/3;a.length=0,a.push(m,m,m)}const l=i.reverse?-io:io,c=i.style==="calligraphy",h=c?o*ag:void 0;s.reset(!1);let p=0;return a.forEach((m,g)=>{const f=lg(n,t,p);c&&h!=null?s.addVertexAt(g,f,l,0,h):s.addVertexAt(g,f,l),p+=m}),s.closed=t,s.numberOfVertices>=2}function cd(s,e,t){const i=Ct(s,e),n=Math.max(1,Math.ceil(i/Math.max(t,1e-8))),r=[];for(let o=0;o<n;o++){const a=o/n;r.push(new d.AcGePoint2d(s.x+(e.x-s.x)*a,s.y+(e.y-s.y)*a))}return r}function ug(s,e,t,i){if(Math.abs(t)<1e-12)return cd(s,e,i);const n=e.x-s.x,r=e.y-s.y,o=Math.hypot(n,r);if(!d.AcGeTol.isPositive(o))return[new d.AcGePoint2d(s.x,s.y)];const a=t>=0?1:-1,l=4*Math.atan(Math.abs(t)),c=o/(2*Math.sin(l/2)),h=(s.x+e.x)/2,p=(s.y+e.y)/2,m=-r/o,g=n/o,f=c*Math.cos(l/2),w=h+m*f*a,v=p+g*f*a,x=Math.atan2(s.y-v,s.x-w),S=l*a,P=Math.abs(c*S),A=Math.max(2,Math.ceil(P/Math.max(i,1e-8))),_=[];for(let C=0;C<A;C++){const O=x+S*C/A;_.push(new d.AcGePoint2d(w+c*Math.cos(O),v+c*Math.sin(O)))}return _}function hg(s){var n;const e=(n=s._geo)==null?void 0:n.vertices;if(e&&e.length>1)return e.map(r=>({x:r.x,y:r.y,bulge:r.bulge??0}));const t=s.numberOfVertices,i=s.getBulgeAt;return Array.from({length:t},(r,o)=>{const a=s.getPoint2dAt(o);return{x:a.x,y:a.y,bulge:(i==null?void 0:i(o))??0}})}function pg(s,e){const t=hg(s);if(t.length<2)return[];const i=[],n=s.closed?t.length:t.length-1;for(let r=0;r<n;r++){const o=t[r],a=t[(r+1)%t.length];i.push(...ug(o,a,o.bulge,e))}if(!s.closed){const r=t[t.length-1];i.push(new d.AcGePoint2d(r.x,r.y))}return i}function mg(s,e){const t=s.radius;if(!d.AcGeTol.isPositive(t))return[];const i=2*Math.PI*t,n=Math.max(8,Math.ceil(i/Math.max(e,1e-8))),r=s.center,o=[];for(let a=0;a<n;a++){const l=a/n*Math.PI*2;o.push(new d.AcGePoint2d(r.x+t*Math.cos(l),r.y+t*Math.sin(l)))}return o}function yg(s,e){const t=s.majorAxisRadius,i=s.minorAxisRadius;if(!d.AcGeTol.isPositive(t)||!d.AcGeTol.isPositive(i))return[];const n=s._geo,r=(n==null?void 0:n.majorAxis)??{x:1,y:0},o=Math.hypot(r.x,r.y)||1,a=r.x/o,l=r.y/o,c=-l,h=a,p=Math.PI*(3*(t+i)-Math.sqrt((3*t+i)*(t+3*i))),m=Math.max(12,Math.ceil(p/Math.max(e,1e-8))),g=s.center,f=s.startAngle??0;let v=(s.endAngle??Math.PI*2)-f;v<=0&&(v+=Math.PI*2);const S=Math.abs(v-Math.PI*2)<1e-6?m:m+1,P=[];for(let A=0;A<S;A++){const _=f+v*A/m,C=t*Math.cos(_),O=i*Math.sin(_);P.push(new d.AcGePoint2d(g.x+a*C+c*O,g.y+l*C+h*O))}return P}function gg(s,e){var o;const t=s._geo,i=(o=t==null?void 0:t.fitPoints)!=null&&o.length?t.fitPoints:t==null?void 0:t.controlPoints;if(!i||i.length<2)return[];const n=[],r=s.closed?i.length:i.length-1;for(let a=0;a<r;a++){const l=i[a],c=i[(a+1)%i.length];n.push(...cd(l,c,e))}if(!s.closed){const a=i[i.length-1];n.push(new d.AcGePoint2d(a.x,a.y))}return n}function dd(s,e){if(s instanceof d.AcDbPolyline){const t=pg(s,e);return t.length>=2?{points:t,closed:s.closed}:void 0}if(s instanceof d.AcDbCircle){const t=mg(s,e);return t.length>=2?{points:t,closed:!0}:void 0}if(s instanceof d.AcDbEllipse){const t=yg(s,e),i=s.startAngle??0;let r=(s.endAngle??Math.PI*2)-i;for(;r<0;)r+=Math.PI*2;const o=r<1e-6||Math.abs(r-Math.PI*2)<.001;return t.length>=2?{points:t,closed:o}:void 0}if(s instanceof d.AcDbSpline){const t=gg(s,e);return t.length>=2?{points:t,closed:!!s.closed}:void 0}}function so(s,e,t){return Ct(s,e)<=Math.max(t*.5,1e-6)}const fg={mode:"rectangular",style:"normal",variance:!0};function Ii(s,e){s.keywords.add(u.t(`jig.revcloud.keywords.${e}.display`),u.t(`jig.revcloud.keywords.${e}.global`),u.t(`jig.revcloud.keywords.${e}.local`))}function Ze(s){return new d.AcGePoint2d(s.x,s.y)}function _t(s,e,t,i,n=!1){return ld(s,e,t,{arcLength:i.arcLength??1,style:i.style,variance:i.variance,reverse:n})}class ud extends R{constructor(e,t,i,n){super(e),this._cloud=new d.AcDbPolyline,this._path=t.map(Ze),this._closed=i,this._settings=n,this.rebuild()}get entity(){return this._cloud}updatePath(e,t){this._path=e.map(Ze),this._closed=t,this.rebuild()}update(e){if(this._path.length===0)return;const t=[...this._path,Ze(e)],i=this._closed&&t.length>=3;_t(this._cloud,t,i,this._settings)}rebuild(){if(this._path.length<2){this._cloud.reset(!1);return}_t(this._cloud,this._path,this._closed,this._settings)}}class bg extends R{constructor(e,t,i){super(e),this._cloud=new d.AcDbPolyline,this._firstPoint=Ze(t),this._settings=i}get entity(){return this._cloud}update(e){_t(this._cloud,no(this._firstPoint,e),!0,this._settings)}}class wg extends R{constructor(e,t,i){super(e),this._closed=!1,this._cloud=new d.AcDbPolyline,this._points=[Ze(t)],this._settings=i}get entity(){return this._cloud}get points(){return this._points}get closed(){return this._closed}addPoint(e){const t=Ze(e),i=this._points[this._points.length-1];i&&Ct(i,t)<1e-8||this._points.push(t)}update(e){const t=this._settings.arcLength??1,i=this._points[this._points.length-1];i&&Ct(i,e)>=t&&this._points.push(Ze(e)),this._closed=this._points.length>=3&&so(this._points[0],e,t);const n=this._closed?this._points:[...this._points,Ze(e)];_t(this._cloud,n,this._closed,this._settings)}}class vg extends R{constructor(e,t,i,n){super(e),this._reverse=!1,this._cloud=new d.AcDbPolyline,this._path=t,this._closed=i,this._settings=n,this._valid=_t(this._cloud,t,i,n)}get entity(){return this._cloud}get valid(){return this._valid}get reverse(){return this._reverse}update(e){}toggleReverse(){this._reverse=!this._reverse,this._valid=_t(this._cloud,this._path,this._closed,this._settings,this._reverse),this.render()}}const js=class js extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=js._settings;for(t.arcLength==null&&(t.arcLength=sd(e.view));;){const i=new T(u.t("jig.revcloud.firstCornerOrOptions"));Ii(i,"arcLength"),Ii(i,"object");const n=i.keywords.add(u.t("jig.revcloud.keywords.rectangular.display"),u.t("jig.revcloud.keywords.rectangular.global"),u.t("jig.revcloud.keywords.rectangular.local")),r=i.keywords.add(u.t("jig.revcloud.keywords.polygonal.display"),u.t("jig.revcloud.keywords.polygonal.global"),u.t("jig.revcloud.keywords.polygonal.local")),o=i.keywords.add(u.t("jig.revcloud.keywords.freehand.display"),u.t("jig.revcloud.keywords.freehand.global"),u.t("jig.revcloud.keywords.freehand.local"));Ii(i,"style"),i.keywords.default=t.mode==="polygonal"?r:t.mode==="freehand"?o:n;const a=await k.instance.editor.getPoint(i);if(a.status===b.Keyword){const l=a.stringResult??"";if(l==="ArcLength"){if(!await this.promptArcLength(t))return;continue}if(l==="Object"){await this.convertObject(e,t);return}if(l==="Rectangular"){t.mode="rectangular",await this.drawRectangular(e,t);return}if(l==="Polygonal"){t.mode="polygonal",await this.drawPolygonal(e,t);return}if(l==="Freehand"){t.mode="freehand",await this.drawFreehand(e,t);return}if(l==="Style"){if(!await this.promptStyle(t))return;continue}continue}if(a.status!==b.OK||!a.value)return;t.mode==="polygonal"?await this.drawPolygonal(e,t,a.value):t.mode==="freehand"?await this.drawFreehand(e,t,a.value):await this.drawRectangular(e,t,a.value);return}}async promptArcLength(e){const t=new be(u.t("jig.revcloud.arcLength"));t.allowNegative=!1,t.allowZero=!1,t.useDefaultValue=e.arcLength!=null,t.defaultValue=e.arcLength??1;const i=await k.instance.editor.getDistance(t);if(i.status!==b.OK&&i.status!==b.None)return!1;const n=i.value??t.defaultValue;return d.AcGeTol.isPositive(n)?(e.arcLength=n,!0):(this.showMessage(u.t("jig.revcloud.invalidArcLength"),"warning"),!0)}async promptStyle(e){const t=new ne(u.t("jig.revcloud.style"));t.allowNone=!0;const i=t.keywords.add(u.t("jig.revcloud.keywords.normal.display"),u.t("jig.revcloud.keywords.normal.global"),u.t("jig.revcloud.keywords.normal.local")),n=t.keywords.add(u.t("jig.revcloud.keywords.calligraphy.display"),u.t("jig.revcloud.keywords.calligraphy.global"),u.t("jig.revcloud.keywords.calligraphy.local"));t.keywords.default=e.style==="calligraphy"?n:i;const r=await k.instance.editor.getKeywords(t);return r.status===b.Cancel?!1:((r.status===b.OK||r.status===b.Keyword)&&(r.stringResult==="Calligraphy"?e.style="calligraphy":r.stringResult==="Normal"&&(e.style="normal")),!0)}async drawRectangular(e,t,i){const n=i??await this.promptPoint("firstCorner");if(!n)return;const r=new T(u.t("jig.revcloud.oppositeCorner"));r.useBasePoint=!0,r.basePoint=new d.AcGePoint3d(n.x,n.y,0),r.useDashedLine=!1,r.jig=new bg(e.view,n,t);const o=await k.instance.editor.getPoint(r);if(o.status!==b.OK||!o.value)return;const a=no(n,o.value);d.AcGeTol.equalToZero(a[0].x-a[1].x)||d.AcGeTol.equalToZero(a[0].y-a[3].y)||await this.commitCloud(e,a,!0,t)}async drawPolygonal(e,t,i){const n=i??await this.promptPoint("startPoint");if(!n)return;const r=[Ze(n)];class o{buildPrompt(){const c=new T(u.t(r.length>=2?"jig.revcloud.nextPointOrUndo":"jig.revcloud.nextPoint"));r.length>=2&&Ii(c,"undo"),c.useDashedLine=!1,c.useBasePoint=!0;const h=r[r.length-1];return c.basePoint=new d.AcGePoint3d(h.x,h.y,0),c.allowNone=r.length>=3,c.jig=new ud(e.view,r,!0,t),c}async handleResult(c){return c.status===b.Keyword?(c.stringResult==="Undo"&&r.length>1&&r.pop(),"continue"):c.status===b.OK&&c.value?(r.push(Ze(c.value)),"continue"):"finish"}}const a=new Ye;a.setState(new o),await a.run(l=>k.instance.editor.getPoint(l)),!(r.length<3)&&await this.commitCloud(e,r,!0,t)}async drawFreehand(e,t,i){const n=i??await this.promptPoint("firstPoint");if(!n)return;const r=new wg(e.view,n,t),o=t.arcLength??1;for(;;){const a=new T(u.t("jig.revcloud.guideCursor"));a.jig=r,a.useDashedLine=!1,a.useBasePoint=!0,a.basePoint=new d.AcGePoint3d(n.x,n.y,0),a.allowNone=!0,a.disableOSnap=!0;const l=await k.instance.editor.getPoint(a);if(l.status===b.Cancel)return;if(l.status===b.None){if(r.points.length<2)return;await this.commitCloud(e,r.points,r.closed,t);return}if(l.status!==b.OK||!l.value)return;if(r.points.length>=3&&so(r.points[0],l.value,o)){await this.commitCloud(e,r.points,!0,t);return}r.addPoint(l.value)}}async convertObject(e,t){for(;;){const i=new $e(u.t("jig.revcloud.selectObject"));i.setRejectMessage(u.t("jig.revcloud.invalidObject")),i.addAllowedClass("Polyline"),i.addAllowedClass("Circle"),i.addAllowedClass("Ellipse"),i.addAllowedClass("Spline");const n=await k.instance.editor.getEntity(i);if(n.status!==b.OK||!n.objectId)return;const r=e.doc.database.openEntityForRead(n.objectId);if(!r)return;const o=dd(r,(t.arcLength??1)*.5);if(!o){this.showMessage(u.t("jig.revcloud.invalidObject"),"warning");continue}await this.commitCloud(e,o.points,o.closed,t)&&this.eraseEntity(e,r);return}}async commitCloud(e,t,i,n){const r=new vg(e.view,t,i,n);if(!r.valid)return!1;try{for(;r.render(),!!await this.promptReverse(r);)r.toggleReverse();const o=new d.AcDbPolyline;return _t(o,t,i,n,r.reverse)?(e.doc.database.tables.blockTable.modelSpace.appendEntity(o),!0):!1}finally{r.end()}}async promptReverse(e){const t=new ne(u.t("jig.revcloud.reverseDirection"));t.jig=e,t.allowNone=!0,Ii(t,"yes");const i=t.keywords.add(u.t("jig.revcloud.keywords.no.display"),u.t("jig.revcloud.keywords.no.global"),u.t("jig.revcloud.keywords.no.local"));t.keywords.default=i;const n=await k.instance.editor.getKeywords(t);return(n.status===b.OK||n.status===b.Keyword)&&n.stringResult==="Yes"}async promptPoint(e){const t=new T(u.t(`jig.revcloud.${e}`)),i=await k.instance.editor.getPoint(t);if(!(i.status!==b.OK||!i.value))return i.value}eraseEntity(e,t){t.erase(),e.view.removeEntity(t)}};js._settings={...fg};let ss=js;const kg={type:"line",increment:.1,tolerance:.5};function ro(s,e){s.keywords.add(u.t(`jig.sketch.keywords.${e}.display`),u.t(`jig.sketch.keywords.${e}.global`),u.t(`jig.sketch.keywords.${e}.local`))}function rs(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function vt(s){return new d.AcGePoint2d(s.x,s.y)}function os(s){return new d.AcGePoint3d(s.x,s.y,0)}function hd(s,e,t){const i=vt(e);if(s.length===0)return s.push(i),!0;const n=s[s.length-1];return rs(n,i)<t?!1:(s.push(i),!0)}function pd(s,e){if(s.length<=2)return s.map(vt);const t=Math.max(e,1e-8),i=[vt(s[0])];for(let o=1;o<s.length-1;o++){const a=i[i.length-1];rs(a,s[o])>=t&&i.push(vt(s[o]))}const n=vt(s[s.length-1]),r=i[i.length-1];return rs(r,n)>1e-8&&i.push(n),i}class md extends R{constructor(e,t,i){super(e),this._polyline=new d.AcDbPolyline,this._points=[vt(t)],this._increment=Math.max(i,1e-8),this._polyline.addVertexAt(0,this._points[0])}get entity(){return this._polyline}get points(){return this._points}update(e){hd(this._points,e,this._increment)&&this._polyline.addVertexAt(this._points.length-1,this._points[this._points.length-1])}}class xg{constructor(e){this.view=e,this._entities=[]}addStroke(e){if(e.length<2)return;const t=new d.AcDbPolyline;e.forEach((i,n)=>t.addVertexAt(n,vt(i))),this._entities.push(t),this.view.addTransientEntity(t)}render(){this._entities.forEach(e=>this.view.addTransientEntity(e))}dispose(){this._entities.forEach(e=>this.view.removeTransientEntity(e.objectId)),this._entities.length=0}}class as extends R{constructor(e,t){super(e),this.preview=t}update(e){}render(){this.preview.render()}}const Fs=class Fs extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=Fs._settings,i=[],n=new xg(e.view);try{for(;;){n.render();const r=new T(u.t("jig.sketch.specifySketch"));ro(r,"type"),ro(r,"increment"),ro(r,"tolerance"),r.allowNone=!0,r.disableOSnap=!0,r.jig=new as(e.view,n);const o=await k.instance.editor.getPoint(r);if(o.status===b.Keyword){const l=o.stringResult??"";if(l==="Type"){if(!await this.promptType(t,n))return;continue}if(l==="Increment"){if(!await this.promptIncrement(t,n))return;continue}if(l==="Tolerance"){if(!await this.promptTolerance(t,n))return;continue}continue}if(o.status===b.None){this.commitStrokes(e,i);return}if(o.status!==b.OK||!o.value)return;const a=await this.captureStroke(e,t,o.value,n);if(a===!1)return;a.length>=2&&(i.push({points:a,type:t.type,tolerance:t.tolerance}),n.addStroke(a))}}finally{n.dispose()}}async promptType(e,t){t==null||t.render();const i=new ne(u.t("jig.sketch.type"));i.allowNone=!0,t&&(i.jig=new as(t.view,t));const n=i.keywords.add(u.t("jig.sketch.keywords.line.display"),u.t("jig.sketch.keywords.line.global"),u.t("jig.sketch.keywords.line.local")),r=i.keywords.add(u.t("jig.sketch.keywords.polyline.display"),u.t("jig.sketch.keywords.polyline.global"),u.t("jig.sketch.keywords.polyline.local")),o=i.keywords.add(u.t("jig.sketch.keywords.spline.display"),u.t("jig.sketch.keywords.spline.global"),u.t("jig.sketch.keywords.spline.local"));i.keywords.default=e.type==="polyline"?r:e.type==="spline"?o:n;const a=await k.instance.editor.getKeywords(i);return a.status===b.Cancel?!1:((a.status===b.OK||a.status===b.Keyword)&&(a.stringResult==="Polyline"?e.type="polyline":a.stringResult==="Spline"?e.type="spline":(a.stringResult==="Line"||a.stringResult==="Lines")&&(e.type="line")),!0)}async promptIncrement(e,t){t==null||t.render();const i=new be(u.t("jig.sketch.increment"));i.allowNegative=!1,i.allowZero=!1,i.useDefaultValue=!0,i.defaultValue=e.increment,t&&(i.jig=new as(t.view,t));const n=await k.instance.editor.getDistance(i);if(n.status===b.Cancel)return!1;const r=n.value??e.increment;return d.AcGeTol.isPositive(r)&&(e.increment=r),!0}async promptTolerance(e,t){t==null||t.render();const i=new be(u.t("jig.sketch.tolerance"));i.allowNegative=!1,i.allowZero=!0,i.useDefaultValue=!0,i.defaultValue=e.tolerance,t&&(i.jig=new as(t.view,t));const n=await k.instance.editor.getDistance(i);if(n.status===b.Cancel)return!1;const r=n.value??e.tolerance;return r>=0&&Number.isFinite(r)&&(e.tolerance=r),!0}async captureStroke(e,t,i,n){n.render();const r=new md(e.view,i,t.increment),o=new T(u.t("jig.sketch.sketching"));o.jig=r,o.useDashedLine=!1,o.useBasePoint=!0,o.basePoint=os(i),o.allowNone=!0,o.disableOSnap=!0;const a=await k.instance.editor.getPoint(o);if(a.status===b.Cancel)return!1;const l=[...r.points];if(a.status===b.OK&&a.value){const c=l[l.length-1];(!c||rs(c,a.value)>1e-8)&&l.push(vt(a.value))}return l}commitStrokes(e,t){for(const i of t)this.appendStroke(e,i)}appendStroke(e,t){const i=e.doc.database.tables.blockTable.modelSpace,n=t.points;if(t.type==="line"){for(let o=1;o<n.length;o++){const a=new d.AcDbLine(os(n[o-1]),os(n[o]));i.appendEntity(a),e.view.addEntity(a)}return}if(t.type==="spline"){const o=pd(n,t.tolerance);if(o.length<2)return;const a=o.map(os),l=Math.min(3,Math.max(1,a.length-1)),c=new d.AcDbSpline(a,"Chord",l,!1);i.appendEntity(c),e.view.addEntity(c);return}const r=new d.AcDbPolyline;n.forEach((o,a)=>r.addVertexAt(a,o)),i.appendEntity(r),e.view.addEntity(r)}};Fs._settings={...kg};let ls=Fs;class yd extends R{constructor(e,t,i,n){super(e),this._points=t,this._settings=i,this._closed=n,this._spline=this.createSpline(t)}get entity(){return this._spline}update(e){const t=new d.AcGePoint2d(e),i=this._points[this._points.length-1],r=!i||!Ag(i,t)?[...this._points,t]:[...this._points];try{this.rebuildSpline(r)}catch{this.rebuildSpline(this._points)}}createSpline(e){return oo(e,this._settings,this._closed)}rebuildSpline(e){if(e.length<2){const o=[new d.AcGePoint3d(0,0,0),new d.AcGePoint3d(1,1,0)],a=1,l=Mi(o.length,a);this._spline.rebuild(o,l,void 0,a);return}const t=e.map(o=>new d.AcGePoint3d(o.x,o.y,0)),i=fd(t.length,this._settings),n=this._closed&&t.length>=3;if(this._settings.method==="fit"){this._spline.rebuild(t,bd(this._settings.knotsType),i,n);return}const r=Mi(t.length,i);this._spline.rebuild(t,r,void 0,i,!1),n&&(this._spline.closed=!0)}}class gd extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=[],i={method:"fit",knotsType:"chord",degree:3};let n=!1;const r=S=>{t.push(new d.AcGePoint2d(S))},o=()=>{t.length<=1||t.pop()},a=()=>t[t.length-1],l=()=>t.length>=3,c=()=>new yd(e.view,t,i,n),h=()=>new Sg(e.view,t,i,n),p=async()=>{const S=new ne(u.t("jig.spline.methodPrompt"));S.keywords.add(u.t("jig.spline.keywords.fit.display"),u.t("jig.spline.keywords.fit.global"),u.t("jig.spline.keywords.fit.local")),S.keywords.add(u.t("jig.spline.keywords.cv.display"),u.t("jig.spline.keywords.cv.global"),u.t("jig.spline.keywords.cv.local"));const P=await k.instance.editor.getKeywords(S);return P.status!==b.OK?!1:(P.stringResult==="Fit"?i.method="fit":P.stringResult==="CV"&&(i.method="cv"),!0)},m=async()=>{const S=new ne(u.t("jig.spline.knotsPrompt"));S.jig=h(),S.keywords.add(u.t("jig.spline.keywords.chord.display"),u.t("jig.spline.keywords.chord.global"),u.t("jig.spline.keywords.chord.local")),S.keywords.add(u.t("jig.spline.keywords.sqrtChord.display"),u.t("jig.spline.keywords.sqrtChord.global"),u.t("jig.spline.keywords.sqrtChord.local")),S.keywords.add(u.t("jig.spline.keywords.uniform.display"),u.t("jig.spline.keywords.uniform.global"),u.t("jig.spline.keywords.uniform.local"));const P=await k.instance.editor.getKeywords(S);return P.status!==b.OK?!1:(P.stringResult==="Chord"?i.knotsType="chord":P.stringResult==="SqrtChord"?i.knotsType="sqrtChord":P.stringResult==="Uniform"&&(i.knotsType="uniform"),!0)},g=async()=>{const S=new Er(u.t("jig.spline.degreePrompt"),1,10);S.jig=h();const P=await k.instance.editor.getInteger(S);if(P.status!==b.OK)return!1;const A=Math.floor(P.value??i.degree);return i.degree=Math.max(1,A),!0},f=S=>{S.useDashedLine=!0,S.useBasePoint=!0;const P=a();P&&(S.basePoint=new d.AcGePoint3d(P)),S.jig=c(),S.allowNone=!0};class w{constructor(P){this.machine=P}buildPrompt(){const P=new T(u.t("jig.spline.nextPointWithFitOptions"));return P.keywords.add(u.t("jig.spline.keywords.method.display"),u.t("jig.spline.keywords.method.global"),u.t("jig.spline.keywords.method.local")),P.keywords.add(u.t("jig.spline.keywords.knots.display"),u.t("jig.spline.keywords.knots.global"),u.t("jig.spline.keywords.knots.local")),P.keywords.add(u.t("jig.spline.keywords.undo.display"),u.t("jig.spline.keywords.undo.global"),u.t("jig.spline.keywords.undo.local")),P.keywords.add(u.t("jig.spline.keywords.close.display"),u.t("jig.spline.keywords.close.global"),u.t("jig.spline.keywords.close.local")),f(P),P}async handleResult(P){if(P.status===b.OK)return r(P.value),"continue";if(P.status!==b.Keyword)return"finish";const A=P.stringResult??"";return A==="Method"?await p()?(i.method==="cv"&&this.machine.setState(new v(this.machine)),"continue"):"finish":A==="Knots"?await m()?"continue":"finish":A==="Undo"?(o(),"continue"):A==="Close"&&l()?(n=!0,"finish"):"continue"}}class v{constructor(P){this.machine=P}buildPrompt(){const P=new T(u.t("jig.spline.nextPointWithCvOptions"));return P.keywords.add(u.t("jig.spline.keywords.method.display"),u.t("jig.spline.keywords.method.global"),u.t("jig.spline.keywords.method.local")),P.keywords.add(u.t("jig.spline.keywords.degree.display"),u.t("jig.spline.keywords.degree.global"),u.t("jig.spline.keywords.degree.local")),P.keywords.add(u.t("jig.spline.keywords.undo.display"),u.t("jig.spline.keywords.undo.global"),u.t("jig.spline.keywords.undo.local")),P.keywords.add(u.t("jig.spline.keywords.close.display"),u.t("jig.spline.keywords.close.global"),u.t("jig.spline.keywords.close.local")),f(P),P}async handleResult(P){if(P.status===b.OK)return r(P.value),"continue";if(P.status!==b.Keyword)return"finish";const A=P.stringResult??"";return A==="Method"?await p()?(i.method==="fit"&&this.machine.setState(new w(this.machine)),"continue"):"finish":A==="Degree"?await g()?"continue":"finish":A==="Undo"?(o(),"continue"):A==="Close"&&l()?(n=!0,"finish"):"continue"}}for(;t.length===0;){const S=new T(u.t("jig.spline.firstPointWithOptions"));S.keywords.add(u.t("jig.spline.keywords.method.display"),u.t("jig.spline.keywords.method.global"),u.t("jig.spline.keywords.method.local"));const P=await k.instance.editor.getPoint(S);if(P.status===b.OK){r(P.value);break}if(P.status===b.Keyword&&P.stringResult==="Method"){if(!await p())return;continue}return}const x=new Ye;if(x.setState(i.method==="fit"?new w(x):new v(x)),await x.run(S=>k.instance.editor.getPoint(S)),t.length>=2){const S=e.doc.database,P=oo(t,i,n);S.tables.blockTable.modelSpace.appendEntity(P)}}}class Sg extends R{constructor(e,t,i,n){super(e),this._spline=oo(t,i,n)}get entity(){return this._spline}update(e){}}function oo(s,e,t){if(s.length<2){const c=[new d.AcGePoint3d(0,0,0),new d.AcGePoint3d(1,1,0)],h=1,p=Mi(c.length,h);return new d.AcDbSpline(c,p,void 0,h)}const i=s.map(c=>new d.AcGePoint3d(c.x,c.y,0)),n=e.method==="fit"?Pg(i):i;if(n.length<2){const c=[new d.AcGePoint3d(0,0,0),new d.AcGePoint3d(1,1,0)],h=1,p=Mi(c.length,h);return new d.AcDbSpline(c,p,void 0,h)}const r=fd(n.length,e),o=t&&n.length>=3;if(e.method==="fit")return new d.AcDbSpline(n,bd(e.knotsType),r,o);const a=Mi(n.length,r),l=new d.AcDbSpline(n,a,void 0,r,!1);return o&&(l.closed=!0),l}function fd(s,e){const t=Math.max(1,s-1);return e.method==="fit"?Math.min(3,t):Math.min(Math.max(1,e.degree),t)}function Pg(s){if(s.length<=1)return s;const e=[new d.AcGePoint3d(s[0])];for(let t=1;t<s.length;t++){const i=e[e.length-1],n=s[t];Cg(i,n)||e.push(new d.AcGePoint3d(n))}return e}function Ag(s,e){return d.DEFAULT_TOL.equalPoint2d(s,e)}function Cg(s,e){return d.DEFAULT_TOL.equalPoint3d(s,e)}function bd(s){switch(s){case"chord":return"Chord";case"sqrtChord":return"SqrtChord";case"uniform":default:return"Uniform"}}function Mi(s,e){const t=[],i=s+e+1;for(let n=0;n<i;n++)n<e+1?t.push(0):n>=i-e-1?t.push(1):t.push((n-e)/(s-e));return t}async function ao(s,e){const t=d.acdbHostApplicationServices(),i=t._workingDatabase;t.workingDatabase=s;try{return await e()}finally{t._workingDatabase=i}}const _g=".dwg,.dxf",wd=100;function Eg(s){var a,l,c,h,p,m,g;const e=(l=(a=window.mlightcadGetLocalFilePath)==null?void 0:a.call(window,s))==null?void 0:l.trim();if(e)return e;const t=(c=window.electron)==null?void 0:c.webUtils,i=(p=(h=t==null?void 0:t.getPathForFile)==null?void 0:h.call(t,s))==null?void 0:p.trim();if(i)return i;const n=s,r=(m=n.path)==null?void 0:m.trim();if(r)return r;const o=(g=n.mozFullPath)==null?void 0:g.trim();return o||s.name}function Lg(s){return s.replace(/\.(dwg|dxf)$/i,"")||s}function Tg(s,e){const t=Lg(e);if(!s.tables.blockTable.has(t))return t;let i=1;for(;s.tables.blockTable.has(`${t}_${i}`);)i++;return`${t}_${i}`}function Ig(){return new Promise(s=>{const e=document.createElement("input");e.type="file",e.accept=_g,e.style.display="none",document.body.appendChild(e);let t=!1;const i=o=>{t||(t=!0,e.removeEventListener("change",n),e.removeEventListener("cancel",r),e.remove(),s(o))},n=()=>{var o;return i((o=e.files)==null?void 0:o[0])},r=()=>i(void 0);e.addEventListener("change",n),e.addEventListener("cancel",r),e.click()})}function Mg(s){var i,n;const e=((n=(i=s.extents)==null?void 0:i.clone)==null?void 0:n.call(i))??new d.AcGeBox3d;if(!e.isEmpty())return e;const t=new d.AcGeBox3d;for(const r of s.tables.blockTable.modelSpace.newIterator())if(!(r instanceof d.AcDbViewport))try{const o=r.geometricExtents;o&&!o.isEmpty()&&(t.expandByPoint(o.min),t.expandByPoint(o.max))}catch{}return t.isEmpty()?new d.AcGeBox3d(new d.AcGePoint3d(0,0,0),new d.AcGePoint3d(wd,wd,0)):t}class Dg extends R{constructor(e,t){super(e),this._mode="point",this._position=new d.AcGePoint3d,this._scale=1,this._rotationRad=0;const i=t.min,n=t.max;this._localCorners=[new d.AcGePoint2d(i.x,i.y),new d.AcGePoint2d(n.x,i.y),new d.AcGePoint2d(n.x,n.y),new d.AcGePoint2d(i.x,n.y)],this._entity=d.AcDbPolyline.from2dPoints(this._localCorners.map(r=>r.clone()),!0),this.applyGeometry()}get entity(){return this._entity}setMode(e){this._mode=e}setPosition(e){this._position=new d.AcGePoint3d(e),this.applyGeometry()}setScale(e){this._scale=e,this.applyGeometry()}setRotationRad(e){this._rotationRad=e,this.applyGeometry()}update(e){if(this._mode==="point"&&typeof e!="number"){this.setPosition(e);return}if(typeof e=="number"){if(this._mode==="scale"){this.setScale(e>0?e:this._scale);return}this._mode==="rotation"&&this.setRotationRad(e*Math.PI/180)}}applyGeometry(){const e=Math.cos(this._rotationRad),t=Math.sin(this._rotationRad),i=this._scale,n=this._localCorners.map(r=>{const o=r.x*i,a=r.y*i;return new d.AcGePoint2d(this._position.x+o*e-a*t,this._position.y+o*t+a*e)});this._entity.reset(!1),n.forEach((r,o)=>{this._entity.addVertexAt(o,r)}),this._entity.closed=!0}}class vd extends z{constructor(){super(),this.mode=F.Write}async execute(e){var a;const t=await Ig();if(!t)return;const i=(a=t.name.split(".").pop())==null?void 0:a.toLocaleLowerCase();if(i!=="dwg"&&i!=="dxf"){this.showMessage(u.t("jig.xattach.unsupportedFile"),"warning");return}let n;try{const l=await t.arrayBuffer();n=await k.instance.withBusyIndicator(async()=>{const c=new d.AcDbDatabase;return await ao(c,async()=>{await c.read(l,{readOnly:!0},i==="dwg"?d.AcDbFileType.DWG:d.AcDbFileType.DXF)}),c},u.t("jig.xattach.loading"))}catch{this.showMessage(u.t("jig.xattach.loadFailed"),"error");return}const r=Mg(n),o=new Dg(e.view,r);try{o.setMode("point");const l=new T(u.t("jig.xattach.insertionPoint"));l.allowNone=!0,l.useDefaultValue=!0,l.defaultValue=new d.AcGePoint3d(0,0,0),l.jig=o;const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK&&c.status!==b.None)return;const h=c.status===b.OK&&c.value?new d.AcGePoint3d(c.value):new d.AcGePoint3d(0,0,0);o.setPosition(h),o.setMode("scale");const p=new ie(u.t("jig.xattach.scale"));p.allowNone=!0,p.allowNegative=!1,p.allowZero=!1,p.useDefaultValue=!0,p.defaultValue=1,p.jig=o;const m=await k.instance.editor.getDouble(p);if(m.status===b.Cancel||m.status===b.Error)return;const g=m.status===b.OK&&m.value!==void 0?m.value:1;if(!(g>0)){this.showMessage(u.t("jig.xattach.invalidScale"),"warning");return}o.setScale(g),o.setMode("rotation");const f=new Se(u.t("jig.xattach.rotation"));f.allowNone=!0,f.allowNegative=!0,f.allowZero=!0,f.useDefaultValue=!0,f.defaultValue=0,f.useBasePoint=!0,f.useDashedLine=!0,f.basePoint=h,f.jig=o;const w=await k.instance.editor.getAngle(f);if(w.status===b.Cancel||w.status===b.Error)return;const x=(w.status===b.OK&&w.value!==void 0?w.value:0)*Math.PI/180,S=e.doc.database,P=Tg(S,t.name),A=Eg(t),_={position:h,scale:g,rotationRad:x},C=await Dt.instance.attachOverlay({blockName:P,fileName:t.name,sourceDb:n,sourcePath:A,transform:_});try{pt(S,"XATTACH",()=>{const{insert:O}=Dt.createHostXrefInsert(S,P,A,_,n.tables.blockTable.modelSpace.origin);C.insertId=O.objectId})}catch(O){throw Dt.instance.unload(C.id),O}ee.emit("missed-data-changed",{})}finally{o.end()}}}const Jt=1e6;class kd extends z{constructor(){super(),this.mode=F.Write}async execute(e){let t="point";for(;;){const i=new T(u.t("jig.xline.firstPointOrOptions"));i.keywords.add(u.t("jig.xline.keywords.hor.display"),u.t("jig.xline.keywords.hor.global"),u.t("jig.xline.keywords.hor.local")),i.keywords.add(u.t("jig.xline.keywords.ver.display"),u.t("jig.xline.keywords.ver.global"),u.t("jig.xline.keywords.ver.local")),i.keywords.add(u.t("jig.xline.keywords.ang.display"),u.t("jig.xline.keywords.ang.global"),u.t("jig.xline.keywords.ang.local"));const n=await k.instance.editor.getPoint(i);if(n.status===b.Keyword)n.stringResult==="Hor"?t="hor":n.stringResult==="Ver"?t="ver":n.stringResult==="Ang"&&(t="ang");else if(n.status===b.OK&&n.value){t="point";const h=new T(u.t("jig.xline.secondPoint"));h.useBasePoint=!0,h.useDashedLine=!0,h.basePoint=new d.AcGePoint3d(n.value);const p=await k.instance.editor.getPoint(h);if(p.status!==b.OK||!p.value)return;const m={x:p.value.x-n.value.x,y:p.value.y-n.value.y,z:p.value.z-n.value.z};this.appendFiniteXLine(e,n.value,m)||this.showMessage(u.t("jig.xline.invalidDirection"),"warning");continue}else return;if(t==="hor"){const h=new T(u.t("jig.xline.throughPoint")),p=await k.instance.editor.getPoint(h);if(p.status!==b.OK||!p.value)return;this.appendFiniteXLine(e,p.value,{x:1,y:0,z:0});continue}if(t==="ver"){const h=new T(u.t("jig.xline.throughPoint")),p=await k.instance.editor.getPoint(h);if(p.status!==b.OK||!p.value)return;this.appendFiniteXLine(e,p.value,{x:0,y:1,z:0});continue}const r=new ie(u.t("jig.xline.angle")),o=await k.instance.editor.getDouble(r);if(o.status!==b.OK||o.value==null)return;const a=new T(u.t("jig.xline.throughPoint")),l=await k.instance.editor.getPoint(a);if(l.status!==b.OK||!l.value)return;const c=o.value*Math.PI/180;this.appendFiniteXLine(e,l.value,{x:Math.cos(c),y:Math.sin(c),z:0})}}appendFiniteXLine(e,t,i){const n=this.normalizeDirection(i);if(!n)return!1;const r=new d.AcGePoint3d(t.x-n.x*Jt,t.y-n.y*Jt,t.z-n.z*Jt),o=new d.AcGePoint3d(t.x+n.x*Jt,t.y+n.y*Jt,t.z+n.z*Jt);return e.doc.database.tables.blockTable.modelSpace.appendEntity(new d.AcDbLine(r,o)),!0}normalizeDirection(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);if(d.AcGeTol.isPositive(t))return{x:e.x/t,y:e.y/t,z:e.z/t}}}function xd(s){const e=s.htmlTransientManager,t=s.activeLayoutBtrId;Ft(s,"Clear Measurements",()=>{e.deselectAll();for(const i of e.groupsOnLayer(W))(i.layoutId==null||i.layoutId===t)&&e.detach(i.id)}),e.clear(oe),s.isHtmlDirty=!0}class Sd extends z{constructor(){super(),this.mode=F.Read}async execute(e){xd(e.view)}}class Pd extends z{constructor(){super(),this.mode=F.Read,this.recordsUndoStack=!1}async execute(e){const t=e.view;Sa(t,!ir())}}function cs(s,e){const t=e.canvas.getBoundingClientRect(),i=window.devicePixelRatio||1,n=Math.round(t.width),r=Math.round(t.height),o=e.canvasToContainer({x:0,y:0});s.style.left=`${o.x}px`,s.style.top=`${o.y}px`,s.style.width=`${n}px`,s.style.height=`${r}px`,(s.width!==n*i||s.height!==r*i)&&(s.width=n*i,s.height=r*i);const a=s.getContext("2d");return a?(a.clearRect(0,0,s.width,s.height),a.save(),a.scale(i,i),{ctx:a,dpr:i}):null}function Ad(s,e,t,i,n,r=2){const o=cs(s,e);if(!o)return;const{ctx:a}=o,l=e.worldToScreen(t),c=e.worldToScreen(i);a.beginPath(),a.moveTo(l.x,l.y),a.lineTo(c.x,c.y),a.strokeStyle=ve(n),a.lineWidth=r,a.stroke(),a.restore()}function Cd(s,e,t,i,n,r,o=2){const a=cs(s,e);if(!a)return;const{ctx:l}=a,c=e.worldToScreen(t),h=e.worldToScreen(i),p=e.worldToScreen(n);l.strokeStyle=ve(r),l.lineWidth=o,l.beginPath(),l.moveTo(c.x,c.y),l.lineTo(h.x,h.y),l.moveTo(c.x,c.y),l.lineTo(p.x,p.y),l.stroke();const m=Math.hypot(h.x-c.x,h.y-c.y),g=Math.hypot(p.x-c.x,p.y-c.y),f=Math.max(Math.min(m,g)*.3,15),w=Math.atan2(h.y-c.y,h.x-c.x),v=Math.atan2(p.y-c.y,p.x-c.x),x=d.AcGeMathUtil.normalizeAngle(v-w)>Math.PI;l.beginPath(),l.arc(c.x,c.y,f,w,v,x),l.stroke(),l.restore()}function _d(s,e,t,i,n=2.5){const r=cs(s,e);if(!r||t.length<3){r==null||r.ctx.restore();return}const{ctx:o}=r,a=t.map(l=>e.worldToScreen(l));o.beginPath(),o.moveTo(a[0].x,a[0].y);for(let l=1;l<a.length;l++)o.lineTo(a[l].x,a[l].y);o.closePath(),o.fillStyle=Xs(i,.2),o.fill(),o.strokeStyle=ve(i),o.lineWidth=n,o.stroke(),o.restore()}function ds(s,e,t,i,n,r,o,a){const l=e.worldToScreen({x:t.cx,y:t.cy}),c=e.worldToScreen(i),h=e.worldToScreen(n),p=Math.hypot(c.x-l.x,c.y-l.y);if(!(p>0))return;const m=Math.atan2(c.y-l.y,c.x-l.x),g=Math.atan2(h.y-l.y,h.x-l.x),f=a?d.AcGeCircArc2d.tryCreateByThreePoints(i,a,n):void 0,w=f?!f.clockwise:d.AcGeMathUtil.normalizeAngle(g-m)>Math.PI;s.beginPath(),s.arc(l.x,l.y,p,m,g,w),s.strokeStyle=ve(r),s.lineWidth=o,s.stroke()}function Ed(s,e,t,i,n,r,o=4,a){const l=cs(s,e);l&&(ds(l.ctx,e,t,i,n,r,o,a),l.ctx.restore())}function Ld(s){let e=0;const t=s.length;for(let i=0;i<t;i++){const n=(i+1)%t;e+=s[i].x*s[n].y,e-=s[n].x*s[i].y}return Math.abs(e)/2}function lo(s){const e=s.reduce((i,n)=>i+n.x,0)/s.length,t=s.reduce((i,n)=>i+n.y,0)/s.length;return{x:e,y:t}}function Td(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=t.x-s.x,o=t.y-s.y,a=i*r+n*o,l=i*o-n*r;return Math.atan2(Math.abs(l),a)*180/Math.PI}function Et(s,e){const t=e.getBoundingClientRect(),i=window.devicePixelRatio||1,n=`${t.width}px`,r=`${t.height}px`,o=Math.max(1,Math.floor(t.width*i)),a=Math.max(1,Math.floor(t.height*i));s.style.left="0",s.style.top="0",s.style.width!==n&&(s.style.width=n),s.style.height!==r&&(s.style.height=r),s.width!==o&&(s.width=o),s.height!==a&&(s.height=a);const l=s.getContext("2d");return l?(l.setTransform(i,0,0,i,0,0),l.clearRect(0,0,t.width,t.height),l):null}function us(s,e,t,i){const n=t.x-e.x,r=t.y-e.y,o=Math.hypot(n,r)||1,a=n/o,l=r/o,c=12,h={x:t.x-a*c-l*c*.45,y:t.y-l*c+a*c*.45},p={x:t.x-a*c+l*c*.45,y:t.y-l*c-a*c*.45};s.fillStyle=i,s.beginPath(),s.moveTo(t.x,t.y),s.lineTo(h.x,h.y),s.lineTo(p.x,p.y),s.closePath(),s.fill()}function co(s,e,t,i,n=!0,r=2){s.strokeStyle=i,s.lineWidth=r,s.beginPath(),s.moveTo(e.x,e.y),s.lineTo(t.x,t.y),s.stroke(),n&&us(s,t,e,i)}function uo(s,e,t,i,n=1.5){const r=Math.min(e.x,t.x),o=Math.min(e.y,t.y),a=Math.abs(e.x-t.x),l=Math.abs(e.y-t.y);s.fillStyle=i,s.globalAlpha=.28,s.fillRect(r,o,a,l),s.globalAlpha=1,s.strokeStyle=i,s.lineWidth=n,s.strokeRect(r,o,a,l)}class ho{worldDraw(e){return this.subWorldDraw(e)}subGetGripPoints(){return[]}subMoveGripPointsAt(e,t){return this}hitTest(e,t,i){return!1}primaryPoint(){}}function po(s,e){const t=s.viewportToCanvas({x:e.clientX,y:e.clientY}),i=s.screenToWorld(t);return{x:i.x,y:i.y}}function Xe(s,e,t){s.htmlTransientManager.updatePosition(e.id,t)}const Id=4,Qt={capture:!0,passive:!1};function Lt(s){const{view:e,el:t,onDragStart:i,onMove:n,onCommit:r}=s,o=s.cursor??"grab";t.style.pointerEvents="auto",t.style.cursor=o,t.style.touchAction="none",t.style.userSelect="none";let a;const l=c=>{if(c.button!==0)return;const h=c.target;if(c.detail>=2||h!=null&&h.isContentEditable||h!=null&&h.closest('[contenteditable="true"]')||t.querySelector('[contenteditable="true"]'))return;const p=c.pointerId,m=c.clientX,g=c.clientY;let f=!1;const w=()=>{window.removeEventListener("pointermove",v,Qt),window.removeEventListener("pointerup",x,Qt),window.removeEventListener("pointercancel",x,Qt),a===w&&(a=void 0)},v=S=>{if(S.pointerId===p){if(!f){const P=S.clientX-m,A=S.clientY-g;if(P*P+A*A<Id*Id)return;f=!0,S.preventDefault(),t.style.cursor="grabbing",i==null||i()}n(po(e,S),S),e.isHtmlDirty=!0}},x=S=>{S.pointerId===p&&(w(),f&&(t.style.cursor=o,r()))};a==null||a(),a=w,window.addEventListener("pointermove",v,Qt),window.addEventListener("pointerup",x,Qt),window.addEventListener("pointercancel",x,Qt)};return t.addEventListener("pointerdown",l),()=>{t.removeEventListener("pointerdown",l),a==null||a()}}function hs(s){const{view:e,tipEl:t,bubbleEl:i,state:n,constrainTip:r,onDragStart:o,onLiveChange:a,onCommit:l}=s;t.element.style.width="14px",t.element.style.height="14px";let c={tip:{...n.tip},anchor:{...n.anchor}};const h=g=>Math.hypot(g.tip.x-c.tip.x,g.tip.y-c.tip.y)<1e-9&&Math.hypot(g.anchor.x-c.anchor.x,g.anchor.y-c.anchor.y)<1e-9,p=Lt({view:e,el:t.element,onDragStart:()=>{c={tip:{...n.tip},anchor:{...n.anchor}},o==null||o()},onMove:g=>{n.tip=r?r(g):g,Xe(e,t,n.tip),a()},onCommit:()=>{const g={tip:{...n.tip},anchor:{...n.anchor}};h(g)||l(g)}}),m=Lt({view:e,el:i.element,onDragStart:()=>{c={tip:{...n.tip},anchor:{...n.anchor}},o==null||o()},onMove:g=>{n.anchor=g,Xe(e,i,n.anchor),a()},onCommit:()=>{const g={tip:{...n.tip},anchor:{...n.anchor}};h(g)||l(g)}});return()=>{p(),m()}}class ei extends ho{constructor(e,t,i){super(),this.entityId=e,this.layoutIdOption=t,this.style=i}get id(){return this.entityId}hitTest(e,t,i){return Hs(this.toRecord().geometry,e,t,i)}commit(e,t){const i=this.subWorldDrawWithDb(e,t);Ta(e,i.group,{...i.extras,dispose:i.dispose})}subWorldDraw(e){throw new Error("Use AcApMeasureEntity.commit(view, db) instead of worldDraw")}createGroup(e){return new M.AcTrHtmlGroup({id:this.entityId,layer:W,layoutId:this.resolveLayoutId(e),selectable:!0})}resolveLayoutId(e){return this.layoutIdOption??e.activeLayoutBtrId}}class Di extends ei{constructor(e,t,i,n){super(n.id??`angle-${Date.now()}`,n.layoutId,n.style),this.vertex=e,this.arm1=t,this.arm2=i}static create(e,t,i,n,r){return new Di(e,t,i,{style:n,id:r==null?void 0:r.id,layoutId:r==null?void 0:r.layoutId})}primaryPoint(){return{x:this.vertex.x,y:this.vertex.y,z:0}}toRecord(e){return{id:this.entityId,type:"angle",layoutId:e,style:mt(this.style),geometry:{type:"angle",vertex:{x:this.vertex.x,y:this.vertex.y},arm1:{x:this.arm1.x,y:this.arm1.y},arm2:{x:this.arm2.x,y:this.arm2.y}}}}subWorldDrawWithDb(e,t){const i=this.style.color,n=Td(this.vertex,this.arm1,this.arm2),r=this.resolveLayoutId(e),o=new M.AcTrHtmlCanvasOverlay({id:`angle-canvas-${this.entityId}`,container:e.container,layer:W,layoutId:r}),a=(I=this.style)=>Cd(o.canvas,e,this.vertex,this.arm1,this.arm2,I.color,Ee(I.lineWeight));a();const l=()=>a(St(this.entityId)??this.style);e.events.viewChanged.addEventListener(l);const c=this.arm1.x-this.vertex.x,h=this.arm1.y-this.vertex.y,p=this.arm2.x-this.vertex.x,m=this.arm2.y-this.vertex.y,g=Math.hypot(c,h),f=Math.hypot(p,m),w=g>0?c/g:1,v=g>0?h/g:0,x=f>0?p/f:1,S=f>0?m/f:0;let P=w+x,A=v+S;const _=Math.hypot(P,A);_>0?(P/=_,A/=_):(P=-v,A=w);const C=Math.max(Math.min(g,f)*.4,Math.max(g,f)*.15),O={x:this.vertex.x+P*C,y:this.vertex.y+A*C};return{group:this.createGroup(e).add(new M.AcTrHtmlDot({id:`${this.entityId}-dotV`,color:i,worldPosition:this.vertex,layer:W}),new M.AcTrHtmlDot({id:`${this.entityId}-dot1`,color:i,worldPosition:this.arm1,layer:W}),new M.AcTrHtmlDot({id:`${this.entityId}-dot2`,color:i,worldPosition:this.arm2,layer:W}),new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:i,text:cn(t,n*Math.PI/180),worldPosition:O,layer:W,fontSize:this.style.fontSize})).addCanvas(o),entityIds:[],dispose:()=>{e.events.viewChanged.removeEventListener(l)},extras:{style:this.style,value:{kind:"angle",radians:n*Math.PI/180},snapshot:this.toRecord(r),redraw:a}}}}class Oi extends ei{constructor(e,t,i,n,r){super(n.id??`arc-${Date.now()}`,n.layoutId,n.style),this.geom=e,this.start=t,this.end=i,this.through=r}resolveMeasuredArc(){return this.through?d.AcGeCircArc2d.tryCreateByThreePoints(this.start,this.through,this.end):d.AcGeCircArc2d.tryCreateShorterArc(this.start,this.end,{x:this.geom.cx,y:this.geom.cy})}static create(e,t,i,n,r){return new Oi(e,t,i,{style:n,id:r==null?void 0:r.id,layoutId:r==null?void 0:r.layoutId},r==null?void 0:r.through)}primaryPoint(){var t;const e=(t=this.resolveMeasuredArc())==null?void 0:t.midPoint;return e?{x:e.x,y:e.y,z:0}:{x:this.start.x,y:this.start.y,z:0}}toRecord(e){return{id:this.entityId,type:"arc",layoutId:e,style:mt(this.style),geometry:{type:"arc",center:{x:this.geom.cx,y:this.geom.cy},radius:this.geom.r,start:{x:this.start.x,y:this.start.y},end:{x:this.end.x,y:this.end.y},...this.through?{through:{x:this.through.x,y:this.through.y}}:{}}}}subWorldDrawWithDb(e,t){var p;const i=this.style.color,n=((p=this.resolveMeasuredArc())==null?void 0:p.length)??0,r=this.primaryPoint(),o=this.resolveLayoutId(e),a=new M.AcTrHtmlCanvasOverlay({id:`arc-canvas-${this.entityId}`,container:e.container,layer:W,layoutId:o}),l=(m=this.style)=>Ed(a.canvas,e,this.geom,this.start,this.end,m.color,Ee(m.lineWeight),this.through);l();const c=()=>l(St(this.entityId)??this.style);return e.events.viewChanged.addEventListener(c),{group:this.createGroup(e).add(new M.AcTrHtmlDot({id:`${this.entityId}-dot1`,color:i,worldPosition:this.start,layer:W}),...this.through?[new M.AcTrHtmlDot({id:`${this.entityId}-dot-through`,color:i,worldPosition:this.through,layer:W})]:[],new M.AcTrHtmlDot({id:`${this.entityId}-dot2`,color:i,worldPosition:this.end,layer:W}),new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:i,text:_e(t,n),worldPosition:r,layer:W,fontSize:this.style.fontSize})).addCanvas(a),entityIds:[],dispose:()=>{e.events.viewChanged.removeEventListener(c)},extras:{style:this.style,value:{kind:"length",value:n},snapshot:this.toRecord(o),redraw:l}}}}class Bi extends ei{constructor(e,t){super(t.id??`area-${Date.now()}`,t.layoutId,t.style),this.points=e}static create(e,t,i){return new Bi(e,{style:t,id:i==null?void 0:i.id,layoutId:i==null?void 0:i.layoutId})}primaryPoint(){if(this.points.length===0)return;const e=lo(this.points);return{x:e.x,y:e.y,z:0}}toRecord(e){return{id:this.entityId,type:"area",layoutId:e,style:mt(this.style),geometry:{type:"area",points:this.points.map(t=>({x:t.x,y:t.y}))}}}subWorldDrawWithDb(e,t){if(this.points.length<3)return{group:this.createGroup(e),entityIds:[],dispose:()=>{},extras:{}};const i=this.style.color,n=Ld(this.points),r=this.resolveLayoutId(e),o=lo(this.points),a=new M.AcTrHtmlCanvasOverlay({id:`area-canvas-${this.entityId}`,container:e.container,layer:W,layoutId:r}),l=(p=this.style)=>_d(a.canvas,e,this.points,p.color,Ee(p.lineWeight));l();const c=()=>l(St(this.entityId)??this.style);return e.events.viewChanged.addEventListener(c),{group:this.createGroup(e).add(new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:i,text:`${_e(t,n)}²`,worldPosition:o,layer:W,fontSize:this.style.fontSize}),...this.points.map((p,m)=>new M.AcTrHtmlDot({id:`${this.entityId}-dot${m}`,color:i,worldPosition:p,layer:W}))).addCanvas(a),entityIds:[],dispose:()=>{e.events.viewChanged.removeEventListener(c)},extras:{style:this.style,value:{kind:"area",value:n},snapshot:this.toRecord(r),redraw:l}}}}function Og(s,e){const t=e.x-s.x,i=e.y-s.y;return Math.sqrt(t*t+i*i)}class ji extends ei{constructor(e,t,i){super(i.id??`dist-${Date.now()}`,i.layoutId,i.style),this.p1=e,this.p2=t}static create(e,t,i,n){return new ji(e,t,{style:i,id:n==null?void 0:n.id,layoutId:n==null?void 0:n.layoutId})}primaryPoint(){return{x:(this.p1.x+this.p2.x)/2,y:(this.p1.y+this.p2.y)/2,z:0}}toRecord(e){return{id:this.entityId,type:"distance",layoutId:e,style:mt(this.style),geometry:{type:"distance",start:{x:this.p1.x,y:this.p1.y},end:{x:this.p2.x,y:this.p2.y}}}}subWorldDrawWithDb(e,t){const i=Og(this.p1,this.p2),n=this.style.color,r=this.resolveLayoutId(e),o=this.primaryPoint(),a=new M.AcTrHtmlCanvasOverlay({id:`dist-canvas-${this.entityId}`,container:e.container,layer:W,layoutId:r}),l=(p=this.style)=>Ad(a.canvas,e,this.p1,this.p2,p.color,Ee(p.lineWeight));l();const c=()=>l(St(this.entityId)??this.style);return e.events.viewChanged.addEventListener(c),{group:this.createGroup(e).add(new M.AcTrHtmlDot({id:`${this.entityId}-dot1`,color:n,worldPosition:this.p1,layer:W}),new M.AcTrHtmlDot({id:`${this.entityId}-dot2`,color:n,worldPosition:this.p2,layer:W}),new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:n,text:_e(t,i),worldPosition:o,layer:W,fontSize:this.style.fontSize})).addCanvas(a),entityIds:[],dispose:()=>{e.events.viewChanged.removeEventListener(c)},extras:{style:this.style,value:{kind:"length",value:i},snapshot:this.toRecord(r),redraw:l}}}}class Fi extends ei{constructor(e,t){super(t.id??`point-${Date.now()}`,t.layoutId,t.style),this.point=e}static create(e,t,i){return new Fi(e,{style:t,id:i==null?void 0:i.id,layoutId:i==null?void 0:i.layoutId})}primaryPoint(){return{x:this.point.x,y:this.point.y,z:0}}toRecord(e){return{id:this.entityId,type:"point",layoutId:e,style:mt(this.style),geometry:{type:"point",position:{x:this.point.x,y:this.point.y}}}}subWorldDrawWithDb(e,t){const i=this.resolveLayoutId(e),n={kind:"coordinate",x:this.point.x,y:this.point.y},r=this.style.color;return{group:this.createGroup(e).add(new M.AcTrHtmlDot({id:`${this.entityId}-dot`,color:r,worldPosition:this.point,layer:W}),new M.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:r,text:$s(t,n),worldPosition:this.point,layer:W,fontSize:this.style.fontSize,transform:"translate(-50%, calc(-50% - 16px))"})),entityIds:[],dispose:()=>{},extras:{style:this.style,value:n,snapshot:this.toRecord(i)}}}}function Md(s){const e=ba(s.style),t={id:s.id,layoutId:s.layoutId,style:e},i=s.geometry;switch(i.type){case"distance":return new ji({x:i.start.x,y:i.start.y,z:0},{x:i.end.x,y:i.end.y,z:0},t);case"angle":return new Di({x:i.vertex.x,y:i.vertex.y,z:0},{x:i.arm1.x,y:i.arm1.y,z:0},{x:i.arm2.x,y:i.arm2.y,z:0},t);case"area":return new Bi(i.points.map(n=>({x:n.x,y:n.y,z:0})),t);case"arc":return new Oi({cx:i.center.x,cy:i.center.y,r:i.radius},i.start,i.end,t,i.through);case"point":return new Fi({x:i.position.x,y:i.position.y,z:0},t)}}function Bg(s){return`${s}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Dd(s,e,t){const i=t.geometry.type==="distance"?"dist":t.geometry.type,n={...t,id:Bg(i)};try{return Md(n).commit(s,e),!0}catch{return!1}}function jg(s,e){if(typeof document>"u")return;const t=new Blob([e],{type:"application/json;charset=utf-8"}),i=URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download=s,n.click(),URL.revokeObjectURL(i)}function Fg(){return new Promise(s=>{if(typeof document>"u"){s(void 0);return}const e=document.createElement("input");e.type="file",e.accept=".json,application/json";let t=!1;const i=n=>{t||(t=!0,s(n))};e.addEventListener("cancel",()=>i()),e.onchange=async()=>{var r;const n=(r=e.files)==null?void 0:r[0];if(!n){i();return}i(await n.text())},e.click()})}class Od extends z{constructor(){super(),this.mode=F.Read,this.recordsUndoStack=!1}async execute(e){const t=e.view,i=e.doc.fileName||e.doc.docTitle,n=va({version:1,drawingName:i,measurements:Ea(t)});jg(ka(i),n)}}class Bd extends z{constructor(){super(),this.mode=F.Read,this.recordsUndoStack=!1}async execute(e){new ce(u.t("jig.measurement.import.chooseFile"));const t=await Fg();if(t==null)return;let i;try{i=wa(t)}catch(o){console.error(o);return}const n=e.view,r=e.doc.database;Ft(n,"Import Measurements",()=>{for(const o of i.measurements)Dd(n,r,o)})}}class we{constructor(e,t,i){this.drawFn=null,this.onViewChanged=()=>this.acapPaint(),this.view=e,this.overlay=new M.AcTrHtmlCanvasOverlay({id:t,container:e.container,layer:i,layoutId:e.activeLayoutBtrId}),e.htmlTransientManager.add(this.overlay),e.events.viewChanged.addEventListener(this.onViewChanged)}get id(){return this.overlay.id}acapSetDraw(e){this.drawFn=e,this.acapPaint(),this.view.isHtmlDirty=!0}acapClear(){this.acapSetDraw(null)}acapDispose(){this.view.events.viewChanged.removeEventListener(this.onViewChanged),this.view.htmlTransientManager.remove(this.overlay.id),this.view.isHtmlDirty=!0}acapPaint(){var t;const e=Et(this.overlay.canvas,this.view.container);e&&((t=this.drawFn)==null||t.call(this,e,this.view))}}function rt(s,e,t,i,n,r,o){const a=typeof n=="string"?n:ve(n),l=e.worldToScreen(t),c=e.worldToScreen(i);s.strokeStyle=a,s.lineWidth=r,o!=null&&o.dashed&&s.setLineDash([8,5]),s.beginPath(),s.moveTo(l.x,l.y),s.lineTo(c.x,c.y),s.stroke(),o!=null&&o.dashed&&s.setLineDash([]),o!=null&&o.arrow&&us(s,l,c,a)}function ti(s,e,t,i,n,r){if(t.length<2)return;const o=typeof i=="string"?i:ve(i),a=t.map(l=>e.worldToScreen(l));s.strokeStyle=o,s.lineWidth=n,r!=null&&r.dashed&&s.setLineDash([8,5]),s.beginPath(),s.moveTo(a[0].x,a[0].y);for(let l=1;l<a.length;l++)s.lineTo(a[l].x,a[l].y);r!=null&&r.closed&&s.closePath(),s.stroke(),r!=null&&r.dashed&&s.setLineDash([])}function mo(s,e,t,i,n,r){if(i<=0)return;const o=typeof n=="string"?n:ve(n),a=e.worldToScreen(t),l=e.worldToScreen({x:t.x+i,y:t.y}),c=Math.hypot(l.x-a.x,l.y-a.y);s.strokeStyle=o,s.lineWidth=r,s.beginPath(),s.arc(a.x,a.y,c,0,Math.PI*2),s.stroke()}function zg(s,e,t,i,n,r){uo(s,e.worldToScreen(t),e.worldToScreen(i),n,r)}function yo(s,e){return[{x:s.x,y:s.y},{x:e.x,y:s.y},{x:e.x,y:e.y},{x:s.x,y:e.y}]}function Ng(s,e,t){const i=e.x-s.x,n=e.y-s.y,r=t.x-s.x,o=t.y-s.y,a=i*r+n*o,l=i*o-n*r;return Math.atan2(Math.abs(l),a)*180/Math.PI}function jd(s,e,t,i,n,r,o){Di.create(t,i,n,r,o).commit(s,e)}class Rg extends R{constructor(e,t,i){super(e),this._vertex=t,this._cursor=t,this._color=i,this._preview=new we(e,`live-angle-arm1-${Date.now()}`,oe)}get entity(){return null}update(e){this._cursor=e;const t=Ee(tt());this._preview.acapSetDraw((i,n)=>{rt(i,n,this._vertex,this._cursor,this._color,t)})}end(){super.end(),this._preview.acapDispose()}}class Vg extends R{constructor(e,t,i,n,r){super(e),this._view=e,this._vertex=i,this._arm1=n,this._arm2=i,this._color=r,this._db=t,this._badgeId=`live-angle-badge-${Date.now()}`,this._htManager=this._view.htmlTransientManager,this._badge=new M.AcTrHtmlBadge({id:this._badgeId,color:r,worldPosition:i,layer:oe,layoutId:this._view.activeLayoutBtrId,fontSize:Be(),transform:"translate(-50%, calc(-50% - 30px))"}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new we(this._view,`live-angle-arm2-${Date.now()}`,oe)}get entity(){return null}update(e){this._arm2=e,this._color=Oe(this._db),this._badge.setColor(this._color),this._badge.setFontSize(Be());const t=Ee(tt());this._preview.acapSetDraw((n,r)=>{rt(n,r,this._vertex,this._arm1,this._color,t,{dashed:!0}),rt(n,r,this._vertex,this._arm2,this._color,t)});const i=Ng(this._vertex,this._arm1,e);this._badge.setText(cn(this._db,i*Math.PI/180)),this._badge.setPosition(this._vertex),this._badge.object.visible=!0}end(){super.end(),this._preview.acapDispose(),this._htManager.remove(this._badgeId)}}class Fd extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Oe(i);await e.view.withMode(ye.SELECTION,()=>t.withCursor(Le.Crosshair,async()=>{const r=new T(u.t("jig.measureAngle.vertex")),o=await t.getPoint(r);if(o.status!==b.OK)return;const a=o.value,l=new T(u.t("jig.measureAngle.arm1"));l.useBasePoint=!0,l.jig=new Rg(e.view,a,n);const c=await t.getPoint(l);if(c.status!==b.OK)return;const h=c.value,p=new T(u.t("jig.measureAngle.arm2"));p.jig=new Vg(e.view,i,a,h,n);const m=await t.getPoint(p);if(m.status!==b.OK)return;const g=m.value;jd(e.view,i,a,h,g,ut(i))}))}}class Gg extends R{constructor(e,t,i,n){super(e),this._onMove=n}get entity(){return null}update(e){this._onMove(e)}}function Kg(s,e,t,i){const n=e.x-s.x,r=e.y-s.y,o=i.x-t.x,a=i.y-t.y,l=n*a-r*o;if(Math.abs(l)<1e-10)return!1;const c=t.x-s.x,h=t.y-s.y,p=(c*a-h*o)/l,m=(c*r-h*n)/l;return p>0&&p<1&&m>0&&m<1}function Ug(s){let e=0;const t=s.length;for(let i=0;i<t;i++){const n=(i+1)%t;e+=s[i].x*s[n].y,e-=s[n].x*s[i].y}return Math.abs(e)/2}function Hg(s){const e=s.reduce((i,n)=>i+n.x,0)/s.length,t=s.reduce((i,n)=>i+n.y,0)/s.length;return{x:e,y:t}}function zd(s,e,t,i,n){t.length<3||Bi.create(t,i,n).commit(s,e)}class Nd extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Oe(i),r=ut(i),o=Ee(r.lineWeight),a=[],l=new M.AcTrHtmlCanvasOverlay({id:`live-area-canvas-${Date.now()}`,container:e.view.container,layer:oe,layoutId:e.view.activeLayoutBtrId}),c=l.canvas,h=e.view.htmlTransientManager;h.add(l);const p=`live-area-badge-${Date.now()}`,m=new M.AcTrHtmlBadge({id:p,color:n,worldPosition:{x:0,y:0},layer:oe,layoutId:e.view.activeLayoutBtrId,fontSize:r.fontSize});m.object.visible=!1,h.add(m);const g=v=>{const x=e.view.canvas.getBoundingClientRect(),S=window.devicePixelRatio||1,P=Math.round(x.width),A=Math.round(x.height),_=e.view.canvasToContainer({x:0,y:0});c.style.left=`${_.x}px`,c.style.top=`${_.y}px`,c.style.width=`${P}px`,c.style.height=`${A}px`,(c.width!==P*S||c.height!==A*S)&&(c.width=P*S,c.height=A*S);const C=c.getContext("2d");if(!C||a.length<1)return;C.clearRect(0,0,c.width,c.height),C.save(),C.scale(S,S);const O=a.map(I=>e.view.worldToScreen(I)),B=v?[...O,e.view.worldToScreen(v)]:O;if(B.length>=3){C.beginPath(),C.moveTo(B[0].x,B[0].y);for(let I=1;I<B.length;I++)C.lineTo(B[I].x,B[I].y);C.closePath(),C.fillStyle=Xs(n,.2),C.fill()}if(O.length>=2){C.beginPath(),C.moveTo(O[0].x,O[0].y);for(let I=1;I<O.length;I++)C.lineTo(O[I].x,O[I].y);C.strokeStyle=ve(n),C.lineWidth=o,C.setLineDash([8,5]),C.stroke(),C.setLineDash([])}if(v&&O.length>=1){const I=O[O.length-1],N=e.view.worldToScreen(v);C.beginPath(),C.moveTo(I.x,I.y),C.lineTo(N.x,N.y),C.strokeStyle=ve(n),C.lineWidth=o,C.stroke()}C.restore()},f=()=>g();e.view.events.viewChanged.addEventListener(f);const w=()=>{h.remove(p),h.remove(l.id),e.view.events.viewChanged.removeEventListener(f)};try{await e.view.withMode(ye.SELECTION,()=>t.withCursor(Le.Crosshair,async()=>{const v=await t.getPoint(new T(u.t("jig.measureArea.firstPoint")));if(v.status!==b.OK)return;const x=v.value;a.push(x),g();try{for(;a.length<50;){const S=new T(u.t("jig.measureArea.nextPoint"));S.useBasePoint=!0,S.allowNone=!0;const P=C=>{if(a.length<2){g(C);return}const O=[...a,C],B=Ug(O);m.setText(`${_e(i,B)}²`),m.setPosition(Hg(O)),m.object.visible=!0,g(C)};S.jig=new Gg(e.view,a[a.length-1],n,P);const A=await t.getPoint(S);if(A.status!==b.OK)break;const _=A.value;if(m.object.visible=!1,a.length>=3){const C=e.view.worldToScreen(_),O=B=>{const I=e.view.worldToScreen(B),N=C.x-I.x,G=C.y-I.y;return N*N+G*G<=196};if(O(a[0])||O(a[a.length-1]))break}if(a.length>=3){const C=a[a.length-1];let O=!1;for(let B=0;B<a.length-2;B++)if(Kg(C,_,a[B],a[B+1])){O=!0;break}if(O)break}a.push(_),g()}}catch{}}))}finally{w()}a.length<3||zd(e.view,i,a,ut(i))}}const Wg=1e-12;function Rd(s,e,t,i){const n=s-t,r=e-i;return n*n+r*r}function $g(s,e,t){const i=t.x-e.x,n=t.y-e.y;if(i*i+n*n<1e-24)return 0;const r=s.radius>0?s.radius:1,o=Math.max(1e-16,1e-12*r*r),a=Rd(e.x,e.y,s.startPoint.x,s.startPoint.y)<=o,l=Rd(e.x,e.y,s.endPoint.x,s.endPoint.y)<=o;if(!a&&!l)return 0;const c=s.getPoints(8);if(c.length<3)return 0;const h=a&&!l?c[1]:c[c.length-2],p=h.x-e.x,m=h.y-e.y,g=Math.hypot(p,m);return g>1e-18?(i*p+n*m)/g:0}function Yg(s,e,t,i){const n=Math.max(1e-18,Math.abs(t)*1e-9);return s<t-n?!0:s>t+n?!1:e>i}function Vd(s,e,t){return Math.abs(Math.hypot(s.x-e.cx,s.y-e.cy)-e.r)<=Math.max(1e-6,e.r*1e-5)}function Zg(s,e){return Math.abs(s.cx-e.cx)<=1e-8&&Math.abs(s.cy-e.cy)<=1e-8&&Math.abs(s.r-e.r)<=1e-8}function Gd(s,e,t,i,n){return{x:s+(n===-1?-1:1)*t*Math.cos(i),y:e+t*Math.sin(i)}}function Xg(s,e){let t=e-s;for(;t<=0;)t+=d.TAU;for(;t>d.TAU;)t-=d.TAU;return t}function qg(s){if(!(s.radius>0))return;const e=s.normal.z>=0?1:-1,t=s.center.x,i=s.center.y,n=s.radius,r=Gd(t,i,n,s.startAngle,e),o=Gd(t,i,n,s.endAngle,e),a=Xg(s.startAngle,s.endAngle);if(!(a>1e-12)||a>=d.TAU-1e-12)return;const l=new d.AcGeCircArc2d(r,o,e*Math.tan(a/4));return l.radius>0?l:void 0}function Jg(s){var n;const e=(n=s._geo)==null?void 0:n.vertices;if(e&&e.length>1)return e.map(r=>({x:r.x,y:r.y,bulge:r.bulge??0}));const t=s.numberOfVertices,i=s.getBulgeAt;return Array.from({length:t},(r,o)=>{const a=s.getPoint2dAt(o);return{x:a.x,y:a.y,bulge:(i==null?void 0:i(o))??0}})}function Qg(s){if(s instanceof d.AcDbCircle)return s.radius>0?[new d.AcGeCircArc2d({x:s.center.x,y:s.center.y},s.radius,0,Math.PI*2,!1)]:[];if(s instanceof d.AcDbArc){const n=qg(s);return n?[n]:[]}if(!(s instanceof d.AcDbPolyline))return[];const e=Jg(s);if(e.length<2)return[];const t=s.closed?e.length:e.length-1,i=[];for(let n=0;n<t;n++){const r=e[n],o=e[(n+1)%e.length];if(!(Math.abs(r.bulge)>Wg))continue;const a=new d.AcGeCircArc2d(r,o,r.bulge);a.radius>0&&i.push(a)}return i}const ps=20,ef=.02;function tf(s){return d.AcGeMathUtil.normalizeAngle(s+Math.PI)-Math.PI}function Kd(s,e,t,i){const n=Math.atan2(s.y-t.cy,s.x-t.cx),r=Math.atan2(e.y-t.cy,e.x-t.cx),o=d.AcGeMathUtil.normalizeAngle(i?n-r:r-n);if(!(o>1e-10)||o>=Math.PI*2-1e-10)return;const a=i?n-o/2:n+o/2;return{through:{x:t.cx+t.r*Math.cos(a),y:t.cy+t.r*Math.sin(a)},length:o*t.r}}function Ie(s){return{x:s.x,y:s.y}}function go(s){return{cx:s.center.x,cy:s.center.y,r:s.radius}}function Ud(s,e){const t=s.x-e.cx,i=s.y-e.cy,n=Math.hypot(t,i);if(!(n>0))return{x:e.cx+e.r,y:e.cy,z:0};const r=e.r/n;return{x:e.cx+t*r,y:e.cy+i*r,z:0}}function fo(s,e){const t=s.doc.database.tables.blockTable,i=s.view.curPos,n=new Set,r=[...s.view.pick(i,ps),...s.view.pick(e,ps)].filter(p=>n.has(p.id)?!1:(n.add(p.id),!0)),o=s.view.worldToScreen(i),a={x:i.x,y:i.y,z:0};let l=null,c=ps,h=-1/0;for(const p of r){const m=t.getEntityById(p.id);if(m)for(const g of Qg(m)){if(!(g.radius>0))continue;const f=g.nearestPoint(a),w=s.view.worldToScreen(f),v=Math.hypot(o.x-w.x,o.y-w.y);if(v>ps)continue;const x=$g(g,{x:f.x,y:f.y},{x:i.x,y:i.y});(!l||Yg(v*v,x,c*c,h))&&(c=v,h=x,l={geom:go(g),snapped:{x:f.x,y:f.y,z:0}})}}return l}function bo(s,e,t,i,n,r,o,a){Oi.create(t,i,r,o,{...a,through:n}).commit(s,e)}class nf extends R{constructor(e,t){super(e.view),this._ctx=e,this._indicatorId=`live-arc-snap-${Date.now()}`,this._htManager=e.view.htmlTransientManager,this._indicator=new M.AcTrHtmlSnapIndicator({id:this._indicatorId,color:t,worldPosition:{x:0,y:0,z:0},layer:oe,layoutId:e.view.activeLayoutBtrId}),this._indicator.object.visible=!1,this._htManager.add(this._indicator)}get entity(){return null}update(e){const t=fo(this._ctx,e);if(t){this._indicator.setPosition(t.snapped),this._indicator.object.visible=!0;return}this._indicator.object.visible=!1}end(){super.end(),this._htManager.remove(this._indicatorId)}}class sf extends R{constructor(e,t,i,n,r){super(e.view),this._baseClockwise=null,this._ctx=e,this._view=e.view,this._geom=i,this._start=Ie(n),this._db=t,this._color=r,this._lastAngle=Math.atan2(n.y-i.cy,n.x-i.cx),this._htManager=this._view.htmlTransientManager,this._indicatorId=`live-arc-end-snap-${Date.now()}`,this._indicator=new M.AcTrHtmlSnapIndicator({id:this._indicatorId,color:r,worldPosition:n,layer:oe,layoutId:this._view.activeLayoutBtrId}),this._htManager.add(this._indicator),this._badgeId=`live-arc-locked-badge-${Date.now()}`,this._badge=new M.AcTrHtmlBadge({id:this._badgeId,color:r,worldPosition:n,layer:oe,layoutId:this._view.activeLayoutBtrId,fontSize:Be()}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new we(this._view,`live-arc-locked-${Date.now()}`,oe)}get entity(){return null}get geom(){return this._geom}get clockwise(){return(this._baseClockwise??!1)!==this._isCtrlFlipped()}_isCtrlFlipped(){return k.instance.editor.getInputToggles().ctrlArcFlip}_trackSweepDirection(e){const t=Math.atan2(e.y-this._geom.cy,e.x-this._geom.cx);if(this._baseClockwise==null){const i=tf(t-this._lastAngle);Math.abs(i)>ef&&(this._baseClockwise=i<0)}this._lastAngle=t}update(e){const t=this._view.curPos,i=fo(this._ctx,e);i&&Vd(this._start,i.geom)&&!Zg(this._geom,i.geom)&&(this._geom=i.geom,this._baseClockwise=null,this._lastAngle=Math.atan2(this._start.y-i.geom.cy,this._start.x-i.geom.cx));const n=Ud(t,this._geom),r=Ie(n);this._trackSweepDirection(r),this._color=Oe(this._db),this._indicator.setPosition(n),this._badge.setColor(this._color),this._badge.setFontSize(Be());const o=Ee(tt()),a=Kd(this._start,r,this._geom,this.clockwise);if(this._preview.acapSetDraw((l,c)=>{ds(l,c,this._geom,this._start,r,this._color,o,a==null?void 0:a.through)}),!a){this._badge.object.visible=!1;return}this._badge.setText(_e(this._db,a.length)),this._badge.setPosition(a.through),this._badge.object.visible=!0}end(){super.end(),this._preview.acapDispose(),this._htManager.remove(this._indicatorId),this._htManager.remove(this._badgeId)}}class rf extends R{constructor(e,t,i){super(e),this._start=t,this._cursor=t,this._color=i,this._preview=new we(e,`live-arc-through-${Date.now()}`,oe)}get entity(){return null}update(e){this._cursor=e;const t=Ee(tt());this._preview.acapSetDraw((i,n)=>{rt(i,n,this._start,this._cursor,this._color,t)})}end(){super.end(),this._preview.acapDispose()}}class of extends R{constructor(e,t,i,n,r){super(e),this._view=e,this._start=Ie(i),this._through=Ie(n),this._end=Ie(n),this._color=r,this._db=t,this._badgeId=`live-arc-badge-${Date.now()}`,this._htManager=this._view.htmlTransientManager,this._badge=new M.AcTrHtmlBadge({id:this._badgeId,color:r,worldPosition:i,layer:oe,layoutId:this._view.activeLayoutBtrId,fontSize:Be()}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new we(this._view,`live-arc-end-${Date.now()}`,oe)}get entity(){return null}update(e){this._end=Ie(e),this._color=Oe(this._db),this._badge.setColor(this._color),this._badge.setFontSize(Be());const t=Ee(tt()),i=d.AcGeCircArc2d.tryCreateByThreePoints(this._start,this._through,this._end),n=i?go(i):null;if(this._preview.acapSetDraw((r,o)=>{if(!n){ti(r,o,[this._start,this._through,this._end],this._color,t);return}ds(r,o,n,this._start,this._end,this._color,t,this._through)}),!i){this._badge.object.visible=!1;return}this._badge.setText(_e(this._db,i.length)),this._badge.setPosition(i.midPoint),this._badge.object.visible=!0}end(){super.end(),this._preview.acapDispose(),this._htManager.remove(this._badgeId)}}class Hd extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Oe(i),r=e.view;await e.view.withMode(ye.SELECTION,()=>t.withCursor(Le.Crosshair,async()=>{t.resetInputToggles();const o=new T(u.t("jig.measureArc.startPoint"));o.jig=new nf(e,n);const a=await t.getPoint(o);if(a.status!==b.OK)return;const l=a.value,c=fo(e,l);if(c){const A=Vd(Ie(l),c.geom)?l:c.snapped;await this.commitLockedArc(e,r,i,n,c.geom,A);return}const h=new T(u.t("jig.measureArc.throughPoint"));h.useBasePoint=!0,h.jig=new rf(e.view,l,n);const p=await t.getPoint(h);if(p.status!==b.OK)return;const m=p.value,g=new T(u.t("jig.measureArc.endPoint"));g.jig=new of(e.view,i,l,m,n);const f=await t.getPoint(g);if(f.status!==b.OK)return;const w=f.value,v=Ie(l),x=Ie(m),S=Ie(w),P=d.AcGeCircArc2d.tryCreateByThreePoints(v,x,S);if(!P){this.showMessage(u.t("jig.measureArc.invalidPoints"),"warning");return}bo(r,i,go(P),v,x,S,ut(i))}))}async commitLockedArc(e,t,i,n,r,o){e.view.editor.resetInputToggles();const a=t.htmlTransientManager,l=`live-arc-locked-dot-${Date.now()}`;a.add(new M.AcTrHtmlDot({id:l,color:n,worldPosition:o,layer:oe,layoutId:t.activeLayoutBtrId}));const c=new T(u.t("jig.measureArc.lockedEndPoint")),h=new sf(e,i,r,o,n);c.jig=h;let p;try{const v=await e.view.editor.getPoint(c);if(v.status!==b.OK)return;p=v.value}finally{a.remove(l)}if(!p)return;const m=h.geom,g=Ie(o),f=Ie(Ud(p,m)),w=Kd(g,f,m,h.clockwise);if(!w){this.showMessage(u.t("jig.measureArc.invalidPoints"),"warning");return}bo(t,i,m,g,w.through,f,ut(i))}}function af(s,e){const t=e.x-s.x,i=e.y-s.y;return Math.sqrt(t*t+i*i)}function Wd(s,e,t,i,n,r){ji.create(t,i,n,r).commit(s,e)}class $d extends R{constructor(e,t,i,n){super(e),this._view=e,this._p1=i,this._p2=i,this._db=t,this._color=n,this._badgeId=`live-dist-badge-${Date.now()}`,this._htManager=this._view.htmlTransientManager,this._badge=new M.AcTrHtmlBadge({id:this._badgeId,color:n,worldPosition:i,layer:oe,layoutId:this._view.activeLayoutBtrId,fontSize:Be()}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new we(this._view,`live-dist-stroke-${Date.now()}`,oe)}get entity(){return null}update(e){this._p2=e,this._color=Oe(this._db),this._badge.setColor(this._color),this._badge.setFontSize(Be());const t=af(this._p1,e),i=Ee(tt());if(this._preview.acapSetDraw((n,r)=>{rt(n,r,this._p1,this._p2,this._color,i)}),t<1e-4){this._badge.object.visible=!1;return}this._badge.setText(_e(this._db,t)),this._badge.setPosition({x:(this._p1.x+e.x)/2,y:(this._p1.y+e.y)/2}),this._badge.object.visible=!0}end(){super.end(),this._preview.acapDispose(),this._htManager.remove(this._badgeId)}}class Yd extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Oe(i);await e.view.withMode(ye.SELECTION,()=>t.withCursor(Le.Crosshair,async()=>{const r=new T(u.t("jig.measureDistance.firstPoint")),o=await t.getPoint(r);if(o.status!==b.OK)return;const a=o.value,l=new T(u.t("jig.measureDistance.secondPoint"));l.useBasePoint=!0,l.jig=new $d(e.view,i,a,n);const c=await t.getPoint(l);if(c.status!==b.OK)return;const h=c.value;Wd(e.view,i,a,h,ut(i))}))}}function Zd(s,e,t,i,n){Fi.create(t,i,n).commit(s,e)}class Xd extends z{constructor(){super(),this.mode=F.Read}async execute(e){const t=e.view.editor,i=e.doc.database;await e.view.withMode(ye.SELECTION,()=>t.withCursor(Le.Crosshair,async()=>{const n=new T(u.t("jig.measurePoint.point")),r=await t.getPoint(n);if(r.status!==b.OK)return;const o=r.value;Zd(e.view,i,o,ut(i))}))}}function wo(){return new d.AcCmColor(d.AcCmColorMethod.ByACI,1)}const ms=d.AcGiLineWeight.LineWeight070,qd=12;let Jd=wo(),Qd=ms,eu=qd;const vo=new Set;function ko(){for(const s of vo)s()}function ys(s){return vo.add(s),()=>{vo.delete(s)}}function J(){return Jd.clone()}function Ae(){return Qd}function qe(){return eu}function tu(s){Jd=s.clone(),ko()}function iu(s){s>0&&(Qd=s,ko())}function nu(s){!Number.isFinite(s)||s<=0||(eu=s,ko())}function Ne(s){const e=Number(s);return!Number.isFinite(e)||e<=0?2:Math.max(1,e/28)}function Tt(s){return s.cssColor??`rgb(${s.red}, ${s.green}, ${s.blue})`}function xo(s){const e=d.AcCmColor.fromString(s);if(e)return li(e);try{return li(new d.AcCmColor().setRGBFromCss(s))}catch{return wo()}}function gs(){return{color:Tt(J()),lineWeight:Ae(),fontSize:qe()}}function su(s="markup"){return typeof crypto<"u"&&"randomUUID"in crypto?`${s}-${crypto.randomUUID()}`:`${s}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function ru(){return new Date().toISOString()}function ou(s){const e=d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.LOGINNAME,s);return typeof e=="string"?e.trim():""}const au=F.Review;function Re(s){s.mode=au,s.recordsUndoStack=!1}function Ve(s,e,t,i){const n=ru();return{id:su(s),type:s,layoutId:e.activeLayoutBtrId,style:gs(),text:i==null?void 0:i.text,comment:(i==null?void 0:i.comment)??"",status:"open",author:ou(t.doc.database),createdAt:n,updatedAt:n}}async function So(s,e,t=""){const i=new ce(u.t(e));i.allowEmpty=!0,i.allowSpaces=!0,i.defaultValue=t,i.useDefaultValue=!0;const n=await s.view.editor.getString(i);if(n.status===b.OK)return(n.stringResult??t).trim()}async function fs(s,e){return(await fr({el:s.textElement,listenOn:s.element,multiline:(e==null?void 0:e.multiline)??!0,initialText:(e==null?void 0:e.initialText)??""})??"").trim()}async function Je(s,e){await s.view.withMode(ye.SELECTION,()=>s.view.editor.withCursor(Le.Crosshair,e))}let bs;function lu(s){bs=s}function zi(s,e){bs==null||bs(s,e)}function cu(s){const e=s.style.lineWeight!=null&&s.style.lineWeight>0?s.style.lineWeight:ms;return{color:xo(s.style.color),lineWeight:e,canvasLineWidth:Ne(e),layer:ln,layoutId:s.layoutId}}class It extends ho{constructor(e){super(),this.record=e}get id(){return this.record.id}toRecord(){return this.record}get markupRecord(){return this.toRecord()}setRecord(e){this.record=e}style(){return cu(this.record)}hitTest(e,t,i){return Ks(this.record.geometry,e,t,i)}primaryPoint(){const e=on(this.record.geometry);if(e)return{x:e.x,y:e.y,z:0}}subGetGripPoints(){const e=on(this.record.geometry);return e?[new d.AcGePoint3d(e.x,e.y,0)]:[]}subMoveGripPointsAt(e,t){return e.length===0?this:e.includes(0)?(this.record={...this.record,geometry:Gs(this.record.geometry,t.x,t.y)},this):this}emptyResult(e){return{group:e,entityIds:[],dispose:()=>{}}}createGroup(){const{layer:e,layoutId:t}=this.style();return new M.AcTrHtmlGroup({id:this.record.id,layer:e,layoutId:t,selectable:!0})}}const lf=8;function cf(s,e,t){const i=s.worldToScreen(t),n={x:i.x+e,y:i.y},r=s.screenToWorld(n);return Math.abs(r.x-t.x)}function Ni(s,e,t){const i=Math.min(s.x,e.x),n=Math.max(s.x,e.x),r=Math.min(s.y,e.y),o=Math.max(s.y,e.y),a=n-i,l=o-r,c={x:(i+n)/2,y:(r+o)/2},h=cf(t,lf,c),p=Math.max(h,1e-6),m=Math.max(4,Math.ceil(a/p)*2),g=Math.max(4,Math.ceil(l/p)*2),f=[];let w=0;const v=x=>x?.4:-.4;for(let x=0;x<=m;x++){const S=x/m;f.push({x:i+a*S,y:r,bulge:x<m?v(w++%2===0):0})}for(let x=1;x<=g;x++){const S=x/g;f.push({x:n,y:r+l*S,bulge:x<g?v(w++%2===0):0})}for(let x=1;x<=m;x++){const S=1-x/m;f.push({x:i+a*S,y:o,bulge:x<m?v(w++%2===0):0})}for(let x=1;x<g;x++){const S=1-x/g;f.push({x:i,y:r+l*S,bulge:x<g-1?v(w++%2===0):0})}return f}function du(s,e){return[{x:s.x,y:s.y},{x:e.x,y:s.y},{x:e.x,y:e.y},{x:s.x,y:e.y}]}function df(s,e,t,i=6){if(Math.abs(t)<1e-8)return[{x:e.x,y:e.y}];const n=e.x-s.x,r=e.y-s.y;if(Math.hypot(n,r)<1e-12)return[{x:e.x,y:e.y}];const a=(s.x+e.x)/2-r*(1-t*t)/(4*t),l=(s.y+e.y)/2+n*(1-t*t)/(4*t),c=Math.hypot(s.x-a,s.y-l),h=Math.atan2(s.y-l,s.x-a);let m=Math.atan2(e.y-l,e.x-a)-h;t>0?m<=0&&(m+=Math.PI*2):m>=0&&(m-=Math.PI*2);const g=[],f=Math.max(2,i);for(let w=1;w<=f;w++){const v=w/f,x=h+m*v;g.push({x:a+c*Math.cos(x),y:l+c*Math.sin(x)})}return g}function ws(s){if(s.length<2)return s.map(t=>({x:t.x,y:t.y}));const e=[{x:s[0].x,y:s[0].y}];for(let t=0;t<s.length;t++){const i=s[t],n=s[(t+1)%s.length],r=df({x:i.x,y:i.y},{x:n.x,y:n.y},i.bulge);for(const o of r)e.push(o)}return e}function uu(s,e,t,i,n,r,o){const a=(o==null?void 0:o.dx)??0,l=(o==null?void 0:o.dy)??0,c=Ni(t,i,e),h=ws(c).map(m=>({x:m.x+a,y:m.y+l}));if(h.length<2)return;const p=h.map(m=>e.worldToScreen(m));s.strokeStyle=n,s.lineWidth=r,s.beginPath(),s.moveTo(p[0].x,p[0].y);for(let m=1;m<p.length;m++)s.lineTo(p[m].x,p[m].y);s.closePath(),s.stroke()}function uf(s,e,t,i){const n=Ni(e,t,i);s.reset(!1);for(let r=0;r<n.length;r++)s.addVertexAt(r,{x:n[r].x,y:n[r].y},n[r].bulge);s.closed=!0}function hf(s,e,t){const i=du(e,t);s.reset(!1);for(let n=0;n<i.length;n++)s.addVertexAt(n,i[n]);s.closed=!0}let ii=!0;function pf(){return ii}function mf(s){ii=s}async function vs(s,e){for(;;){const t=ii?"jig.markup.shape.calloutOn":"jig.markup.shape.calloutOff",i=new T(`${u.t(e)} ${u.t(t)}`);i.keywords.add(u.t("jig.markup.shape.keywords.callout.display"),u.t("jig.markup.shape.keywords.callout.global"),u.t("jig.markup.shape.keywords.callout.local")),i.keywords.add(u.t("jig.markup.shape.keywords.noCallout.display"),u.t("jig.markup.shape.keywords.noCallout.global"),u.t("jig.markup.shape.keywords.noCallout.local"));const n=await s.view.editor.getPoint(i);if(n.status===b.Keyword){const r=n.stringResult??"";if(r==="Callout"){ii=!0;continue}if(r==="NoCallout"){ii=!1;continue}continue}return n.status!==b.OK?void 0:n.value}}function yf(s){return s.kind==="circle"?{...s.center}:{x:(s.corner1.x+s.corner2.x)/2,y:(s.corner1.y+s.corner2.y)/2}}function ni(s,e){if(s.kind==="circle"){const{center:w,radius:v}=s,x=e.x-w.x,S=e.y-w.y,P=Math.hypot(x,S);if(P<1e-9||v<=0)return{x:w.x+v,y:w.y};const A=v/P;return{x:w.x+x*A,y:w.y+S*A}}const t=Math.min(s.corner1.x,s.corner2.x),i=Math.max(s.corner1.x,s.corner2.x),n=Math.min(s.corner1.y,s.corner2.y),r=Math.max(s.corner1.y,s.corner2.y),o=(t+i)/2,a=(n+r)/2,l=(i-t)/2,c=(r-n)/2,h=e.x-o,p=e.y-a;if(Math.abs(h)<1e-9&&Math.abs(p)<1e-9)return{x:i,y:a};const m=Math.abs(h)>1e-9?l/Math.abs(h):Number.POSITIVE_INFINITY,g=Math.abs(p)>1e-9?c/Math.abs(p):Number.POSITIVE_INFINITY,f=Math.min(m,g);return{x:o+h*f,y:a+p*f}}function gf(s,e,t){return ws(Ni(s,e,t))}class ff extends R{constructor(e,t,i){super(e),this._view=e,this._outline=t,this._color=i,this._ht=this._view.htmlTransientManager;const n=yf(t);this._tip=ni(t,{x:n.x+1,y:n.y}),this._anchor={...this._tip};const r=Date.now();this._tipDotId=`live-shape-callout-tip-${r}`,this._bubbleId=`live-shape-callout-bubble-${r}`;const o=this._view.activeLayoutBtrId;this._tipDot=new M.AcTrHtmlDot({id:this._tipDotId,color:i,worldPosition:this._tip,layer:le,layoutId:o}),this._ht.add(this._tipDot),this._bubble=new M.AcTrHtmlCallout({id:this._bubbleId,color:i,text:"",fontSize:qe(),worldPosition:this._tip,layer:le,layoutId:o}),this._ht.add(this._bubble),this._preview=new we(this._view,`live-shape-callout-stroke-${r}`,le),this._unsubDrawStyle=ys(()=>this.applyCurrentStyle()),this.paintPreview(),this._view.isHtmlDirty=!0}get entity(){return null}update(e){const t={x:e.x,y:e.y};this._tip=ni(this._outline,t),this._anchor=t,this._tipDot.setPosition(this._tip),this._bubble.setPosition(t),this.paintPreview(),this._view.isHtmlDirty=!0}get capsule(){return this._bubble}end(){}disposePreview(){var e;(e=this._unsubDrawStyle)==null||e.call(this),this._unsubDrawStyle=void 0,this._preview.acapDispose(),this._ht.remove(this._tipDotId),this._ht.remove(this._bubbleId),this._view.isHtmlDirty=!0}applyCurrentStyle(){this._color=J(),this._tipDot.setColor(this._color),this._bubble.setColor(this._color),this._bubble.setFontSize(qe()),this.paintPreview(),this._view.isHtmlDirty=!0}paintPreview(){const e=this._outline,t=this._color,i=Ne(Ae()),n=this._tip,r=this._anchor,o=this._view;this._preview.acapSetDraw((a,l)=>{if(e.kind==="circle")mo(a,l,e.center,e.radius,t,i);else if(e.kind==="cloud"){const c=gf(e.corner1,e.corner2,o);ti(a,l,c,t,i,{closed:!0})}else ti(a,l,yo(e.corner1,e.corner2),t,i,{closed:!0});rt(a,l,n,r,t,i)})}}async function ks(s,e){if(!ii)return;const t=J(),i=new ff(s.view,e,t);try{const n=new T(u.t("jig.markup.shape.calloutAnchor"));n.useBasePoint=!1,n.jig=i;const r=await s.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=ni(e,{x:o.x,y:o.y}),l=await fs(i.capsule);return{tip:a,anchor:{x:o.x,y:o.y},text:l||void 0}}finally{i.disposePreview()}}function Ri(s,e){K().setSelectedId(e),s.htmlTransientManager.selectGroup(e)}function hu(s){const{view:e,group:t,record:i,callout:n,style:r,cleanups:o,outline:a}=s,{color:l,layer:c,layoutId:h}=r,p=e.container,m=new M.AcTrHtmlCanvasOverlay({id:`${i.id}-shape-leader`,container:p,layer:c,layoutId:h});t.addCanvas(m);const g={tip:{...n.tip},anchor:{...n.anchor}},f=()=>{const S=Et(m.canvas,p);S&&co(S,e.worldToScreen(g.tip),e.worldToScreen(g.anchor),i.style.color,!1,Ne(i.style.lineWeight!=null&&i.style.lineWeight>0?i.style.lineWeight:ms))};f(),e.events.viewChanged.addEventListener(f),o.push(()=>e.events.viewChanged.removeEventListener(f));const w=new M.AcTrHtmlCallout({id:`${i.id}-shape-bubble`,color:l,text:n.text||i.text||"",fontSize:i.style.fontSize,worldPosition:g.anchor,layer:c,layoutId:h}),v=new M.AcTrHtmlDot({id:`${i.id}-shape-tip`,color:l,worldPosition:g.tip,layer:c,layoutId:h});return t.add(w,v),o.push(En({view:e,el:w.textElement,listenOn:w.element,recordId:i.id,multiline:!0})),{live:g,redraw:f,tipDot:v,bubble:w,bindGrips:()=>{o.push(hs({view:e,tipEl:v,bubbleEl:w,state:g,constrainTip:S=>ni(a,S),onDragStart:()=>Ri(e,i.id),onLiveChange:f,onCommit:S=>{const P=K().get(i.id);if(!P||P.geometry.type!==a.kind)return;const A=P.geometry;A.type!=="cloud"&&A.type!=="rect"&&A.type!=="circle"||ke(e,"Move Callout",()=>{var C;const _=K().updateGeometry(i.id,{...A,callout:{tip:S.tip,anchor:S.anchor,text:((C=A.callout)==null?void 0:C.text)??n.text}});_&&zi(e,_)})}}))}}}function Vi(s){const{view:e,recordId:t,centerEl:i,onLiveOffset:n,attached:r}=s;let o={x:i.object.position.x,y:i.object.position.y},a={...o},l;return Lt({view:e,el:i.element,cursor:"move",onDragStart:()=>{Ri(e,t);const c=K().get(t);o=(c?on(c.geometry):void 0)??{x:i.object.position.x,y:i.object.position.y},a={...o},l=r?{tip:{...r.live.tip},anchor:{...r.live.anchor}}:void 0},onMove:c=>{a=c;const h=c.x-o.x,p=c.y-o.y;n==null||n(h,p),Xe(e,i,c),r&&l&&(r.live.tip=ae(l.tip,h,p),r.live.anchor=ae(l.anchor,h,p),Xe(e,r.tipDot,r.live.tip),Xe(e,r.bubble,r.live.anchor),r.redraw())},onCommit:()=>{const c=a.x-o.x,h=a.y-o.y;if(Math.hypot(c,h)<1e-9){n==null||n(0,0);return}ke(e,"Move Markup",()=>{const p=K().get(t);if(!p)return;const m=K().updateGeometry(t,Gs(p.geometry,c,h));m&&zi(e,m)})}})}class pu extends It{constructor(e){super(e)}primaryPoint(){const e=this.record.geometry;if(e.type==="callout")return{x:e.anchor.x,y:e.anchor.y,z:0}}subGetGripPoints(){const e=this.record.geometry;return e.type!=="callout"?[]:[new d.AcGePoint3d(e.tip.x,e.tip.y,0),new d.AcGePoint3d(e.anchor.x,e.anchor.y,0),new d.AcGePoint3d((e.tip.x+e.anchor.x)/2,(e.tip.y+e.anchor.y)/2,0)]}subMoveGripPointsAt(e,t){const i=this.record.geometry;if(i.type!=="callout")return this;let n={...i.tip},r={...i.anchor};for(const o of e)o===0?n={x:n.x+t.x,y:n.y+t.y}:o===1?r={x:r.x+t.x,y:r.y+t.y}:o===2&&(n={x:n.x+t.x,y:n.y+t.y},r={x:r.x+t.x,y:r.y+t.y});return this.record={...this.record,geometry:{type:"callout",tip:n,anchor:r}},this}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="callout")return this.emptyResult(this.createGroup());const{color:i,canvasLineWidth:n,layer:r,layoutId:o}=this.style(),a=this.createGroup(),l=[],c=[],h=e.container,p=new M.AcTrHtmlCanvasOverlay({id:`${this.record.id}-leader`,container:h,layer:r,layoutId:o});a.addCanvas(p);const m={tip:{...t.tip},anchor:{...t.anchor}},g=()=>{const S=Et(p.canvas,h);S&&co(S,e.worldToScreen(m.tip),e.worldToScreen(m.anchor),this.record.style.color,!0,n)};g(),e.events.viewChanged.addEventListener(g),l.push(()=>e.events.viewChanged.removeEventListener(g));const f=new M.AcTrHtmlCallout({id:`${this.record.id}-bubble`,color:i,text:this.record.text||this.record.comment||"Callout",fontSize:this.record.style.fontSize,worldPosition:m.anchor,layer:r,layoutId:o}),w=new M.AcTrHtmlDot({id:`${this.record.id}-tip`,color:i,worldPosition:m.tip,layer:r,layoutId:o}),v=new M.AcTrHtmlDot({id:`${this.record.id}-center`,color:i,worldPosition:{x:(m.tip.x+m.anchor.x)/2,y:(m.tip.y+m.anchor.y)/2},layer:r,layoutId:o});a.add(f,w,v),l.push(En({view:e,el:f.textElement,listenOn:f.element,recordId:this.record.id,multiline:!0}));const x=()=>{Xe(e,v,{x:(m.tip.x+m.anchor.x)/2,y:(m.tip.y+m.anchor.y)/2})};return c.push(()=>{l.push(hs({view:e,tipEl:w,bubbleEl:f,state:m,onDragStart:()=>Ri(e,this.record.id),onLiveChange:()=>{g(),x()},onCommit:S=>{ke(e,"Move Callout",()=>{const P=K().updateGeometry(this.record.id,{type:"callout",tip:S.tip,anchor:S.anchor});P&&zi(e,P)})}}),Vi({view:e,recordId:this.record.id,centerEl:v,attached:{live:m,redraw:g,tipDot:w,bubble:f}}))}),{group:a,entityIds:[],dispose:()=>{for(const S of l)try{S()}catch{}},bindGrips:()=>{for(const S of c)S()}}}}class mu extends It{constructor(e){super(e)}subGetGripPoints(){return[]}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="highlight")return this.emptyResult(this.createGroup());const{color:i,canvasLineWidth:n,layer:r,layoutId:o}=this.style(),a=this.createGroup(),l=[],c=e.container,h=new M.AcTrHtmlCanvasOverlay({id:`${this.record.id}-hl`,container:c,layer:r,layoutId:o});a.addCanvas(h);const p=()=>{const m=Et(h.canvas,c);m&&uo(m,e.worldToScreen(t.corner1),e.worldToScreen(t.corner2),this.record.style.color,n)};return p(),e.events.viewChanged.addEventListener(p),l.push(()=>e.events.viewChanged.removeEventListener(p)),a.add(new M.AcTrHtmlDot({id:`${this.record.id}-dot`,color:i,worldPosition:{x:(t.corner1.x+t.corner2.x)/2,y:(t.corner1.y+t.corner2.y)/2},layer:r,layoutId:o})),{group:a,entityIds:[],dispose:()=>{for(const m of l)try{m()}catch{}}}}}class yu extends It{constructor(e){super(e)}subGetGripPoints(){const e=this.record.geometry;return e.type!=="line"&&e.type!=="arrow"?[]:[new d.AcGePoint3d(e.start.x,e.start.y,0),new d.AcGePoint3d(e.end.x,e.end.y,0)]}subMoveGripPointsAt(e,t){const i=this.record.geometry;if(i.type!=="line"&&i.type!=="arrow")return this;let n={...i.start},r={...i.end};for(const o of e)o===0?n={x:n.x+t.x,y:n.y+t.y}:o===1&&(r={x:r.x+t.x,y:r.y+t.y});return this.record={...this.record,geometry:i.type==="arrow"?{type:"arrow",start:n,end:r}:{type:"line",start:n,end:r}},this}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="line"&&t.type!=="arrow")return this.emptyResult(this.createGroup());const{color:i,canvasLineWidth:n,layer:r,layoutId:o}=this.style(),a=this.createGroup(),l=[],c=[],h={start:{...t.start},end:{...t.end}},p=new M.AcTrHtmlDot({id:`${this.record.id}-dot1`,color:i,worldPosition:h.start,layer:r,layoutId:o}),m=new M.AcTrHtmlDot({id:`${this.record.id}-dot2`,color:i,worldPosition:h.end,layer:r,layoutId:o});a.add(p,m);const g=e.container,f=new M.AcTrHtmlCanvasOverlay({id:`${this.record.id}-stroke`,container:g,layer:r,layoutId:o});a.addCanvas(f);let w={start:{...h.start},end:{...h.end}};const v=t.type==="arrow",x=()=>{const A=Et(f.canvas,g);if(!A)return;const _=e.worldToScreen(h.start),C=e.worldToScreen(h.end);A.strokeStyle=this.record.style.color,A.lineWidth=n,A.beginPath(),A.moveTo(_.x,_.y),A.lineTo(C.x,C.y),A.stroke(),v&&us(A,_,C,this.record.style.color)};x(),e.events.viewChanged.addEventListener(x),l.push(()=>e.events.viewChanged.removeEventListener(x));const S=()=>{Ri(e,this.record.id),w={start:{...h.start},end:{...h.end}}},P=()=>{const A=Math.hypot(h.start.x-w.start.x,h.start.y-w.start.y),_=Math.hypot(h.end.x-w.end.x,h.end.y-w.end.y);if(A<1e-9&&_<1e-9){x();return}ke(e,v?"Move Arrow":"Move Line",()=>{const C=K().updateGeometry(this.record.id,v?{type:"arrow",start:{...h.start},end:{...h.end}}:{type:"line",start:{...h.start},end:{...h.end}});C&&zi(e,C)})};return c.push(()=>{l.push(Lt({view:e,el:p.element,onDragStart:S,onMove:A=>{h.start=A,Xe(e,p,A),x()},onCommit:P}),Lt({view:e,el:m.element,onDragStart:S,onMove:A=>{h.end=A,Xe(e,m,A),x()},onCommit:P}))}),{group:a,entityIds:[],dispose:()=>{for(const A of l)try{A()}catch{}},bindGrips:()=>{for(const A of c)A()}}}}class gu extends It{constructor(e){super(e)}subGetGripPoints(){return super.subGetGripPoints()}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="cloud"&&t.type!=="rect"&&t.type!=="circle")return this.emptyResult(this.createGroup());const{color:i,canvasLineWidth:n,layer:r,layoutId:o}=this.style(),a=this.createGroup(),l=[],c=[];let h,p,m={dx:0,dy:0};t.type==="cloud"?(h={x:(t.corner1.x+t.corner2.x)/2,y:(t.corner1.y+t.corner2.y)/2},p={kind:"cloud",corner1:t.corner1,corner2:t.corner2}):t.type==="rect"?(h={x:(t.corner1.x+t.corner2.x)/2,y:(t.corner1.y+t.corner2.y)/2},p={kind:"rect",corner1:t.corner1,corner2:t.corner2}):(h={...t.center},p={kind:"circle",center:t.center,radius:t.radius});const g=e.container,f=new M.AcTrHtmlCanvasOverlay({id:`${this.record.id}-shape`,container:g,layer:r,layoutId:o});a.addCanvas(f);const w=()=>{const S=Et(f.canvas,g);if(!S)return;const P=this.record.style.color;if(t.type==="cloud")uu(S,e,t.corner1,t.corner2,P,n,m);else if(t.type==="rect"){const A=yo(t.corner1,t.corner2).map(_=>({x:_.x+m.dx,y:_.y+m.dy}));ti(S,e,A,P,n,{closed:!0})}else mo(S,e,{x:t.center.x+m.dx,y:t.center.y+m.dy},t.radius,P,n)};w(),e.events.viewChanged.addEventListener(w),l.push(()=>e.events.viewChanged.removeEventListener(w));const v=new M.AcTrHtmlDot({id:`${this.record.id}-dot`,color:i,worldPosition:h,layer:r,layoutId:o});a.add(v);const x=t.callout?hu({view:e,group:a,record:this.record,callout:t.callout,style:this.style(),cleanups:l,outline:p}):void 0;return c.push(()=>{var S;(S=x==null?void 0:x.bindGrips)==null||S.call(x),l.push(Vi({view:e,recordId:this.record.id,centerEl:v,attached:x,onLiveOffset:(P,A)=>{m={dx:P,dy:A},w()}}))}),{group:a,entityIds:[],dispose:()=>{for(const S of l)try{S()}catch{}},bindGrips:()=>{for(const S of c)S()}}}}class fu extends It{constructor(e){super(e)}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="stamp"&&t.type!=="symbol")return this.emptyResult(this.createGroup());const{color:i,layer:n,layoutId:r}=this.style(),o=this.createGroup(),a=[],l=[],c=t.type==="stamp"?t.stampId:t.symbolId,h=new M.AcTrHtmlStamp({id:`${this.record.id}-stamp`,color:i,stampId:c,text:this.record.text,imageUrl:t.imageUrl,worldPosition:t.position,layer:n,layoutId:r});return o.add(h),l.push(()=>{a.push(Vi({view:e,recordId:this.record.id,centerEl:h}))}),{group:o,entityIds:[],dispose:()=>{for(const p of a)try{p()}catch{}},bindGrips:()=>{for(const p of l)p()}}}}class bu extends It{constructor(e){super(e)}subWorldDraw(e){const t=this.record.geometry;if(t.type!=="text")return this.emptyResult(this.createGroup());const{color:i,layer:n,layoutId:r}=this.style(),o=this.createGroup(),a=[],l=[],c=new M.AcTrHtmlBadge({id:`${this.record.id}-badge`,color:i,text:this.record.text||"Note",fontSize:this.record.style.fontSize,worldPosition:t.position,layer:n,layoutId:r});return o.add(c),a.push(En({view:e,el:c.element,recordId:this.record.id})),l.push(()=>{a.push(Vi({view:e,recordId:this.record.id,centerEl:c}))}),{group:o,entityIds:[],dispose:()=>{for(const h of a)try{h()}catch{}},bindGrips:()=>{for(const h of l)h()}}}}function xs(s){switch(s.geometry.type){case"text":return new bu(s);case"line":case"arrow":return new yu(s);case"cloud":case"rect":case"circle":return new gu(s);case"highlight":return new mu(s);case"callout":return new pu(s);case"stamp":case"symbol":return new fu(s)}}const bf=xs;function Xb(s){return s}class wu{constructor(){this.published=new Set,this.suppressingStoreRemove=!1}republishAll(e){this.clearVisuals(e,{clearStore:!1});for(const t of K().list())this.publish(e,t)}publish(e,t){var f;const i=e,n=K().selectedId===t.id;this.published.has(t.id)&&this.unpublish(e,t.id,{keepInStore:!0});const o=xs(t).worldDraw(i),{group:a,entityIds:l}=o,c={entityIds:l,dispose:o.dispose},h=K(),p=a.onSelectedChanged;a.onSelectedChanged=(w,v)=>{p==null||p(w,v),w?(h.setSelectedId(v.id),c.entityIds.length>0&&i.highlight(c.entityIds)):(h.selectedId===v.id&&h.setSelectedId(void 0),c.entityIds.length>0&&i.unhighlight(c.entityIds))};const m=a.onVisibleChanged;a.onVisibleChanged=(w,v)=>{m==null||m(w,v);for(const x of c.entityIds)i.setTransientEntityVisible(x,w)};const g=a.onDispose;a.onDispose=()=>{g==null||g(),c.entityIds.length>0&&i.unhighlight(c.entityIds),c.dispose(),this.published.delete(t.id),this.suppressingStoreRemove||h.removeRecord(t.id)},i.htmlTransientManager.add(a),(f=o.bindGrips)==null||f.call(o),i.isHtmlDirty=!0,this.published.add(t.id),n&&(K().setSelectedId(t.id),i.htmlTransientManager.selectGroup(t.id))}unpublish(e,t,i){const n=(i==null?void 0:i.keepInStore)===!0,r=()=>this.unpublishInternal(e,t,n);if(!n&&!fe().isBusy){ke(e,"Delete Markup",r);return}r()}unpublishInternal(e,t,i){const n=e;this.suppressingStoreRemove=i;try{n.htmlTransientManager.has(t)?n.htmlTransientManager.remove(t):(this.published.delete(t),i||K().removeRecord(t))}finally{this.suppressingStoreRemove=!1}n.isHtmlDirty=!0}clearVisuals(e,t){const i=(t==null?void 0:t.clearStore)!==!1,n=()=>this.clearVisualsInternal(e,i);if(i&&!fe().isBusy){ke(e,"Clear Markups",n);return}n()}clearLayout(e,t,i){const n=(i==null?void 0:i.clearStore)!==!1,r=()=>{const o=K().list().filter(a=>a.layoutId===t).map(a=>a.id);for(const a of o)this.unpublish(e,a,{keepInStore:!n});e.isHtmlDirty=!0};if(n&&!fe().isBusy){ke(e,"Clear Markups",r);return}r()}clearVisualsInternal(e,t){const i=e;this.suppressingStoreRemove=!0;try{i.htmlTransientManager.deselectAll(),i.htmlTransientManager.clear(ln),i.htmlTransientManager.clear(le),this.published.clear()}finally{this.suppressingStoreRemove=!1}t&&K().clear({markDirty:!0}),i.isHtmlDirty=!0}forgetPublished(){this.published.clear()}select(e,t){e.htmlTransientManager.selectGroup(t),K().setSelectedId(t)}focus(e,t){const i=xs(t).primaryPoint();if(!i)return;const n=e,r=50,o=new d.AcGeBox2d().expandByPoint({x:i.x-r,y:i.y-r}).expandByPoint({x:i.x+r,y:i.y+r});n.zoomTo(o,1.5),this.select(e,t.id)}}let Po;function ot(){return Po||(Po=new wu),Po}lu((s,e)=>{ot().publish(s,e)});function vu(){fe().clear(),xt().clear(),K().reset(),ot().forgetPublished(),ht()}function Ge(s,e){ke(s,"Create Markup",()=>{K().upsert(e),ot().publish(s,e)})}function Ss(s,e){const t=K(),i=t.selectedId;i&&ke(s,"Markup Style",()=>{const n=t.updateStyle(i,e);n&&ot().publish(s,n)})}class ku extends z{constructor(){super(),Re(this)}async execute(e){const t=e.view;ot().clearLayout(t,t.activeLayoutBtrId,{clearStore:!0})}}class wf extends R{constructor(e,t,i){super(e),this._view=e,this._p1=t,this._p2=t,this._color=i,this._preview=new we(this._view,`live-markup-arrow-${Date.now()}`,le)}get entity(){return null}update(e){this._p2=e,this._color=J();const t=Ne(Ae());this._preview.acapSetDraw((i,n)=>{rt(i,n,this._p1,this._p2,this._color,t,{arrow:!0})})}end(){super.end(),this._preview.acapDispose()}}class xu extends z{constructor(){super(),Re(this)}async execute(e){await Je(e,async()=>{const t=J(),i=new T(u.t("jig.markup.arrow.firstPoint")),n=await e.view.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new T(u.t("jig.markup.arrow.secondPoint"));o.useBasePoint=!0,o.jig=new wf(e.view,r,t);const a=await e.view.editor.getPoint(o);if(a.status!==b.OK)return;const l=a.value,h={...Ve("arrow",e.view,e),type:"arrow",geometry:{type:"arrow",start:{x:r.x,y:r.y},end:{x:l.x,y:l.y}}};Ge(e.view,h)})}}class vf extends R{constructor(e,t,i,n){super(e),this._view=e,this._tip={x:t.x,y:t.y,z:t.z??0},this._anchor={...this._tip},this._color=n,this._ht=this._view.htmlTransientManager;const r=this._view.activeLayoutBtrId,o=Date.now();this._tipDotId=`live-markup-callout-tip-${o}`,this._bubbleId=`live-markup-callout-bubble-${o}`,this._tipDot=new M.AcTrHtmlDot({id:this._tipDotId,color:n,worldPosition:this._tip,layer:le,layoutId:r}),this._ht.add(this._tipDot),this._bubble=new M.AcTrHtmlCallout({id:this._bubbleId,color:n,text:i,fontSize:qe(),worldPosition:this._tip,layer:le,layoutId:r}),this._ht.add(this._bubble),this._preview=new we(this._view,`live-markup-callout-leader-${o}`,le),this._unsubDrawStyle=ys(()=>this.applyCurrentStyle()),this._view.isHtmlDirty=!0}get entity(){return null}update(e){this._anchor={x:e.x,y:e.y,z:e.z??0},this._color=J(),this._bubble.setPosition(this._anchor),this._bubble.setFontSize(qe()),this.paintLeader(),this._view.isHtmlDirty=!0}get capsule(){return this._bubble}end(){}disposePreview(){var e;(e=this._unsubDrawStyle)==null||e.call(this),this._unsubDrawStyle=void 0,this._preview.acapDispose(),this._ht.remove(this._tipDotId),this._ht.remove(this._bubbleId),this._view.isHtmlDirty=!0}applyCurrentStyle(){this._color=J(),this._tipDot.setColor(this._color),this._bubble.setColor(this._color),this._bubble.setFontSize(qe()),this.paintLeader(),this._view.isHtmlDirty=!0}paintLeader(){const e=Ne(Ae()),t=this._color,i=this._tip,n=this._anchor;this._preview.acapSetDraw((r,o)=>{rt(r,o,n,i,t,e,{arrow:!0})})}}class Su extends z{constructor(){super(),Re(this)}async execute(e){await Je(e,async()=>{const t=J(),i=new T(u.t("jig.markup.callout.tip")),n=await e.view.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new vf(e.view,r,"",t);try{const a=new T(u.t("jig.markup.callout.anchor"));a.basePoint=new d.AcGePoint3d(r.x,r.y,r.z??0),a.useBasePoint=!0,a.useDashedLine=!1,a.jig=o;const l=await e.view.editor.getPoint(a);if(l.status!==b.OK)return;const c=l.value,h=await fs(o.capsule),m={...Ve("callout",e.view,e,{text:h||void 0}),type:"callout",geometry:{type:"callout",tip:{x:r.x,y:r.y},anchor:{x:c.x,y:c.y}}};Ge(e.view,m)}finally{o.disposePreview()}})}}function kf(s,e){return po(s,e)}function xf(s,e,t){Xe(s,e,t)}function Sf(s){return Lt(s)}function Pf(s){const{outline:e,...t}=s;return hs({...t,constrainTip:e?i=>ni(e,i):void 0})}class Af extends R{constructor(e,t,i){super(e),this._radius=0,this._view=e,this._center=t,this._color=i,this._preview=new we(this._view,`live-markup-circle-${Date.now()}`,le)}get entity(){return null}update(e){this._radius=Math.max(e,0),this._color=J();const t=Ne(Ae());this._preview.acapSetDraw((i,n)=>{mo(i,n,this._center,this._radius,this._color,t)})}end(){super.end(),this._preview.acapDispose()}}class Pu extends z{constructor(){super(),Re(this)}async execute(e){await Je(e,async()=>{const t=J(),i=await vs(e,"jig.markup.circle.center");if(!i)return;const n=new be(u.t("jig.markup.circle.radius"));n.allowZero=!1,n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new d.AcGePoint3d(i.x,i.y,i.z??0),n.jig=new Af(e.view,i,t);const r=await e.view.editor.getDistance(n);if(r.status!==b.OK)return;const o=r.value,a=await ks(e,{kind:"circle",center:{x:i.x,y:i.y},radius:o}),c={...Ve("circle",e.view,e,{text:a==null?void 0:a.text}),type:"circle",geometry:{type:"circle",center:{x:i.x,y:i.y},radius:o,callout:a}};Ge(e.view,c)})}}function Cf(s,e,t){return ws(Ni(s,e,t))}class _f extends R{constructor(e,t,i){super(e),this._view=e,this._first=t,this._second=t,this._color=i,this._preview=new we(this._view,`live-markup-cloud-${Date.now()}`,le)}get entity(){return null}update(e){this._second=e,this._color=J();const t=Ne(Ae()),i=Cf(this._first,this._second,this._view);this._preview.acapSetDraw((n,r)=>{ti(n,r,i,this._color,t,{closed:!0})})}end(){super.end(),this._preview.acapDispose()}}class Au extends z{constructor(){super(),Re(this)}async execute(e){await Je(e,async()=>{const t=J(),i=await vs(e,"jig.markup.cloud.firstCorner");if(!i)return;const n=new T(u.t("jig.markup.cloud.secondCorner"));n.useBasePoint=!0,n.jig=new _f(e.view,i,t);const r=await e.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=await ks(e,{kind:"cloud",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y}}),c={...Ve("cloud",e.view,e,{text:a==null?void 0:a.text}),type:"cloud",geometry:{type:"cloud",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y},callout:a}};Ge(e.view,c)})}}class Ef extends R{constructor(e,t,i){super(e),this._view=e,this._first=t,this._second=t,this._colorCss=Tt(i),this._preview=new we(this._view,`live-markup-highlight-${Date.now()}`,le)}get entity(){return null}update(e){this._second=e,this._colorCss=Tt(J());const t=Ne(Ae());this._preview.acapSetDraw((i,n)=>{zg(i,n,this._first,this._second,this._colorCss,t)})}end(){super.end(),this._preview.acapDispose()}}class Cu extends z{constructor(){super(),Re(this)}async execute(e){await Je(e,async()=>{const t=J(),i=Tt(t),n=new T(u.t("jig.markup.highlight.firstCorner")),r=await e.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=new T(u.t("jig.markup.highlight.secondCorner"));a.useBasePoint=!0,a.jig=new Ef(e.view,o,t);const l=await e.view.editor.getPoint(a);if(l.status!==b.OK)return;const c=l.value,p={...Ve("highlight",e.view,e),type:"highlight",style:{color:i,lineWeight:Ae()},geometry:{type:"highlight",corner1:{x:o.x,y:o.y},corner2:{x:c.x,y:c.y}}};Ge(e.view,p)})}}const Lf=["text","line","arrow","cloud","rect","circle","highlight","callout","stamp","symbol"];function si(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function Me(s){return si(s)&&typeof s.x=="number"&&typeof s.y=="number"}function _u(s){return!(!si(s)||!Me(s.tip)||!Me(s.anchor)||s.text!==void 0&&typeof s.text!="string")}function Tf(s){return typeof s=="string"&&ea.includes(s)}function If(s){return typeof s=="string"&&Lf.includes(s)}function Mf(s){if(!si(s)||typeof s.id!="string"||!If(s.type)||!si(s.style)||typeof s.style.color!="string"||!si(s.geometry)||s.geometry.type!==s.type||!Tf(s.status))return;const e=s.geometry;switch(s.type){case"text":if(!Me(e.position))return;break;case"line":case"arrow":if(!Me(e.start)||!Me(e.end))return;break;case"cloud":case"rect":case"highlight":if(!Me(e.corner1)||!Me(e.corner2)||(s.type==="cloud"||s.type==="rect")&&e.callout!==void 0&&!_u(e.callout))return;break;case"circle":if(!Me(e.center)||typeof e.radius!="number"||!(e.radius>0)||e.callout!==void 0&&!_u(e.callout))return;break;case"callout":if(!Me(e.tip)||!Me(e.anchor))return;break;case"stamp":if(!Me(e.position)||typeof e.stampId!="string")return;break;case"symbol":if(!Me(e.position)||typeof e.symbolId!="string")return;break;default:return}return{id:s.id,type:s.type,layoutId:typeof s.layoutId=="string"?s.layoutId:void 0,style:{color:s.style.color,lineWeight:typeof s.style.lineWeight=="number"?s.style.lineWeight:void 0,fontSize:typeof s.style.fontSize=="number"&&s.style.fontSize>0?s.style.fontSize:void 0},text:typeof s.text=="string"?s.text:void 0,comment:typeof s.comment=="string"?s.comment:"",status:s.status,author:typeof s.author=="string"?s.author:"",createdAt:typeof s.createdAt=="string"?s.createdAt:new Date().toISOString(),updatedAt:typeof s.updatedAt=="string"?s.updatedAt:new Date().toISOString(),geometry:s.geometry}}function Eu(s){let e;try{e=JSON.parse(s)}catch{throw new Error("Invalid markup sidecar: not JSON")}if(!si(e)||e.version!==1)throw new Error("Invalid markup sidecar: expected version 1");if(!Array.isArray(e.markups))throw new Error("Invalid markup sidecar: markups must be an array");const t=[];for(const i of e.markups){const n=Mf(i);n&&t.push(n)}return{version:1,drawingName:typeof e.drawingName=="string"?e.drawingName:void 0,markups:t}}function Lu(s){return`${JSON.stringify(s,null,2)}
575
+ `}function Tu(s){return s?`${s.replace(/\.(dwg|dxf)$/i,"")}.markup.json`:"drawing.markup.json"}function Df(s,e){if(typeof document>"u")return;const t=new Blob([e],{type:"application/json;charset=utf-8"}),i=URL.createObjectURL(t),n=document.createElement("a");n.href=i,n.download=s,n.click(),URL.revokeObjectURL(i)}function Of(){return new Promise(s=>{if(typeof document>"u"){s(void 0);return}const e=document.createElement("input");e.type="file",e.accept=".json,application/json";let t=!1;const i=n=>{t||(t=!0,s(n))};e.addEventListener("cancel",()=>i()),e.onchange=async()=>{var r;const n=(r=e.files)==null?void 0:r[0];if(!n){i();return}i(await n.text())},e.click()})}class Iu extends z{constructor(){super(),this.mode=F.Read,this.recordsUndoStack=!1}async execute(e){const t=K();t.drawingName||(t.drawingName=e.doc.fileName||e.doc.docTitle);const i=Lu(t.toSidecar());Df(Tu(t.drawingName),i),t.markClean()}}class Mu extends z{constructor(){super(),this.mode=F.Review,this.recordsUndoStack=!1}async execute(e){new ce(u.t("jig.markup.import.chooseFile"));const t=await Of();if(t==null)return;let i;try{i=Eu(t)}catch(r){console.error(r);return}const n=K();ke(e.view,"Import Markups",()=>{n.replaceAll(i.markups,i.drawingName),ot().republishAll(e.view)})}}class Bf extends R{constructor(e,t,i,n){super(e),this._view=e,this._p1=t,this._p2=t,this._color=i,this._ht=this._view.htmlTransientManager,this._badgeId=`live-markup-line-${Date.now()}`,this._badge=new M.AcTrHtmlBadge({id:this._badgeId,color:i,text:n,worldPosition:t,layer:le,layoutId:this._view.activeLayoutBtrId}),this._badge.object.visible=!1,this._ht.add(this._badge),this._preview=new we(this._view,`live-markup-line-stroke-${Date.now()}`,le)}get entity(){return null}update(e){this._p2=e,this._color=J(),this._badge.setColor(this._color);const t=Ne(Ae());this._preview.acapSetDraw((i,n)=>{rt(i,n,this._p1,this._p2,this._color,t)}),this._badge.setPosition({x:(this._p1.x+e.x)/2,y:(this._p1.y+e.y)/2}),this._badge.object.visible=!0}end(){super.end(),this._preview.acapDispose(),this._ht.remove(this._badgeId)}}class Du extends z{constructor(){super(),Re(this)}async execute(e){await Je(e,async()=>{const t=J(),i=new T(u.t("jig.markup.line.firstPoint")),n=await e.view.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new T(u.t("jig.markup.line.secondPoint"));o.useBasePoint=!0,o.jig=new Bf(e.view,r,t,"Line");const a=await e.view.editor.getPoint(o);if(a.status!==b.OK)return;const l=a.value,h={...Ve("line",e.view,e),type:"line",style:{color:Tt(t),lineWeight:Ae()},geometry:{type:"line",start:{x:r.x,y:r.y},end:{x:l.x,y:l.y}}};Ge(e.view,h)})}}class jf extends R{constructor(e,t,i){super(e),this._view=e,this._first=t,this._second=t,this._color=i,this._preview=new we(this._view,`live-markup-rect-${Date.now()}`,le)}get entity(){return null}update(e){this._second=e,this._color=J();const t=Ne(Ae()),i=yo(this._first,this._second);this._preview.acapSetDraw((n,r)=>{ti(n,r,i,this._color,t,{closed:!0})})}end(){super.end(),this._preview.acapDispose()}}class Ou extends z{constructor(){super(),Re(this)}async execute(e){await Je(e,async()=>{const t=J(),i=await vs(e,"jig.markup.rect.firstCorner");if(!i)return;const n=new T(u.t("jig.markup.rect.secondCorner"));n.useBasePoint=!0,n.jig=new jf(e.view,i,t);const r=await e.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=await ks(e,{kind:"rect",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y}}),c={...Ve("rect",e.view,e,{text:a==null?void 0:a.text}),type:"rect",geometry:{type:"rect",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y},callout:a}};Ge(e.view,c)})}}const Bu=new Set(["approved","rejected","revised","for-review","custom"]);class ju extends z{constructor(){super(),Re(this)}async execute(e){await Je(e,async()=>{const t=new ce(u.t("jig.markup.stamp.kind"));t.allowEmpty=!1,t.allowSpaces=!1,t.defaultValue="approved",t.useDefaultValue=!0;const i=await e.view.editor.getString(t);if(i.status!==b.OK)return;const n=(i.stringResult??"approved").trim().toLowerCase();let r;(n==="custom"||!Bu.has(n))&&(r=await So(e,"jig.markup.stamp.imageUrl",""));const o=await So(e,"jig.markup.stamp.caption",""),a=new T(u.t("jig.markup.stamp.point")),l=await e.view.editor.getPoint(a);if(l.status!==b.OK)return;const c=l.value;if(n!=="custom"&&!Bu.has(n)){const f={...Ve("symbol",e.view,e,{text:o||void 0}),type:"symbol",style:gs(),geometry:{type:"symbol",position:{x:c.x,y:c.y},symbolId:n,imageUrl:r||void 0}};Ge(e.view,f);return}const m={...Ve("stamp",e.view,e,{text:o||void 0}),type:"stamp",style:gs(),geometry:{type:"stamp",position:{x:c.x,y:c.y},stampId:n,imageUrl:r||void 0}};Ge(e.view,m)})}}class Fu extends z{constructor(){super(),Re(this)}async execute(e){await Je(e,async()=>{const t=new T(u.t("jig.markup.text.point")),i=await e.view.editor.getPoint(t);if(i.status!==b.OK)return;const n=i.value,r=e.view,o=`live-markup-text-${Date.now()}`,a=new M.AcTrHtmlBadge({id:o,color:J(),text:"",fontSize:qe(),worldPosition:n,layer:le,layoutId:r.activeLayoutBtrId});r.htmlTransientManager.add(a),r.isHtmlDirty=!0;const l=ys(()=>{a.setColor(J()),a.setFontSize(qe()),r.isHtmlDirty=!0});let c="Note";try{c=await fs({textElement:a.element,element:a.element},{multiline:!1})||"Note"}finally{l(),r.htmlTransientManager.remove(o),r.isHtmlDirty=!0}const p={...Ve("text",r,e,{text:c}),type:"text",geometry:{type:"text",position:{x:n.x,y:n.y}}};Ge(e.view,p)})}}let Ao=!0;function Ff(){return Ao}function zu(s,e){Ao=e,s.htmlTransientManager.setVisible(e,ln),s.htmlTransientManager.setVisible(e,le),s.isHtmlDirty=!0}class Nu extends z{constructor(){super(),this.mode=F.Review,this.recordsUndoStack=!1}async execute(e){const t=e.view;zu(t,!Ao)}}class Co extends $t{constructor(e,t,i,n=1,r=!1){super(e,t,Math.max(0,n)),this._basePoint=new d.AcGePoint3d(i),this._fitMode=r}update(e){const t=new d.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z);if(this.batchPreview.useBatchPreview&&this.copyCount>1){this.batchPreview.updatePlacements(this._view,t,this._fitMode);return}super.update(e)}buildTransforms(e){const t=new d.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z);return(this.previewEntries.length>0?this.previewEntries:[{entity:{objectId:""},copyFactor:1}]).map(n=>{const r=Kn(t,n.copyFactor,this.copyCount,this._fitMode);return{objectId:n.entity.objectId,matrix:new d.AcGeMatrix3d().makeTranslation(r.x,r.y,r.z)}})}}const tn=class tn extends z{constructor(){super(),this.mode=F.Write}addKeyword(e,t){e.keywords.add(u.t(`jig.copy.keywords.${t}.display`),u.t(`jig.copy.keywords.${t}.global`),u.t(`jig.copy.keywords.${t}.local`))}computeDisplacement(e,t){return new d.AcGePoint3d(t).sub(e)}scaleDisplacement(e,t,i,n){return Kn(e,t,i,n)}appendCopies(e,t){t.length!==0&&(e.doc.database.tables.blockTable.modelSpace.appendEntity(t),e.view.addEntity(t))}buildCopies(e,t,i=1,n=!1){const r=[];for(let o=1;o<=i;o++){const a=e.map(h=>h.clone()).filter(h=>!!h),l=this.scaleDisplacement(t,o,i,n),c=new d.AcGeMatrix3d().makeTranslation(l.x,l.y,l.z);a.forEach(h=>h.transformBy(c)),r.push(...a)}return r}async promptCopyMode(e){const t=new ne(u.t("jig.copy.modePrompt"));t.allowNone=!0,this.addKeyword(t,"single"),this.addKeyword(t,"multiple");const i=t.keywords.findByGlobalName(e);i&&(t.keywords.default=i);const n=await k.instance.editor.getKeywords(t);if(n.status===b.None)return e;if(n.status!==b.OK)return;const r=n.stringResult??"";return r==="Single"||r==="Multiple"?r:e}async promptArrayPlacement(e,t,i){const n=new Er(u.t("jig.copy.arrayItemCount"),2);n.lowerLimit=2,n.allowNegative=!1,n.allowZero=!1;const r=await k.instance.editor.getInteger(n);if(r.status!==b.OK)return;const o=r.value??2,a=Math.max(1,o-1);for(;;){const l=new T(u.t("jig.copy.arraySecondPointOrFit"));this.addKeyword(l,"fit"),l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=i,l.jig=new Co(e.view,t,i,a);const c=await k.instance.editor.getPoint(l);if(c.status===b.OK)return{copyCount:a,endPoint:new d.AcGePoint3d(c.value),fitMode:!1};if(c.status===b.Keyword&&c.stringResult==="Fit"){const h=new T(u.t("jig.copy.arrayFitSecondPoint"));h.useBasePoint=!0,h.useDashedLine=!0,h.basePoint=i,h.jig=new Co(e.view,t,i,a,!0);const p=await k.instance.editor.getPoint(h);if(p.status===b.OK)return{copyCount:a,endPoint:new d.AcGePoint3d(p.value),fitMode:!0}}return}}async executeCopyLoop(e,t,i,n,r=!1){for(;;){const o=new T(u.t(r?"jig.copy.displacementOrArray":"jig.copy.secondPointOrArray"));this.addKeyword(o,"array"),o.useBasePoint=!0,o.useDashedLine=!0,o.basePoint=i,o.allowNone=!0,o.jig=new Co(e.view,t,i);const a=await k.instance.editor.getPoint(o);if(a.status===b.OK){const l=this.buildCopies(t,this.computeDisplacement(i,a.value));if(this.appendCopies(e,l),n==="Single")return;continue}if(a.status===b.Keyword&&a.stringResult==="Array"){const l=await this.promptArrayPlacement(e,t,i);if(!l)continue;const c=this.buildCopies(t,this.computeDisplacement(i,l.endPoint),l.copyCount,l.fitMode);if(this.appendCopies(e,c),n==="Single")return;continue}return}}async execute(e){const t=e.view.selectionSet,i=await Un(e,{promptKey:"copy"});if(!i)return;const n=i.entities.map(l=>e.doc.database.openEntityForRead(l.objectId)).filter(l=>!!l);if(n.length===0){t.clear();return}let r=tn._defaultMode,o,a=!1;for(;!o;){const l=new T(u.t("jig.copy.basePointOrOptions"));l.allowNone=!0,this.addKeyword(l,"displacement"),this.addKeyword(l,"mode"),r!=="Multiple"&&this.addKeyword(l,"multiple");const c=await k.instance.editor.getPoint(l);if(c.status===b.OK){o=new d.AcGePoint3d(c.value);break}if(c.status===b.None){o=new d.AcGePoint3d(0,0,0),a=!0;break}if(c.status!==b.Keyword){t.clear();return}const h=c.stringResult??"";if(h==="Displacement"){o=new d.AcGePoint3d(0,0,0),a=!0;break}if(h==="Multiple"){r="Multiple";continue}if(h!=="Mode"){t.clear();return}const p=await this.promptCopyMode(r);if(!p){t.clear();return}r=p,tn._defaultMode=p}await this.executeCopyLoop(e,n,o,r,a),t.clear()}};tn._defaultMode="Multiple";let Ps=tn;class Ru extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.view.selectionSet,i=await hc(e,"erase");i&&(e.doc.entityService.eraseEntities(i),t.clear())}}class Vu extends z{async execute(e){const t=e.view.selectionSet;let i=t.count>0?t.ids:[];if(i.length===0){const r=new Pt(u.sysCmdPrompt("hideobjects")),o=await k.instance.editor.getSelection(r);if(o.status!==b.OK||!o.value||o.value.count===0)return;i=o.value.ids}const n=$h(e,i);n>0&&this.showMessage(`${n} ${u.t("jig.hideobjects.hidden")}`,"success")}}class Gu extends $t{constructor(e,t,i){super(e,t),this._basePoint=new d.AcGePoint3d(i)}buildTransforms(e){const t=new d.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z),i=new d.AcGeMatrix3d().makeTranslation(t.x,t.y,t.z);return(this.previewEntries.length>0?this.previewEntries:[{entity:{objectId:""},copyFactor:1}]).map(r=>({objectId:r.entity.objectId,matrix:i}))}}class Ku extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=e.view.selectionSet,i=await Un(e,{promptKey:"move"});if(!i)return;const{entities:n}=i;let r,o;const a=m=>{m.keywords.add(u.t("jig.move.keywords.displacement.display"),u.t("jig.move.keywords.displacement.global"),u.t("jig.move.keywords.displacement.local"))};class l{constructor(g){this.machine=g}buildPrompt(){const g=new T(u.t("jig.move.basePointOrDisplacement"));return a(g),g.allowNone=!0,g}async handleResult(g){return g.status===b.OK?(r=new d.AcGePoint3d(g.value),this.machine.setState(new c(this.machine)),"continue"):g.status===b.None?(this.machine.setState(new h),"continue"):g.status===b.Keyword&&g.stringResult==="Displacement"?(this.machine.setState(new h),"continue"):"finish"}}class c{constructor(g){this.machine=g}buildPrompt(){const g=new T(u.t("jig.move.secondPointOrDisplacement"));return a(g),r&&(g.useBasePoint=!0,g.useDashedLine=!0,g.basePoint=r,g.jig=new Gu(e.view,n,r)),g.allowNone=!0,g}async handleResult(g){if(g.status===b.OK&&r){const f=new d.AcGePoint3d(g.value);return o=new d.AcGePoint3d(f).sub(r),"finish"}return g.status===b.Keyword&&g.stringResult==="Displacement"?(this.machine.setState(new h),"continue"):"finish"}}class h{buildPrompt(){const g=new T(u.t("jig.move.displacement"));return g.useBasePoint=!0,g.useDashedLine=!0,g.basePoint=new d.AcGePoint3d(0,0,0),g.jig=new Gu(e.view,n,g.basePoint),g.allowNone=!0,g}async handleResult(g){return g.status===b.OK&&(o=new d.AcGePoint3d(g.value)),"finish"}}const p=new Ye;if(p.setState(new l(p)),await p.run(m=>k.instance.editor.getPoint(m)),!o){t.clear();return}e.doc.entityService.translateEntities(n,o),t.clear()}}function zf(s){return s instanceof d.AcDbCurve}function Uu(s,e,t){try{const i=s.getOffsetSideAtPoint(t),n=s.getOffsetCurves(e*i);return n.forEach(r=>zr.copyDisplayTraits(s,r)),n}catch{return[]}}class Nf extends R{constructor(e,t,i){super(e),this._previewCurves=[],this._renderedIds=[],this._view=e,this._curve=t,this._distance=i}update(e){this.clearRendered(),this._previewCurves=Uu(this._curve,this._distance,e)}render(){this._previewCurves.length!==0&&(this._view.addTransientEntity(this._previewCurves),this._renderedIds=this._previewCurves.map(e=>e.objectId))}end(){this.clearRendered()}clearRendered(){this._renderedIds.forEach(e=>this._view.removeTransientEntity(e)),this._renderedIds=[]}}class Gi extends z{constructor(){super(),this.mode=F.Write}async execute(e){const t=(h,p="info")=>{this.showMessage(h,p)},i=e.doc.database.tables.blockTable;let n,r;class o{constructor(p){this.machine=p}buildPrompt(){const p=Gi._lastDistance,m=new be(u.t("jig.offset.distance"));return m.useBasePoint=!1,m.useDashedLine=!0,m.allowZero=!1,m.allowNegative=!1,p!=null&&(m.defaultValue=p,m.useDefaultValue=!0,m.allowNone=!0),m}handleResult(p){return!(p instanceof Pe)||p.status!==b.OK||p.value==null?"finish":!Number.isFinite(p.value)||d.AcGeTol.isNonPositive(p.value)?(t(u.t("jig.offset.invalidDistance"),"warning"),"finish"):(n=p.value,Gi._lastDistance=p.value,this.machine.setState(new a(this.machine)),"continue")}}class a{constructor(p){this.machine=p}buildPrompt(){const p=new $e(u.t("jig.offset.selectObject"));return p.allowNone=!0,p.allowObjectOnLockedLayer=!0,p.setRejectMessage(u.t("jig.offset.invalidSelection")),p}handleResult(p){if(!(p instanceof zn)||p.status===b.None||p.status!==b.OK||!p.objectId)return"finish";const m=e.doc.database.openEntityForRead(p.objectId);return zf(m)?(r=m,this.machine.setState(new l(this.machine)),"continue"):(t(u.t("jig.offset.invalidSelection"),"warning"),"continue")}}class l{constructor(p){this.machine=p}buildPrompt(){const p=new T(u.t("jig.offset.sidePoint"));if(p.allowNone=!0,p.disableOSnap=!0,r&&n!=null){const m=new Nf(e.view,r,n);m.update({...e.view.curPos,z:0}),m.render(),p.jig=m}return p}handleResult(p){if(!(p instanceof Rn)||p.status!==b.OK||!p.value||!r||n==null)return"finish";const m=Uu(r,n,new d.AcGePoint3d(p.value));return m.length===0?t(u.t("jig.offset.offsetFailed"),"warning"):i.modelSpace.appendEntity(m),r=void 0,this.machine.setState(new a(this.machine)),"continue"}}const c=new Ye;c.setState(new o(c)),await c.run(h=>h instanceof be?k.instance.editor.getDistance(h):h instanceof $e?k.instance.editor.getEntity(h):k.instance.editor.getPoint(h))}}class As extends ql{}class Hu extends $t{constructor(e,t,i,n=0){super(e,t),this._lastAngleRad=0,this._basePoint=new d.AcGePoint3d(i),this._referenceAngleDeg=n}get entity(){return this.previewEntities[0]??null}update(e){const t=(e-this._referenceAngleDeg)*Math.PI/180;if(this.batchPreview.useBatchPreview){if(d.AcGeTol.equalToZero(t-this._lastAngleRad))return;this.batchPreview.updateMatrix(this._view,Yt(this._basePoint,t)),this._lastAngleRad=t;return}this._lastAngleRad=t,super.update(e)}buildTransforms(e){const t=(e-this._referenceAngleDeg)*Math.PI/180,i=Yt(this._basePoint,t);return this.previewEntries.map(n=>({objectId:n.entity.objectId,matrix:i}))}}const Vo=class Vo extends z{constructor(){super(),this.mode=F.Write}addKeyword(e,t){e.keywords.add(u.t(`jig.rotate.keywords.${t}.display`),u.t(`jig.rotate.keywords.${t}.global`),u.t(`jig.rotate.keywords.${t}.local`))}warnInvalidInput(e){this.notify(u.t(`jig.rotate.invalid.${e}`),"warning")}computeAngleDeg(e,t){const i=t.x-e.x,n=t.y-e.y;if(d.AcGeTol.isPositive(Math.hypot(i,n)))return Math.atan2(n,i)*180/Math.PI}async promptReferenceAngle(e,t,i){for(;;){const n=new Se(u.t("jig.rotate.referenceAngleOrPoints"));this.addKeyword(n,"points"),n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=i,n.allowNegative=!0,n.allowZero=!0,n.useDefaultValue=!0,n.defaultValue=0,n.jig=new As(e.view,t);const r=await k.instance.editor.getAngle(n);if(r.status===b.OK)return r.value??0;if(r.status===b.Keyword&&r.stringResult==="Points"){const o=new T(u.t("jig.rotate.firstReferencePoint"));o.jig=new As(e.view,t);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)return;const l=new T(u.t("jig.rotate.secondReferencePoint"));l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new d.AcGePoint3d(a.value),l.jig=new As(e.view,t);const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK)return;const h=this.computeAngleDeg(a.value,c.value);if(h==null){this.warnInvalidInput("referencePoints");continue}return h}return}}async promptRotationAngle(e,t,i){let n=!1;for(;;){const r=new Se(u.t("jig.rotate.rotationAngleOrOptions"));this.addKeyword(r,"copy"),this.addKeyword(r,"reference"),r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=i,r.allowNegative=!0,r.allowZero=!0,r.allowNone=!0,r.jig=new Hu(e.view,t,i);const o=await k.instance.editor.getAngle(r);if(o.status===b.OK)return{copyMode:n,angleRad:(o.value??0)*Math.PI/180};if(o.status!==b.Keyword)return;const a=o.stringResult??"";if(a==="Copy"){n=!0;continue}if(a!=="Reference")return;const l=await this.promptReferenceAngle(e,t,i);if(l==null)return;const c=new Se(u.t("jig.rotate.newAngle"));c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=i,c.allowNegative=!0,c.allowZero=!0,c.allowNone=!0,c.jig=new Hu(e.view,t,i,l);const h=await k.instance.editor.getAngle(c);return h.status!==b.OK?void 0:{copyMode:n,angleRad:((h.value??0)-l)*Math.PI/180}}}async execute(e){const t=e.view.selectionSet,i=await Un(e,{promptKey:"rotate"});if(!i)return;const{entities:n}=i,r=new T(u.t("jig.rotate.basePoint"));r.jig=new As(e.view,n),r.allowNone=!0;const o=await k.instance.editor.getPoint(r);if(o.status!==b.OK){t.clear();return}const a=new d.AcGePoint3d(o.value),l=await this.promptRotationAngle(e,n,a);if(!l){t.clear();return}const c=Yt(a,l.angleRad),h=e.doc.entityService;l.copyMode?h.cloneAndTransform(n,c):h.transformEntities(n,c),t.clear()}};Vo.createRotationMatrix=Yt;let Cs=Vo;class Wu extends z{async execute(e){const t=Yh(e);if(t>0){this.showMessage(`${t} ${u.t("jig.hideobjects.restored")}`,"success");return}this.showMessage(u.t("jig.hideobjects.nothingToRestore"),"info")}}const De=class De{constructor(e){this.disposed=!1,De.ensureStyles();const t=e.host??document.body,i=e.titleId??`ml-ui-dialog-title-${De.nextTitleId++}`;this.closeOnEscape=e.closeOnEscape??!0,this.previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null,this.backdrop=document.createElement("div"),this.backdrop.className="ml-ui-dialog-backdrop",vr(e.theme??kr(t),this.backdrop),(e.closeOnBackdrop??!0)&&this.backdrop.addEventListener("mousedown",o=>{o.target===this.backdrop&&this.close()}),this.dialog=document.createElement("div"),this.dialog.className=["ml-ui-dialog",e.dialogClassName].filter(Boolean).join(" "),this.dialog.setAttribute("role","dialog"),this.dialog.setAttribute("aria-modal","true"),this.dialog.setAttribute("aria-labelledby",i),this.dialog.tabIndex=-1,this.dialog.addEventListener("mousedown",o=>o.stopPropagation());const n=document.createElement("div");n.className="ml-ui-dialog-header",this.titleEl=document.createElement("div"),this.titleEl.id=i,this.titleEl.className="ml-ui-dialog-title",this.titleEl.textContent=e.title;const r=document.createElement("button");r.type="button",r.className="ml-ui-dialog-close",r.setAttribute("aria-label",e.closeLabel??"Close"),r.textContent="×",r.addEventListener("click",()=>this.close()),n.appendChild(this.titleEl),n.appendChild(r),this.bodyEl=document.createElement("div"),this.bodyEl.className="ml-ui-dialog-body",this.footerEl=document.createElement("div"),this.footerEl.className="ml-ui-dialog-footer",this.dialog.appendChild(n),this.dialog.appendChild(this.bodyEl),this.dialog.appendChild(this.footerEl),this.backdrop.appendChild(this.dialog),t.appendChild(this.backdrop),this.onKeyDown=o=>{if(o.key==="Escape"){if(!this.closeOnEscape)return;o.preventDefault(),this.close();return}o.key==="Tab"&&this.trapFocus(o)},window.addEventListener("keydown",this.onKeyDown)}show(){return this.openPromise||(this.openPromise=new Promise(e=>{this.resolve=e})),this.openPromise}close(){var e,t;this.disposed||(this.disposed=!0,window.removeEventListener("keydown",this.onKeyDown),this.backdrop.parentNode&&this.backdrop.parentNode.removeChild(this.backdrop),(e=this.previouslyFocused)==null||e.focus(),(t=this.resolve)==null||t.call(this),this.resolve=void 0)}focusAfterOpen(e){queueMicrotask(()=>e.focus())}trapFocus(e){const t=this.getFocusableElements();if(t.length===0){e.preventDefault(),this.dialog.focus();return}const i=t[0],n=t[t.length-1],r=document.activeElement;if(e.shiftKey){(r===i||!this.dialog.contains(r))&&(e.preventDefault(),n.focus());return}(r===n||!this.dialog.contains(r))&&(e.preventDefault(),i.focus())}getFocusableElements(){const e=["a[href]","button:not([disabled])","textarea:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(this.dialog.querySelectorAll(e)).filter(t=>!t.hasAttribute("disabled")&&t.getAttribute("aria-hidden")!=="true"&&t.tabIndex>=0&&t.offsetParent!==null)}static ensureStyles(){if(De.stylesInjected)return;if(document.getElementById(De.styleId)){De.stylesInjected=!0;return}const e=document.createElement("style");e.id=De.styleId,e.textContent=`
526
576
  .ml-ui-dialog-backdrop {
527
577
  position: fixed;
528
578
  inset: 0;
@@ -596,7 +646,7 @@
596
646
  .ml-ui-dialog-btn:hover {
597
647
  filter: brightness(1.05);
598
648
  }
599
- `.trim(),document.head.appendChild(e),Le.stylesInjected=!0}};Le.styleId="ml-ui-dialog-styles",Le.stylesInjected=!1,Le.nextTitleId=0;let xs=Le;const de=class de extends xs{constructor(e){super({host:e,title:d.t("main.about.title"),closeLabel:d.t("main.about.close"),titleId:"ml-ui-about-title",dialogClassName:"ml-ui-about-dialog"}),de.ensureAboutStyles(),this.buildContent()}static open(e=document.body){var i;(i=de.openInstance)==null||i.close();const t=new de(e);return de.openInstance=t,t.show()}close(){de.openInstance===this&&(de.openInstance=null),super.close()}buildContent(){const e=Vo({className:"ml-ui-about-brand",iconSize:"56px"}),t=document.createElement("div");t.className="ml-ui-about-product",t.textContent=d.t("main.about.product");const i=document.createElement("div");i.className="ml-ui-about-tagline",i.textContent=d.t("main.about.tagline");const n=document.createElement("div");n.className="ml-ui-about-links",n.appendChild(this.createLink(d.t("main.about.website"),zo)),n.appendChild(this.createLink(d.t("main.about.docs"),No)),n.appendChild(this.createLink(d.t("main.about.repository"),Ro));const r=document.createElement("div");r.className="ml-ui-about-copyright",r.textContent=d.t("main.about.copyright").replace("{year}",String(new Date().getFullYear())),this.bodyEl.appendChild(e),this.bodyEl.appendChild(t),this.bodyEl.appendChild(i),this.bodyEl.appendChild(n),this.bodyEl.appendChild(r);const o=document.createElement("button");o.type="button",o.className="ml-ui-dialog-btn",o.textContent=d.t("main.about.ok"),o.addEventListener("click",()=>this.close()),this.footerEl.appendChild(o),this.focusAfterOpen(o)}createLink(e,t){const i=document.createElement("a");return i.className="ml-ui-about-link",i.href=t,i.target="_blank",i.rel="noopener noreferrer",i.textContent=e,i}static ensureAboutStyles(){if(de.aboutStylesInjected)return;if(document.getElementById(de.aboutStyleId)){de.aboutStylesInjected=!0;return}const e=document.createElement("style");e.id=de.aboutStyleId,e.textContent=`
649
+ `.trim(),document.head.appendChild(e),De.stylesInjected=!0}};De.styleId="ml-ui-dialog-styles",De.stylesInjected=!1,De.nextTitleId=0;let _s=De;const he=class he extends _s{constructor(e){super({host:e,title:u.t("main.about.title"),closeLabel:u.t("main.about.close"),titleId:"ml-ui-about-title",dialogClassName:"ml-ui-about-dialog"}),he.ensureAboutStyles(),this.buildContent()}static open(e=document.body){var i;(i=he.openInstance)==null||i.close();const t=new he(e);return he.openInstance=t,t.show()}close(){he.openInstance===this&&(he.openInstance=null),super.close()}buildContent(){const e=Yo({className:"ml-ui-about-brand",iconSize:"56px"}),t=document.createElement("div");t.className="ml-ui-about-product",t.textContent=u.t("main.about.product");const i=document.createElement("div");i.className="ml-ui-about-tagline",i.textContent=u.t("main.about.tagline");const n=document.createElement("div");n.className="ml-ui-about-links",n.appendChild(this.createLink(u.t("main.about.website"),Ho)),n.appendChild(this.createLink(u.t("main.about.docs"),Wo)),n.appendChild(this.createLink(u.t("main.about.repository"),$o));const r=document.createElement("div");r.className="ml-ui-about-copyright",r.textContent=u.t("main.about.copyright").replace("{year}",String(new Date().getFullYear())),this.bodyEl.appendChild(e),this.bodyEl.appendChild(t),this.bodyEl.appendChild(i),this.bodyEl.appendChild(n),this.bodyEl.appendChild(r);const o=document.createElement("button");o.type="button",o.className="ml-ui-dialog-btn",o.textContent=u.t("main.about.ok"),o.addEventListener("click",()=>this.close()),this.footerEl.appendChild(o),this.focusAfterOpen(o)}createLink(e,t){const i=document.createElement("a");return i.className="ml-ui-about-link",i.href=t,i.target="_blank",i.rel="noopener noreferrer",i.textContent=e,i}static ensureAboutStyles(){if(he.aboutStylesInjected)return;if(document.getElementById(he.aboutStyleId)){he.aboutStylesInjected=!0;return}const e=document.createElement("style");e.id=he.aboutStyleId,e.textContent=`
600
650
  .ml-ui-about-brand {
601
651
  display: flex;
602
652
  flex-direction: column;
@@ -661,7 +711,7 @@
661
711
  font-size: 11px;
662
712
  color: var(--ml-ui-text-muted, #909399);
663
713
  }
664
- `.trim(),document.head.appendChild(e),de.aboutStylesInjected=!0}};de.aboutStyleId="ml-ui-about-dialog-styles",de.aboutStylesInjected=!1,de.openInstance=null;let Ss=de;class Ou extends z{constructor(){super(...arguments),this.recordsUndoStack=!1}async execute(e){var i;const t=((i=e.view)==null?void 0:i.container)??document.body;await Ss.open(t)}}let Gi=null;Q.on("font-file-selected",({file:s})=>{Gi==null||Gi(s),Gi=null});function cf(){return new Promise(s=>{Gi=s,Q.emit("cache-font",{})})}class Ki extends z{static async cacheFontFile(e,t){const i=(t==null?void 0:t.notify)??!0,n=new Ki;try{const r=await $i.cacheFont(e,void 0,t==null?void 0:t.aliases);return i&&(r.status==="Success"?n.notify(`${d.t("main.message.fontCached")}: ${r.fontName}`,"success"):n.notify(`${d.t("main.message.fontCacheFailed")}: ${e.name}`,"error")),r}catch{return i&&n.notify(`${d.t("main.message.fontCacheFailed")}: ${e.name}`,"error"),{fontName:"",url:"",status:"FailedToLoad"}}}async execute(e){const t=await cf();t&&await Ki.cacheFontFile(t)}}class ju extends z{async execute(e){this.printSelectionSet(e),this.printStats(e),this.printPerformanceData()}printSelectionSet(e){const t=e.doc.database.tables.blockTable.modelSpace;e.view.selectionSet.ids.forEach(i=>{const n=t.getIdAt(i);n&&u.log.info(n)})}printStats(e){const t=e.view.stats,i=t.layouts;u.log.info("Geometry information in current drawing:");for(let n=0;n<i.length;++n){console.group(`Layout: ${n}`);const r=i[n],o=[0,0,0,0,0,0,0],a=[0,0,0,0,0,0,0];let l=0;const c=r.layers.map(h=>(o[0]=h.line.indexed.geometrySize/1024,o[1]=h.line.nonIndexed.geometrySize/1024,o[2]=h.mesh.indexed.geometrySize/1024,o[3]=h.mesh.nonIndexed.geometrySize/1024,o[4]=h.point.indexed.geometrySize/1024,o[5]=h.point.nonIndexed.geometrySize/1024,o[6]=h.unbatched.geometrySize/1024,a[0]+=o[0],a[1]+=o[1],a[2]+=o[2],a[3]+=o[3],a[4]+=o[4],a[5]+=o[5],a[6]+=o[6],l+=h.unbatched.count,{name:h.name,"idx line (KB)":o[0].toFixed(1),"line (KB)":o[1].toFixed(1),"idx mesh (KB)":o[2].toFixed(1),"mesh (KB)":o[3].toFixed(1),"idx point (KB)":o[4].toFixed(1),"point (KB)":o[5].toFixed(1),"unbatched (KB)":o[6].toFixed(1),"unbatched count":h.unbatched.count,"unbatched line":h.unbatched.byType.line,"unbatched mesh":h.unbatched.byType.mesh,"unbatched point":h.unbatched.byType.point,"unbatched other":h.unbatched.byType.other,"total geo (KB)":(h.summary.totalGeometrySize/1024).toFixed(1),"total mapping (KB)":(h.summary.totalMappingSize/1024).toFixed(1)}));c.push({name:"total","idx line (KB)":a[0].toFixed(1),"line (KB)":a[1].toFixed(1),"idx mesh (KB)":a[2].toFixed(1),"mesh (KB)":a[3].toFixed(1),"idx point (KB)":a[4].toFixed(1),"point (KB)":a[5].toFixed(1),"unbatched (KB)":a[6].toFixed(1),"unbatched count":l,"unbatched line":r.summary.totalSize.unbatchedByType.line,"unbatched mesh":r.summary.totalSize.unbatchedByType.mesh,"unbatched point":r.summary.totalSize.unbatchedByType.point,"unbatched other":r.summary.totalSize.unbatchedByType.other,"total geo (KB)":(r.summary.totalSize.geometry/1024).toFixed(1),"total mapping (KB)":(r.summary.totalSize.mapping/1024).toFixed(1)}),console.table(c),console.table([{layoutCount:t.summary.layoutCount,entityCount:t.summary.entityCount,"scene line (KB)":(t.summary.totalSize.line/1024).toFixed(1),"scene mesh (KB)":(t.summary.totalSize.mesh/1024).toFixed(1),"scene point (KB)":(t.summary.totalSize.point/1024).toFixed(1),"scene unbatched (KB)":(t.summary.totalSize.unbatched/1024).toFixed(1),"scene unbatched count":t.summary.totalSize.unbatchedCount,"scene unbatched line":t.summary.totalSize.unbatchedByType.line,"scene unbatched mesh":t.summary.totalSize.unbatchedByType.mesh,"scene unbatched point":t.summary.totalSize.unbatchedByType.point,"scene unbatched other":t.summary.totalSize.unbatchedByType.other,"scene total geo (KB)":(t.summary.totalSize.geometry/1024).toFixed(1),"scene total mapping (KB)":(t.summary.totalSize.mapping/1024).toFixed(1)}]),console.groupEnd()}}printPerformanceData(){u.AcCmPerformanceCollector.getInstance().printAll()}}function Bu(s){return!Number.isFinite(s)||s<0?"—":s<1024?`${Math.round(s)} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:s<1024*1024*1024?`${(s/(1024*1024)).toFixed(2)} MB`:`${(s/(1024*1024*1024)).toFixed(2)} GB`}function df(){const e=performance.memory;if(e)return{usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}function Fu(s){return Object.entries(s).map(([e,t])=>({name:e,count:t.count,estimatedBytes:t.bytes})).sort((e,t)=>t.estimatedBytes-e.estimatedBytes)}function uf(s){const e=u.acdbEstimateDatabaseMemory(s);return{estimate:e,categories:Fu(e.byCategory),entitiesByType:Fu(e.byEntityType),estimatedBytes:e.totalBytes,entityCount:e.entityCount,objectCount:e.objectCount,isEstimated:!0}}function hf(s,e){const t=[];return s.layouts.forEach((i,n)=>{const r=e[n]??`layout-${n}`;for(const o of i.layers)t.push({layoutKey:r,layoutIndex:n,layerName:o.name,entityCount:o.summary.entityCount,lineBytes:o.line.indexed.geometrySize+o.line.nonIndexed.geometrySize,meshBytes:o.mesh.indexed.geometrySize+o.mesh.nonIndexed.geometrySize,pointBytes:o.point.indexed.geometrySize+o.point.nonIndexed.geometrySize,unbatchedBytes:o.unbatched.geometrySize,geometryBytes:o.summary.totalGeometrySize,mappingBytes:o.summary.totalMappingSize,unbatchedCount:o.unbatched.count})}),t}function zu(s,e){try{for(const t of e.tables.blockTable.newIterator())if(t.objectId===s)return String(t.name??s)}catch{}return s}function Nu(s){const e=[...s.mainThread.fonts,...s.workers.flatMap(i=>i.fonts)],t=new Map;for(const i of e){const n=i.names[0]??"(unnamed)",r=t.get(n);(!r||i.estimatedBytes>r.estimatedBytes)&&t.set(n,{name:n,type:i.type,estimatedBytes:i.estimatedBytes})}return[...t.values()].sort((i,n)=>n.estimatedBytes-i.estimatedBytes)}async function pf(){const s=D.FontManager.instance.missedFonts??{},e=Object.keys(s),t=await M.AcTrMTextRenderer.getInstance().estimateMemoryUsage(),i=t.workers.reduce((n,r)=>n+r.totalEstimatedBytes,0);return{missedCount:e.length,missedNames:e,estimatedBytes:t.totalEstimatedBytes,mainThreadBytes:t.mainThread.totalEstimatedBytes,workerBytes:i,loadedFontCount:Nu(t).length,indexedDbBytes:t.indexedDbFontCache.totalBytes,indexedDbFontCount:t.indexedDbFontCache.fontCount,fonts:Nu(t),report:t,isEstimated:!0}}async function Ru(s,e){const t=s.stats,i=[...s.cadScene.layouts.entries()],n=i.map(([S])=>zu(S,e)),r=hf(t,n),o=i.map(([S,P])=>({layoutKey:zu(S,e),stats:P.spatialIndexStats})),a=o.reduce((S,P)=>S+P.stats.estimatedBytes,0),l=o.reduce((S,P)=>S+(P.stats.rootItemCount??P.stats.itemCount),0),c=o.reduce((S,P)=>S+(P.stats.childItemCount??0),0),h=uf(e),p=s.renderer.styleManager.getStats(),m=await pf(),g=df(),f=t.summary.totalSize.geometry,w=t.summary.totalSize.mapping,v=[`${m.loadedFontCount} loaded`];m.missedCount>0&&v.push(`${m.missedCount} missed`);const x=[{id:"geometry",bytes:f,isEstimated:!1,detail:`${t.summary.entityCount} entities`},{id:"mapping",bytes:w,isEstimated:!0,detail:"batch slot metadata"},{id:"spatial",bytes:a,isEstimated:!0,detail:`${l} root / ${c} child items`},{id:"dataModel",bytes:h.estimatedBytes,isEstimated:!0,detail:`${h.entityCount} entities`},{id:"materials",bytes:p.totalEstimatedBytes,isEstimated:!0,detail:`${p.totalCount} cached`},{id:"fonts",bytes:m.estimatedBytes,isEstimated:!0,detail:v.join(" · ")}];return g&&x.unshift({id:"heap",bytes:g.usedJSHeapSize,isEstimated:!0,detail:`limit ${Bu(g.jsHeapSizeLimit)}`}),{collectedAt:Date.now(),heap:g,summary:x,geometry:{scene:t,layers:r},spatial:{layouts:o,totalEstimatedBytes:a,totalRootItems:l,totalChildItems:c},dataModel:h,materials:p,fonts:m}}class mf{static collect(e,t){return Ru(e,t)}}class Vu extends z{async execute(e){Q.emit("open-file",{})}}class Gu extends z{async execute(e){if(!await k.instance.newDocument())throw new Error("Failed to create new drawing")}}class Ku extends z{async execute(){k.instance.regen()}}class Uu extends z{async execute(e){e.view.mode=me.SELECTION,e.view.setCursor(Ce.Crosshair)}}class Hu extends z{constructor(){super(),this.mode=F.Review}async execute(e){const t=u.AcDbSysVarManager.instance(),i=t.getVar(this.globalName,e.doc.database),n=d.t("jig.sysvar.prompt").trim(),r=new le(n);i!=null&&(r.defaultValue=String(i),r.useDefaultValue=!0);const o=await k.instance.editor.getString(r);if(o.status!==b.OK||!o.stringResult)return;const a=o.stringResult;t.getDescriptor(this.globalName)&&t.setVar(this.globalName,a,e.doc.database)}}class Wu extends z{async execute(e){const t=e.doc.database,i=e.view,n=i.activeLayoutBtrId===i.modelSpaceBtrId,r=or(n),o=u.AcDbSysVarManager.instance();if(!o.getDescriptor(r))return;const l=o.getVar(r,t);o.setVar(r,$a(l),t)}}class $u extends z{constructor(){super(),this.globalName="undo",this.localName="Undo",this.recordsUndoStack=!1}async execute(e){const t=vt().undo(e.doc.database);if(!t){const i=d.sysCmdKey(this.globalName,"nothingToUndo");this.showMessage(d.sysCmd(this.globalName,"nothingToUndo"),"info",i);return}t==="markup"&&it().republishAll(e.view),lt()}}class Yu extends z{constructor(){super(),this.globalName="redo",this.localName="Redo",this.recordsUndoStack=!1}async execute(e){const t=vt().redo(e.doc.database);if(!t){const i=d.sysCmdKey(this.globalName,"nothingToRedo");this.showMessage(d.sysCmd(this.globalName,"nothingToRedo"),"info",i);return}t==="markup"&&it().republishAll(e.view),lt()}}class Tt extends z{captureCurrentViewBox(e){const t=e.view.screenToWorld({x:0,y:0}),i=e.view.screenToWorld({x:e.view.width,y:e.view.height});return new u.AcGeBox2d().expandByPoint(t).expandByPoint(i)}rememberViewBeforeZoom(e){Tt.previousViewBox=this.captureCurrentViewBox(e)}zoomToExtents(e){this.rememberViewBeforeZoom(e),e.view.zoomToFitDrawing()}zoomToWindow(e,t,i){const n=new u.AcGeBox2d().expandByPoint(t).expandByPoint(i);this.rememberViewBeforeZoom(e),e.view.zoomTo(n,1)}async promptAndZoomWindowFromFirstCorner(e,t){const i=new I(d.t("jig.zoom.secondCorner"));i.useBasePoint=!0,i.basePoint=new u.AcGePoint3d(t),i.useDashedLine=!0;const n=await k.instance.editor.getPoint(i);n.status!==b.OK||!n.value||this.zoomToWindow(e,t,n.value)}async promptAndZoomWindowByBox(e){const t=new In(d.t("jig.zoom.firstCorner"),d.t("jig.zoom.secondCorner")),i=await k.instance.editor.getBox(t);i.status!==b.OK||!i.value||(this.rememberViewBeforeZoom(e),e.view.zoomTo(i.value,1))}async runCenter(e){const t=new I(d.t("jig.zoom.centerPoint")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK||!i.value)return;const n=new le(d.t("jig.zoom.heightOrScale")),r=await k.instance.editor.getString(n);if(r.status!==b.OK||!r.stringResult)return;const o=this.parseScaleFactor(r.stringResult);if(o!=null){this.applyRelativeScale(e,o,i.value);return}const a=Number(r.stringResult);if(!Number.isFinite(a)||a<=0)return;const l=e.view.width/Math.max(e.view.height,1),c=a/2,h=a*l/2,p=new u.AcGeBox2d().expandByPoint({x:i.value.x-h,y:i.value.y-c}).expandByPoint({x:i.value.x+h,y:i.value.y+c});this.rememberViewBeforeZoom(e),e.view.zoomTo(p,1)}parseScaleFactor(e){const t=e.trim().toLowerCase();if(!t)return;if(t.endsWith("xp")){const n=Number(t.slice(0,-2));return Number.isFinite(n)&&n>0?n:void 0}if(t.endsWith("x")){const n=Number(t.slice(0,-1));return Number.isFinite(n)&&n>0?n:void 0}const i=Number(t);return Number.isFinite(i)&&i>0?i:void 0}applyRelativeScale(e,t,i){const n=this.captureCurrentViewBox(e),r=Math.max(n.max.x-n.min.x,u.FLOAT_TOL),o=Math.max(n.max.y-n.min.y,u.FLOAT_TOL),a=r/(2*t),l=o/(2*t),c=i??{x:(n.min.x+n.max.x)/2,y:(n.min.y+n.max.y)/2},h=new u.AcGeBox2d().expandByPoint({x:c.x-a,y:c.y-l}).expandByPoint({x:c.x+a,y:c.y+l});this.rememberViewBeforeZoom(e),e.view.zoomTo(h,1)}runPrevious(e){if(!Tt.previousViewBox)return;const t=this.captureCurrentViewBox(e);e.view.zoomTo(Tt.previousViewBox,1),Tt.previousViewBox=t}async execute(e){const t=new I(d.t("jig.zoom.mainPrompt"));t.allowNone=!0,t.keywords.add(d.t("jig.zoom.keywords.all.display"),d.t("jig.zoom.keywords.all.global"),d.t("jig.zoom.keywords.all.local")),t.keywords.add(d.t("jig.zoom.keywords.center.display"),d.t("jig.zoom.keywords.center.global"),d.t("jig.zoom.keywords.center.local")),t.keywords.add(d.t("jig.zoom.keywords.extents.display"),d.t("jig.zoom.keywords.extents.global"),d.t("jig.zoom.keywords.extents.local")),t.keywords.add(d.t("jig.zoom.keywords.previous.display"),d.t("jig.zoom.keywords.previous.global"),d.t("jig.zoom.keywords.previous.local")),t.keywords.add(d.t("jig.zoom.keywords.scale.display"),d.t("jig.zoom.keywords.scale.global"),d.t("jig.zoom.keywords.scale.local")),t.keywords.add(d.t("jig.zoom.keywords.window.display"),d.t("jig.zoom.keywords.window.global"),d.t("jig.zoom.keywords.window.local"));const i=await k.instance.editor.getPoint(t);if(i.status===b.None){this.zoomToExtents(e);return}if(i.status===b.OK&&i.value){await this.promptAndZoomWindowFromFirstCorner(e,i.value);return}if(i.status!==b.Keyword)return;const n=i.stringResult??"";if(n==="All"||n==="Extents"){this.zoomToExtents(e);return}if(n==="Window"){await this.promptAndZoomWindowByBox(e);return}if(n==="Center"){await this.runCenter(e);return}if(n==="Scale"){const r=new le(d.t("jig.zoom.scaleFactor")),o=await k.instance.editor.getString(r);if(o.status!==b.OK||!o.stringResult)return;const a=this.parseScaleFactor(o.stringResult);if(a==null)return;this.applyRelativeScale(e,a);return}n==="Previous"&&this.runPrevious(e)}}class Zu extends z{async execute(e){e.view.mode=me.PAN,e.view.setCursor(Ce.Grab)}}class Xu{constructor(e,t){this._plugins=new Map,this._lazyRegistrations=new Map,this._triggerToPluginName=new Map,this._lazyLoadPromises=new Map,this._context=e,this._commandManager=t}async loadPlugin(e){const t=e.name;if(!t)throw new Error("[AcApPluginManager] Plugin name is required");if(this._plugins.has(t))throw new Error(`[AcApPluginManager] Plugin '${t}' is already loaded`);try{await e.onLoad(this._context,this._commandManager)}catch(i){throw new Error(`[AcApPluginManager] Failed to load plugin '${t}': ${i}`)}this._plugins.set(t,e)}registerLazyPlugin(e){const t=e.name;if(!t)throw new Error("[AcApPluginManager] Lazy plugin name is required");if(this._lazyRegistrations.has(t))throw new Error(`[AcApPluginManager] Lazy plugin '${t}' is already registered`);if(!e.triggers.length)throw new Error(`[AcApPluginManager] Lazy plugin '${t}' requires at least one trigger`);this._lazyRegistrations.set(t,e);for(const i of e.triggers){const n=i.trim().toUpperCase();if(n){if(this._triggerToPluginName.has(n))throw new Error(`[AcApPluginManager] Trigger '${i}' is already registered to lazy plugin '${this._triggerToPluginName.get(n)}'`);this._triggerToPluginName.set(n,t)}}}isLazyPluginTrigger(e){return this._triggerToPluginName.has(e.trim().toUpperCase())}getLazyPluginTriggers(){return Array.from(this._triggerToPluginName.keys())}async loadByTrigger(e){const t=e.trim().toUpperCase(),i=this._triggerToPluginName.get(t);if(!i)return!1;if(this.isPluginLoaded(i))return!0;const n=this._lazyLoadPromises.get(i);if(n)return n;const r=this._lazyRegistrations.get(i);if(!r)return!1;const o=(async()=>{try{const a=await r.loader();if(a.name!==i)throw new Error(`[AcApPluginManager] Lazy plugin '${i}' loader returned plugin '${a.name}'`);return this.isPluginLoaded(i)||await this.loadPlugin(a),!0}catch(a){return u.log.error(`[AcApPluginManager] Failed to load lazy plugin '${i}' for trigger '${e}':`,a),!1}finally{this._lazyLoadPromises.delete(i)}})();return this._lazyLoadPromises.set(i,o),o}async unloadPlugin(e){const t=this._plugins.get(e);if(!t)return!1;try{await t.onUnload(this._context,this._commandManager)}catch(i){u.log.error(`[AcApPluginManager] Error unloading plugin '${e}':`,i)}return this._plugins.delete(e),!0}isPluginLoaded(e){return this._plugins.has(e)}getPlugin(e){return this._plugins.get(e)}getLoadedPlugins(){return Array.from(this._plugins.keys())}async unloadAllPlugins(){const e=Array.from(this._plugins.keys());for(const t of e)await this.unloadPlugin(t)}async loadPluginsFromConfig(e,t){const i=(t==null?void 0:t.continueOnError)??!1,n=[],r=[];for(const o of e)try{const a=typeof o=="function"?o():o;await this.loadPlugin(a),n.push(a.name)}catch(a){const l=typeof o=="function"?"Unknown":o.name||"Unknown",c=a instanceof Error?a:new Error(String(a));if(r.push({name:l,error:c}),!i)throw c}return{loaded:n,failed:r}}async loadPluginsFromFolder(e,t){const i=(t==null?void 0:t.continueOnError)??!1,n=(t==null?void 0:t.pluginList)||[],r=[],o=[];if(n.length===0)return u.log.warn("[AcApPluginManager] No plugin list provided. Cannot load plugins from folder without a list of files."),{loaded:r,failed:o};const a=e.replace(/\/$/,""),l=a.startsWith("./")?a:`./${a}`;for(const c of n)try{const p=await import(`${l}/${c.replace(/^\//,"")}`);let m=p.default,g;if(!m){const w=c.replace(/\.(js|ts)$/,"");g=w.split(/[-_]/).map(v=>v.charAt(0).toUpperCase()+v.slice(1).toLowerCase()).join(""),m=p[g]||p.Plugin||p[w]}if(!m){const w=g||"Plugin";throw new Error(`No plugin export found in ${c}. Expected default export, or named export 'Plugin' or '${w}'.`)}let f;if(typeof m=="function"?m.prototype&&m.prototype.onLoad?f=new m:f=m():f=m,!f||typeof f.onLoad!="function")throw new Error(`Invalid plugin in ${c}. Plugin must implement AcApPlugin interface.`);await this.loadPlugin(f),r.push(f.name)}catch(h){const p=h instanceof Error?h:new Error(String(h));if(o.push({name:c,error:p}),!i)throw p}return{loaded:r,failed:o}}}const yf={isDebug:!1,isShowCommandLine:!0,isShowCoordinate:!0,isShowEntityInfo:!1,isShowFileName:!0,isShowLanguageSelector:!0,isShowRibbon:!0,isShowToolbar:!0,isShowStats:!1,fontMapping:{},osnapModes:u.acdbOsnapModesToMask([u.AcDbOsnapMode.EndPoint,u.AcDbOsnapMode.MidPoint,u.AcDbOsnapMode.Center,u.AcDbOsnapMode.Quadrant,u.AcDbOsnapMode.Nearest])},wo="settings";function qu(s){const e={...s};let t=!1;return!("isShowRibbon"in e)&&typeof e.isShowMainMenu=="boolean"&&(e.isShowRibbon=e.isShowMainMenu,t=!0),"isShowMainMenu"in e&&(delete e.isShowMainMenu,t=!0),{settings:e,migrated:t}}class we{constructor(){this.events={modified:new u.AcCmEventManager}}static get instance(){return this._instance||(this._instance=new we),this._instance}set(e,t){const i=this.settings;i[e]=t,localStorage.setItem(wo,JSON.stringify(i)),this.events.modified.dispatch({key:e,value:t})}get(e){return this.settings[e]}toggle(e){const t=this.get(e);this.set(e,!t)}get isDebug(){return this.get("isDebug")}set isDebug(e){this.set("isDebug",e)}get isShowCommandLine(){return this.get("isShowCommandLine")}set isShowCommandLine(e){this.set("isShowCommandLine",e)}get isShowCoordinate(){return this.get("isShowCoordinate")}set isShowCoordinate(e){this.set("isShowCoordinate",e)}get isShowEntityInfo(){return this.get("isShowEntityInfo")}set isShowEntityInfo(e){this.set("isShowEntityInfo",e)}get isShowFileName(){return this.get("isShowFileName")}set isShowFileName(e){this.set("isShowFileName",e)}get isShowLanguageSelector(){return this.get("isShowLanguageSelector")}set isShowLanguageSelector(e){this.set("isShowLanguageSelector",e)}get isShowRibbon(){return this.get("isShowRibbon")}set isShowRibbon(e){this.set("isShowRibbon",e)}get isShowToolbar(){return this.get("isShowToolbar")}set isShowToolbar(e){this.set("isShowToolbar",e)}get isShowStats(){return this.get("isShowStats")}set isShowStats(e){this.set("isShowStats",e)}get fontMapping(){return this.get("fontMapping")}set fontMapping(e){this.set("fontMapping",e)}setFontMapping(e,t){const i=this.get("fontMapping");i[e]=t,this.set("fontMapping",i)}get osnapModes(){return this.get("osnapModes")}set osnapModes(e){this.set("osnapModes",e)}get settings(){const e=localStorage.getItem(wo),t=e==null?{}:JSON.parse(e),{settings:i,migrated:n}=qu(t),r=Bo.defaults(i,yf);return n&&localStorage.setItem(wo,JSON.stringify(r)),r}}const gf=new Set(["measuredistance","measurearea","measureangle","measurearc","measurepoint"]),ff=new Set(["markuptext","markupline","markuparrow","markupcloud","markuprect","markupcircle","markuphighlight","markupcallout","markupstamp"]);let Ju,vo=!1;const ko=new Set;function Qu(s){const e=s==null?void 0:s.trim().toLowerCase();if(e){if(gf.has(e))return"measure";if(ff.has(e))return"markup"}}function bf(s){Ju=s}function eh(){return Ju??we.instance.isShowRibbon}function th(s,e=eh()){return s!=null&&!e}function wf(){return vo}function vf(s){return ko.add(s),()=>{ko.delete(s)}}function xo(s){if(vo!==s){vo=s;for(const e of ko)e(s)}}const kf=[10,12,13,14,16,18,20,24,28,32],ih="ml-draw-style-toolbar-styles",xf=`
714
+ `.trim(),document.head.appendChild(e),he.aboutStylesInjected=!0}};he.aboutStyleId="ml-ui-about-dialog-styles",he.aboutStylesInjected=!1,he.openInstance=null;let Es=he;class $u extends z{constructor(){super(...arguments),this.recordsUndoStack=!1}async execute(e){var i;const t=((i=e.view)==null?void 0:i.container)??document.body;await Es.open(t)}}let Ki=null;ee.on("font-file-selected",({file:s})=>{Ki==null||Ki(s),Ki=null});function Rf(){return new Promise(s=>{Ki=s,ee.emit("cache-font",{})})}class Ui extends z{static async cacheFontFile(e,t){const i=(t==null?void 0:t.notify)??!0,n=new Ui;try{const r=await Yi.cacheFont(e,void 0,t==null?void 0:t.aliases);return i&&(r.status==="Success"?n.notify(`${u.t("main.message.fontCached")}: ${r.fontName}`,"success"):n.notify(`${u.t("main.message.fontCacheFailed")}: ${e.name}`,"error")),r}catch{return i&&n.notify(`${u.t("main.message.fontCacheFailed")}: ${e.name}`,"error"),{fontName:"",url:"",status:"FailedToLoad"}}}async execute(e){const t=await Rf();t&&await Ui.cacheFontFile(t)}}class Yu extends z{async execute(e){this.printSelectionSet(e),this.printStats(e),this.printPerformanceData()}printSelectionSet(e){const t=e.doc.database.tables.blockTable.modelSpace;e.view.selectionSet.ids.forEach(i=>{const n=t.getIdAt(i);n&&d.log.info(n)})}printStats(e){const t=e.view.stats,i=t.layouts;d.log.info("Geometry information in current drawing:");for(let n=0;n<i.length;++n){console.group(`Layout: ${n}`);const r=i[n],o=[0,0,0,0,0,0,0],a=[0,0,0,0,0,0,0];let l=0;const c=r.layers.map(h=>(o[0]=h.line.indexed.geometrySize/1024,o[1]=h.line.nonIndexed.geometrySize/1024,o[2]=h.mesh.indexed.geometrySize/1024,o[3]=h.mesh.nonIndexed.geometrySize/1024,o[4]=h.point.indexed.geometrySize/1024,o[5]=h.point.nonIndexed.geometrySize/1024,o[6]=h.unbatched.geometrySize/1024,a[0]+=o[0],a[1]+=o[1],a[2]+=o[2],a[3]+=o[3],a[4]+=o[4],a[5]+=o[5],a[6]+=o[6],l+=h.unbatched.count,{name:h.name,"idx line (KB)":o[0].toFixed(1),"line (KB)":o[1].toFixed(1),"idx mesh (KB)":o[2].toFixed(1),"mesh (KB)":o[3].toFixed(1),"idx point (KB)":o[4].toFixed(1),"point (KB)":o[5].toFixed(1),"unbatched (KB)":o[6].toFixed(1),"unbatched count":h.unbatched.count,"unbatched line":h.unbatched.byType.line,"unbatched mesh":h.unbatched.byType.mesh,"unbatched point":h.unbatched.byType.point,"unbatched other":h.unbatched.byType.other,"total geo (KB)":(h.summary.totalGeometrySize/1024).toFixed(1),"total mapping (KB)":(h.summary.totalMappingSize/1024).toFixed(1)}));c.push({name:"total","idx line (KB)":a[0].toFixed(1),"line (KB)":a[1].toFixed(1),"idx mesh (KB)":a[2].toFixed(1),"mesh (KB)":a[3].toFixed(1),"idx point (KB)":a[4].toFixed(1),"point (KB)":a[5].toFixed(1),"unbatched (KB)":a[6].toFixed(1),"unbatched count":l,"unbatched line":r.summary.totalSize.unbatchedByType.line,"unbatched mesh":r.summary.totalSize.unbatchedByType.mesh,"unbatched point":r.summary.totalSize.unbatchedByType.point,"unbatched other":r.summary.totalSize.unbatchedByType.other,"total geo (KB)":(r.summary.totalSize.geometry/1024).toFixed(1),"total mapping (KB)":(r.summary.totalSize.mapping/1024).toFixed(1)}),console.table(c),console.table([{layoutCount:t.summary.layoutCount,entityCount:t.summary.entityCount,"scene line (KB)":(t.summary.totalSize.line/1024).toFixed(1),"scene mesh (KB)":(t.summary.totalSize.mesh/1024).toFixed(1),"scene point (KB)":(t.summary.totalSize.point/1024).toFixed(1),"scene unbatched (KB)":(t.summary.totalSize.unbatched/1024).toFixed(1),"scene unbatched count":t.summary.totalSize.unbatchedCount,"scene unbatched line":t.summary.totalSize.unbatchedByType.line,"scene unbatched mesh":t.summary.totalSize.unbatchedByType.mesh,"scene unbatched point":t.summary.totalSize.unbatchedByType.point,"scene unbatched other":t.summary.totalSize.unbatchedByType.other,"scene total geo (KB)":(t.summary.totalSize.geometry/1024).toFixed(1),"scene total mapping (KB)":(t.summary.totalSize.mapping/1024).toFixed(1)}]),console.groupEnd()}}printPerformanceData(){d.AcCmPerformanceCollector.getInstance().printAll()}}function Zu(s){return!Number.isFinite(s)||s<0?"—":s<1024?`${Math.round(s)} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:s<1024*1024*1024?`${(s/(1024*1024)).toFixed(2)} MB`:`${(s/(1024*1024*1024)).toFixed(2)} GB`}function Vf(){const e=performance.memory;if(e)return{usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}function Xu(s){return Object.entries(s).map(([e,t])=>({name:e,count:t.count,estimatedBytes:t.bytes})).sort((e,t)=>t.estimatedBytes-e.estimatedBytes)}function Gf(s){const e=d.acdbEstimateDatabaseMemory(s);return{estimate:e,categories:Xu(e.byCategory),entitiesByType:Xu(e.byEntityType),estimatedBytes:e.totalBytes,entityCount:e.entityCount,objectCount:e.objectCount,isEstimated:!0}}function Kf(s,e){const t=[];return s.layouts.forEach((i,n)=>{const r=e[n]??`layout-${n}`;for(const o of i.layers)t.push({layoutKey:r,layoutIndex:n,layerName:o.name,entityCount:o.summary.entityCount,lineBytes:o.line.indexed.geometrySize+o.line.nonIndexed.geometrySize,meshBytes:o.mesh.indexed.geometrySize+o.mesh.nonIndexed.geometrySize,pointBytes:o.point.indexed.geometrySize+o.point.nonIndexed.geometrySize,unbatchedBytes:o.unbatched.geometrySize,geometryBytes:o.summary.totalGeometrySize,mappingBytes:o.summary.totalMappingSize,unbatchedCount:o.unbatched.count})}),t}function qu(s,e){try{for(const t of e.tables.blockTable.newIterator())if(t.objectId===s)return String(t.name??s)}catch{}return s}function Ju(s){const e=[...s.mainThread.fonts,...s.workers.flatMap(i=>i.fonts)],t=new Map;for(const i of e){const n=i.names[0]??"(unnamed)",r=t.get(n);(!r||i.estimatedBytes>r.estimatedBytes)&&t.set(n,{name:n,type:i.type,estimatedBytes:i.estimatedBytes})}return[...t.values()].sort((i,n)=>n.estimatedBytes-i.estimatedBytes)}async function Uf(){const s=D.FontManager.instance.missedFonts??{},e=Object.keys(s),t=await M.AcTrMTextRenderer.getInstance().estimateMemoryUsage(),i=t.workers.reduce((n,r)=>n+r.totalEstimatedBytes,0);return{missedCount:e.length,missedNames:e,estimatedBytes:t.totalEstimatedBytes,mainThreadBytes:t.mainThread.totalEstimatedBytes,workerBytes:i,loadedFontCount:Ju(t).length,indexedDbBytes:t.indexedDbFontCache.totalBytes,indexedDbFontCount:t.indexedDbFontCache.fontCount,fonts:Ju(t),report:t,isEstimated:!0}}async function Qu(s,e){const t=s.stats,i=[...s.cadScene.layouts.entries()],n=i.map(([S])=>qu(S,e)),r=Kf(t,n),o=i.map(([S,P])=>({layoutKey:qu(S,e),stats:P.spatialIndexStats})),a=o.reduce((S,P)=>S+P.stats.estimatedBytes,0),l=o.reduce((S,P)=>S+(P.stats.rootItemCount??P.stats.itemCount),0),c=o.reduce((S,P)=>S+(P.stats.childItemCount??0),0),h=Gf(e),p=s.renderer.styleManager.getStats(),m=await Uf(),g=Vf(),f=t.summary.totalSize.geometry,w=t.summary.totalSize.mapping,v=[`${m.loadedFontCount} loaded`];m.missedCount>0&&v.push(`${m.missedCount} missed`);const x=[{id:"geometry",bytes:f,isEstimated:!1,detail:`${t.summary.entityCount} entities`},{id:"mapping",bytes:w,isEstimated:!0,detail:"batch slot metadata"},{id:"spatial",bytes:a,isEstimated:!0,detail:`${l} root / ${c} child items`},{id:"dataModel",bytes:h.estimatedBytes,isEstimated:!0,detail:`${h.entityCount} entities`},{id:"materials",bytes:p.totalEstimatedBytes,isEstimated:!0,detail:`${p.totalCount} cached`},{id:"fonts",bytes:m.estimatedBytes,isEstimated:!0,detail:v.join(" · ")}];return g&&x.unshift({id:"heap",bytes:g.usedJSHeapSize,isEstimated:!0,detail:`limit ${Zu(g.jsHeapSizeLimit)}`}),{collectedAt:Date.now(),heap:g,summary:x,geometry:{scene:t,layers:r},spatial:{layouts:o,totalEstimatedBytes:a,totalRootItems:l,totalChildItems:c},dataModel:h,materials:p,fonts:m}}class Hf{static collect(e,t){return Qu(e,t)}}class eh extends z{async execute(e){ee.emit("open-file",{})}}class th extends z{async execute(e){if(!await k.instance.newDocument())throw new Error("Failed to create new drawing")}}class ih extends z{async execute(){k.instance.regen()}}class nh extends z{async execute(e){e.view.mode=ye.SELECTION,e.view.setCursor(Le.Crosshair)}}class sh extends z{constructor(){super(),this.mode=F.Review}async execute(e){const t=d.AcDbSysVarManager.instance(),i=t.getVar(this.globalName,e.doc.database),n=u.t("jig.sysvar.prompt").trim(),r=new ce(n);i!=null&&(r.defaultValue=String(i),r.useDefaultValue=!0);const o=await k.instance.editor.getString(r);if(o.status!==b.OK||!o.stringResult)return;const a=o.stringResult;t.getDescriptor(this.globalName)&&t.setVar(this.globalName,a,e.doc.database)}}class rh extends z{async execute(e){const t=e.doc.database,i=e.view,n=i.activeLayoutBtrId===i.modelSpaceBtrId,r=dr(n),o=d.AcDbSysVarManager.instance();if(!o.getDescriptor(r))return;const l=o.getVar(r,t);o.setVar(r,tl(l),t)}}class oh extends z{constructor(){super(),this.globalName="undo",this.localName="Undo",this.recordsUndoStack=!1}async execute(e){const t=xt().undo(e.doc.database);if(!t){const i=u.sysCmdKey(this.globalName,"nothingToUndo");this.showMessage(u.sysCmd(this.globalName,"nothingToUndo"),"info",i);return}t==="markup"&&ot().republishAll(e.view),ht()}}class ah extends z{constructor(){super(),this.globalName="redo",this.localName="Redo",this.recordsUndoStack=!1}async execute(e){const t=xt().redo(e.doc.database);if(!t){const i=u.sysCmdKey(this.globalName,"nothingToRedo");this.showMessage(u.sysCmd(this.globalName,"nothingToRedo"),"info",i);return}t==="markup"&&ot().republishAll(e.view),ht()}}class Mt extends z{captureCurrentViewBox(e){const t=e.view.screenToWorld({x:0,y:0}),i=e.view.screenToWorld({x:e.view.width,y:e.view.height});return new d.AcGeBox2d().expandByPoint(t).expandByPoint(i)}rememberViewBeforeZoom(e){Mt.previousViewBox=this.captureCurrentViewBox(e)}zoomToExtents(e){this.rememberViewBeforeZoom(e),e.view.zoomToFitDrawing()}zoomToWindow(e,t,i){const n=new d.AcGeBox2d().expandByPoint(t).expandByPoint(i);this.rememberViewBeforeZoom(e),e.view.zoomTo(n,1)}async promptAndZoomWindowFromFirstCorner(e,t){const i=new T(u.t("jig.zoom.secondCorner"));i.useBasePoint=!0,i.basePoint=new d.AcGePoint3d(t),i.useDashedLine=!0;const n=await k.instance.editor.getPoint(i);n.status!==b.OK||!n.value||this.zoomToWindow(e,t,n.value)}async promptAndZoomWindowByBox(e){const t=new Bn(u.t("jig.zoom.firstCorner"),u.t("jig.zoom.secondCorner")),i=await k.instance.editor.getBox(t);i.status!==b.OK||!i.value||(this.rememberViewBeforeZoom(e),e.view.zoomTo(i.value,1))}async runCenter(e){const t=new T(u.t("jig.zoom.centerPoint")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK||!i.value)return;const n=new ce(u.t("jig.zoom.heightOrScale")),r=await k.instance.editor.getString(n);if(r.status!==b.OK||!r.stringResult)return;const o=this.parseScaleFactor(r.stringResult);if(o!=null){this.applyRelativeScale(e,o,i.value);return}const a=Number(r.stringResult);if(!Number.isFinite(a)||a<=0)return;const l=e.view.width/Math.max(e.view.height,1),c=a/2,h=a*l/2,p=new d.AcGeBox2d().expandByPoint({x:i.value.x-h,y:i.value.y-c}).expandByPoint({x:i.value.x+h,y:i.value.y+c});this.rememberViewBeforeZoom(e),e.view.zoomTo(p,1)}parseScaleFactor(e){const t=e.trim().toLowerCase();if(!t)return;if(t.endsWith("xp")){const n=Number(t.slice(0,-2));return Number.isFinite(n)&&n>0?n:void 0}if(t.endsWith("x")){const n=Number(t.slice(0,-1));return Number.isFinite(n)&&n>0?n:void 0}const i=Number(t);return Number.isFinite(i)&&i>0?i:void 0}applyRelativeScale(e,t,i){const n=this.captureCurrentViewBox(e),r=Math.max(n.max.x-n.min.x,d.FLOAT_TOL),o=Math.max(n.max.y-n.min.y,d.FLOAT_TOL),a=r/(2*t),l=o/(2*t),c=i??{x:(n.min.x+n.max.x)/2,y:(n.min.y+n.max.y)/2},h=new d.AcGeBox2d().expandByPoint({x:c.x-a,y:c.y-l}).expandByPoint({x:c.x+a,y:c.y+l});this.rememberViewBeforeZoom(e),e.view.zoomTo(h,1)}runPrevious(e){if(!Mt.previousViewBox)return;const t=this.captureCurrentViewBox(e);e.view.zoomTo(Mt.previousViewBox,1),Mt.previousViewBox=t}async execute(e){const t=new T(u.t("jig.zoom.mainPrompt"));t.allowNone=!0,t.keywords.add(u.t("jig.zoom.keywords.all.display"),u.t("jig.zoom.keywords.all.global"),u.t("jig.zoom.keywords.all.local")),t.keywords.add(u.t("jig.zoom.keywords.center.display"),u.t("jig.zoom.keywords.center.global"),u.t("jig.zoom.keywords.center.local")),t.keywords.add(u.t("jig.zoom.keywords.extents.display"),u.t("jig.zoom.keywords.extents.global"),u.t("jig.zoom.keywords.extents.local")),t.keywords.add(u.t("jig.zoom.keywords.previous.display"),u.t("jig.zoom.keywords.previous.global"),u.t("jig.zoom.keywords.previous.local")),t.keywords.add(u.t("jig.zoom.keywords.scale.display"),u.t("jig.zoom.keywords.scale.global"),u.t("jig.zoom.keywords.scale.local")),t.keywords.add(u.t("jig.zoom.keywords.window.display"),u.t("jig.zoom.keywords.window.global"),u.t("jig.zoom.keywords.window.local"));const i=await k.instance.editor.getPoint(t);if(i.status===b.None){this.zoomToExtents(e);return}if(i.status===b.OK&&i.value){await this.promptAndZoomWindowFromFirstCorner(e,i.value);return}if(i.status!==b.Keyword)return;const n=i.stringResult??"";if(n==="All"||n==="Extents"){this.zoomToExtents(e);return}if(n==="Window"){await this.promptAndZoomWindowByBox(e);return}if(n==="Center"){await this.runCenter(e);return}if(n==="Scale"){const r=new ce(u.t("jig.zoom.scaleFactor")),o=await k.instance.editor.getString(r);if(o.status!==b.OK||!o.stringResult)return;const a=this.parseScaleFactor(o.stringResult);if(a==null)return;this.applyRelativeScale(e,a);return}n==="Previous"&&this.runPrevious(e)}}class lh extends z{async execute(e){e.view.mode=ye.PAN,e.view.setCursor(Le.Grab)}}class ch{constructor(e,t){this._plugins=new Map,this._lazyRegistrations=new Map,this._triggerToPluginName=new Map,this._lazyLoadPromises=new Map,this._context=e,this._commandManager=t}async loadPlugin(e){const t=e.name;if(!t)throw new Error("[AcApPluginManager] Plugin name is required");if(this._plugins.has(t))throw new Error(`[AcApPluginManager] Plugin '${t}' is already loaded`);try{await e.onLoad(this._context,this._commandManager)}catch(i){throw new Error(`[AcApPluginManager] Failed to load plugin '${t}': ${i}`)}this._plugins.set(t,e)}registerLazyPlugin(e){const t=e.name;if(!t)throw new Error("[AcApPluginManager] Lazy plugin name is required");if(this._lazyRegistrations.has(t))throw new Error(`[AcApPluginManager] Lazy plugin '${t}' is already registered`);if(!e.triggers.length)throw new Error(`[AcApPluginManager] Lazy plugin '${t}' requires at least one trigger`);this._lazyRegistrations.set(t,e);for(const i of e.triggers){const n=i.trim().toUpperCase();if(n){if(this._triggerToPluginName.has(n))throw new Error(`[AcApPluginManager] Trigger '${i}' is already registered to lazy plugin '${this._triggerToPluginName.get(n)}'`);this._triggerToPluginName.set(n,t)}}}isLazyPluginTrigger(e){return this._triggerToPluginName.has(e.trim().toUpperCase())}getLazyPluginTriggers(){return Array.from(this._triggerToPluginName.keys())}async loadByTrigger(e){const t=e.trim().toUpperCase(),i=this._triggerToPluginName.get(t);if(!i)return!1;if(this.isPluginLoaded(i))return!0;const n=this._lazyLoadPromises.get(i);if(n)return n;const r=this._lazyRegistrations.get(i);if(!r)return!1;const o=(async()=>{try{const a=await r.loader();if(a.name!==i)throw new Error(`[AcApPluginManager] Lazy plugin '${i}' loader returned plugin '${a.name}'`);return this.isPluginLoaded(i)||await this.loadPlugin(a),!0}catch(a){return d.log.error(`[AcApPluginManager] Failed to load lazy plugin '${i}' for trigger '${e}':`,a),!1}finally{this._lazyLoadPromises.delete(i)}})();return this._lazyLoadPromises.set(i,o),o}async unloadPlugin(e){const t=this._plugins.get(e);if(!t)return!1;try{await t.onUnload(this._context,this._commandManager)}catch(i){d.log.error(`[AcApPluginManager] Error unloading plugin '${e}':`,i)}return this._plugins.delete(e),!0}isPluginLoaded(e){return this._plugins.has(e)}getPlugin(e){return this._plugins.get(e)}getLoadedPlugins(){return Array.from(this._plugins.keys())}async unloadAllPlugins(){const e=Array.from(this._plugins.keys());for(const t of e)await this.unloadPlugin(t)}async loadPluginsFromConfig(e,t){const i=(t==null?void 0:t.continueOnError)??!1,n=[],r=[];for(const o of e)try{const a=typeof o=="function"?o():o;await this.loadPlugin(a),n.push(a.name)}catch(a){const l=typeof o=="function"?"Unknown":o.name||"Unknown",c=a instanceof Error?a:new Error(String(a));if(r.push({name:l,error:c}),!i)throw c}return{loaded:n,failed:r}}async loadPluginsFromFolder(e,t){const i=(t==null?void 0:t.continueOnError)??!1,n=(t==null?void 0:t.pluginList)||[],r=[],o=[];if(n.length===0)return d.log.warn("[AcApPluginManager] No plugin list provided. Cannot load plugins from folder without a list of files."),{loaded:r,failed:o};const a=e.replace(/\/$/,""),l=a.startsWith("./")?a:`./${a}`;for(const c of n)try{const p=await import(`${l}/${c.replace(/^\//,"")}`);let m=p.default,g;if(!m){const w=c.replace(/\.(js|ts)$/,"");g=w.split(/[-_]/).map(v=>v.charAt(0).toUpperCase()+v.slice(1).toLowerCase()).join(""),m=p[g]||p.Plugin||p[w]}if(!m){const w=g||"Plugin";throw new Error(`No plugin export found in ${c}. Expected default export, or named export 'Plugin' or '${w}'.`)}let f;if(typeof m=="function"?m.prototype&&m.prototype.onLoad?f=new m:f=m():f=m,!f||typeof f.onLoad!="function")throw new Error(`Invalid plugin in ${c}. Plugin must implement AcApPlugin interface.`);await this.loadPlugin(f),r.push(f.name)}catch(h){const p=h instanceof Error?h:new Error(String(h));if(o.push({name:c,error:p}),!i)throw p}return{loaded:r,failed:o}}}const Wf=new Set(["measuredistance","measurearea","measureangle","measurearc","measurepoint"]),$f=new Set(["markuptext","markupline","markuparrow","markupcloud","markuprect","markupcircle","markuphighlight","markupcallout","markupstamp"]);let dh,_o=!1;const Eo=new Set;function uh(s){const e=s==null?void 0:s.trim().toLowerCase();if(e){if(Wf.has(e))return"measure";if($f.has(e))return"markup"}}function hh(s){if(s.commandKind)return s.commandKind;if(!(s.markupSelected&&s.measurementSelected)){if(s.markupSelected)return"markup";if(s.measurementSelected)return"measure"}}function Yf(s){dh=s}function ph(){return dh??ue.instance.isShowRibbon}function mh(s,e=ph()){return s!=null&&!e}function Zf(){return _o}function Xf(s){return Eo.add(s),()=>{Eo.delete(s)}}function Lo(s){if(_o!==s){_o=s;for(const e of Eo)e(s)}}const qf=[10,12,13,14,16,18,20,24,28,32],yh="ml-draw-style-toolbar-styles",Jf=`
665
715
  .ml-draw-style-toolbar {
666
716
  position: absolute;
667
717
  top: 20px;
@@ -712,6 +762,107 @@
712
762
  font-size: 12px;
713
763
  padding: 0 6px;
714
764
  }
765
+ .ml-draw-style-toolbar__lineweight {
766
+ position: relative;
767
+ width: 120px;
768
+ flex: 0 0 120px;
769
+ }
770
+ .ml-draw-style-toolbar__lineweight-trigger {
771
+ display: flex;
772
+ align-items: center;
773
+ gap: 6px;
774
+ width: 100%;
775
+ height: 28px;
776
+ box-sizing: border-box;
777
+ padding: 0 6px;
778
+ border: 1px solid var(--ml-ui-border, #dcdfe6);
779
+ border-radius: 4px;
780
+ background: var(--ml-ui-bg, #fff);
781
+ color: inherit;
782
+ font-family: inherit;
783
+ font-size: 12px;
784
+ line-height: 1;
785
+ text-align: left;
786
+ cursor: pointer;
787
+ }
788
+ .ml-draw-style-toolbar__lineweight-label {
789
+ min-width: 0;
790
+ overflow: hidden;
791
+ text-overflow: ellipsis;
792
+ white-space: nowrap;
793
+ text-align: left;
794
+ }
795
+ .ml-draw-style-toolbar__lineweight-caret {
796
+ flex: 0 0 auto;
797
+ margin-left: auto;
798
+ width: 0;
799
+ height: 0;
800
+ border-left: 3.5px solid transparent;
801
+ border-right: 3.5px solid transparent;
802
+ border-top: 4px solid currentColor;
803
+ opacity: 0.55;
804
+ }
805
+ .ml-draw-style-toolbar__lineweight-preview {
806
+ position: relative;
807
+ display: inline-flex;
808
+ width: 36px;
809
+ height: 14px;
810
+ flex: 0 0 36px;
811
+ }
812
+ .ml-draw-style-toolbar__lineweight-preview::before {
813
+ content: '';
814
+ position: absolute;
815
+ left: 0;
816
+ right: 0;
817
+ top: 50%;
818
+ height: var(--ml-lineweight-height, 2px);
819
+ transform: translateY(-50%);
820
+ background-color: currentColor;
821
+ border-radius: 999px;
822
+ }
823
+ .ml-draw-style-toolbar__lineweight-menu {
824
+ display: none;
825
+ position: absolute;
826
+ top: calc(100% + 4px);
827
+ left: 0;
828
+ z-index: 2;
829
+ min-width: 148px;
830
+ max-height: 260px;
831
+ overflow-y: auto;
832
+ padding: 4px 0;
833
+ border: 1px solid var(--ml-ui-border, #dcdfe6);
834
+ border-radius: 6px;
835
+ background: var(--ml-ui-bg, rgba(255, 255, 255, 0.98));
836
+ box-shadow: var(--ml-ui-shadow, 0 4px 12px rgba(0, 0, 0, 0.16));
837
+ }
838
+ .ml-draw-style-toolbar__lineweight-menu.is-open {
839
+ display: block;
840
+ }
841
+ .ml-draw-style-toolbar__lineweight-item {
842
+ display: flex;
843
+ align-items: center;
844
+ gap: 6px;
845
+ width: 100%;
846
+ box-sizing: border-box;
847
+ padding: 4px 10px;
848
+ border: 0;
849
+ background: transparent;
850
+ color: inherit;
851
+ font-family: inherit;
852
+ font-size: 12px;
853
+ cursor: pointer;
854
+ }
855
+ .ml-draw-style-toolbar__lineweight-item:hover,
856
+ .ml-draw-style-toolbar__lineweight-item.is-selected {
857
+ background: var(--ml-ui-hover, rgba(64, 158, 255, 0.12));
858
+ }
859
+ .ml-draw-style-toolbar__lineweight-text {
860
+ min-width: 0;
861
+ overflow: hidden;
862
+ text-overflow: ellipsis;
863
+ white-space: nowrap;
864
+ text-align: left;
865
+ }
715
866
  .ml-draw-style-toolbar__color {
716
867
  position: relative;
717
868
  }
@@ -762,12 +913,12 @@
762
913
  outline: 2px solid var(--ml-ui-accent, #409eff);
763
914
  outline-offset: -1px;
764
915
  }
765
- `;function nh(s){const e=new u.AcCmColor;return e.colorIndex=s,e}function Sf(s){return nh(s).cssColor||"#ffffff"}function sh(s){if(s.isByACI&&s.colorIndex!=null&&s.colorIndex>=1)return s.colorIndex}const Pf=Array.from({length:9},(s,e)=>e+1),Af=Array.from({length:240},(s,e)=>e+10),Cf=Array.from({length:6},(s,e)=>e+250);function _f(){return Array.from(new Set(Object.values(u.AcGiLineWeight).filter(s=>typeof s=="number"&&s>0))).sort((s,e)=>s-e)}function rh(s){return`${(s/100).toFixed(2)} mm`}function Ef(){if(typeof document>"u")return;let s=document.getElementById(ih);s||(s=document.createElement("style"),s.id=ih,document.head.appendChild(s)),s.textContent=xf}class oh{constructor(e){this.view=e,this.colorPanelOpen=!1,Ef(),this.root=document.createElement("div"),this.root.className="ml-draw-style-toolbar",this.root.setAttribute("role","toolbar"),gr(fr(e.container),this.root),this.colorWrap=document.createElement("div"),this.colorWrap.className="ml-draw-style-toolbar__color",this.swatch=document.createElement("button"),this.swatch.type="button",this.swatch.className="ml-draw-style-toolbar__swatch",this.swatchFill=document.createElement("span"),this.swatchFill.className="ml-draw-style-toolbar__swatch-fill",this.swatch.appendChild(this.swatchFill),this.colorPanel=document.createElement("div"),this.colorPanel.className="ml-draw-style-toolbar__color-panel",this.colorPanel.appendChild(this.createAciPalette(Af,"ml-draw-style-toolbar__aci-large")),this.colorPanel.appendChild(this.createAciPalette(Pf,"ml-draw-style-toolbar__aci-small")),this.colorPanel.appendChild(this.createAciPalette(Cf,"ml-draw-style-toolbar__aci-gray")),this.colorWrap.appendChild(this.swatch),this.colorWrap.appendChild(this.colorPanel),this.root.appendChild(this.colorWrap),this.lineWeightSelect=document.createElement("select"),this.lineWeightSelect.className="ml-draw-style-toolbar__select";for(const i of _f()){const n=document.createElement("option");n.value=String(i),n.textContent=rh(i),this.lineWeightSelect.appendChild(n)}this.root.appendChild(this.lineWeightSelect),this.fontSizeSelect=document.createElement("select"),this.fontSizeSelect.className="ml-draw-style-toolbar__select",this.root.appendChild(this.fontSizeSelect),this.swatch.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.colorPanelOpen?this.hideColorPanel():this.showColorPanel()}),this.colorWrap.addEventListener("mouseenter",()=>this.clearColorLeaveTimer()),this.colorWrap.addEventListener("mouseleave",()=>this.scheduleHideColorPanel()),this.lineWeightSelect.addEventListener("change",()=>{const i=Number(this.lineWeightSelect.value);i>0&&this.applyLineWeight(i)}),this.fontSizeSelect.addEventListener("change",()=>{const i=Number(this.fontSizeSelect.value);i>0&&this.applyFontSize(i)}),this.root.addEventListener("pointerdown",i=>i.stopPropagation()),this.root.addEventListener("mousedown",i=>i.stopPropagation()),this.onDocumentPointerDown=i=>{if(!this.colorPanelOpen)return;const n=i.target;n&&this.colorWrap.contains(n)||(this.hideColorPanel(),i.preventDefault(),i.stopPropagation())},document.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.onCommandWillStart=i=>{this.setKind(Qu(i.command.globalName))},this.onCommandEnded=()=>this.setKind(void 0);const t=e.container;getComputedStyle(t).position==="static"&&(t.style.position="relative"),t.appendChild(this.root),e.editor.events.commandWillStart.addEventListener(this.onCommandWillStart),e.editor.events.commandEnded.addEventListener(this.onCommandEnded),this.onSettingsModified=i=>{i.key==="isShowRibbon"&&this.refreshVisibility()},we.instance.events.modified.addEventListener(this.onSettingsModified),this.relabel()}dispose(){this.hideColorPanel(),document.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.view.editor.events.commandWillStart.removeEventListener(this.onCommandWillStart),this.view.editor.events.commandEnded.removeEventListener(this.onCommandEnded),we.instance.events.modified.removeEventListener(this.onSettingsModified),this.root.remove(),xo(!1)}setKind(e){this.kind=e,this.refreshVisibility()}refreshVisibility(){const e=th(this.kind);this.root.classList.toggle("is-visible",e),xo(e),e?(this.relabel(),this.syncFromSession()):this.hideColorPanel()}relabel(){this.swatch.title=d.t("main.drawStyle.color"),this.lineWeightSelect.title=d.t("main.drawStyle.lineWeight"),this.fontSizeSelect.title=d.t("main.drawStyle.fontSize")}syncFromSession(){if(this.kind==="measure"){const r=ba(),o=u.acdbHostApplicationServices().workingDatabase,a=(r==null?void 0:r.color)??(o?Je(o):$s("#7b8794")),l=(r==null?void 0:r.lineWeight)??jt(),c=(r==null?void 0:r.fontSize)??wt();this.paint(a,l,c);return}const e=U().selectedId?U().get(U().selectedId):void 0,t=e?mo(e.style.color):ee(),i=(e==null?void 0:e.style.lineWeight)??Pe(),n=(e==null?void 0:e.style.fontSize)??tt();this.paint(t,i,n)}paint(e,t,i){const n=ge(e);this.swatchFill.style.background=n,this.markSelectedAci(sh(e));const r=String(t);if(!Array.from(this.lineWeightSelect.options).some(l=>l.value===r)){const l=document.createElement("option");l.value=r,l.textContent=rh(t),this.lineWeightSelect.appendChild(l)}this.lineWeightSelect.value=r;const o=new Set(kf);Number.isFinite(i)&&i>0&&o.add(Math.round(i));const a=[...o].sort((l,c)=>l-c);this.fontSizeSelect.replaceChildren();for(const l of a){const c=document.createElement("option");c.value=String(l),c.textContent=`${l} px`,this.fontSizeSelect.appendChild(c)}this.fontSizeSelect.value=String(Number.isFinite(i)&&i>0?Math.round(i):12)}applyColor(e){if(this.swatchFill.style.background=ge(e),this.markSelectedAci(sh(e)),this.kind==="measure"){ea(e),un(this.view,{color:e});return}Gd(e),bs(this.view,{color:Et(e)})}createAciPalette(e,t){const i=document.createElement("div");i.className=t;for(const n of e){const r=document.createElement("button");r.type="button",r.className="ml-draw-style-toolbar__aci-cell",r.dataset.aci=String(n),r.style.background=Sf(n),r.title=String(n),r.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),this.applyColor(nh(n)),this.hideColorPanel()}),i.appendChild(r)}return i}markSelectedAci(e){this.colorPanel.querySelectorAll(".ml-draw-style-toolbar__aci-cell").forEach(t=>{const i=t;i.classList.toggle("is-selected",i.dataset.aci===String(e))})}showColorPanel(){this.clearColorLeaveTimer(),this.colorPanelOpen=!0,this.colorPanel.classList.add("is-open")}hideColorPanel(){this.clearColorLeaveTimer(),this.colorPanelOpen=!1,this.colorPanel.classList.remove("is-open")}scheduleHideColorPanel(){this.clearColorLeaveTimer(),this.colorLeaveTimer=window.setTimeout(()=>this.hideColorPanel(),180)}clearColorLeaveTimer(){this.colorLeaveTimer!=null&&(window.clearTimeout(this.colorLeaveTimer),this.colorLeaveTimer=void 0)}applyLineWeight(e){if(this.kind==="measure"){ta(e),un(this.view,{lineWeight:e});return}Kd(e),bs(this.view,{lineWeight:e})}applyFontSize(e){if(this.kind==="measure"){ia(e),un(this.view,{fontSize:e});return}Ud(e),bs(this.view,{fontSize:e})}}function So(s){if(!s)return[];const t=(s.includes(`
916
+ `;function gh(s){const e=new d.AcCmColor;return e.colorIndex=s,e}function Qf(s){return gh(s).cssColor||"#ffffff"}function fh(s){if(s.isByACI&&s.colorIndex!=null&&s.colorIndex>=1)return s.colorIndex}const eb=Array.from({length:9},(s,e)=>e+1),tb=Array.from({length:240},(s,e)=>e+10),ib=Array.from({length:6},(s,e)=>e+250);function nb(){return Array.from(new Set(Object.values(d.AcGiLineWeight).filter(s=>typeof s=="number"&&s>0))).sort((s,e)=>s-e)}function bh(s){return`${(s/100).toFixed(2)} mm`}function wh(s){return Math.max(1,Math.min(6,s/40))}function sb(s,e){const t="ml-draw-style-toolbar",i=nb();let n=!1;const r=document.createElement("div");r.className=`${t}__lineweight`;const o=document.createElement("button");o.type="button",o.className=`${t}__lineweight-trigger`,o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-expanded","false");const a=document.createElement("span");a.className=`${t}__lineweight-preview`;const l=document.createElement("span");l.className=`${t}__lineweight-label`;const c=document.createElement("span");c.className=`${t}__lineweight-caret`,c.setAttribute("aria-hidden","true"),o.append(a,l,c);const h=document.createElement("div");h.className=`${t}__lineweight-menu`,h.setAttribute("role","listbox");const p=v=>{a.style.setProperty("--ml-lineweight-height",`${wh(v)}px`),l.textContent=bh(v)},m=v=>{h.querySelectorAll(`.${t}__lineweight-item`).forEach(x=>{const S=x;S.classList.toggle("is-selected",S.dataset.value===String(v))})},g=()=>{n=!1,h.classList.remove("is-open"),o.setAttribute("aria-expanded","false")},f=()=>{e(),n=!0,h.classList.add("is-open"),o.setAttribute("aria-expanded","true")},w=v=>{const x=document.createElement("button");x.type="button",x.className=`${t}__lineweight-item`,x.dataset.value=String(v),x.setAttribute("role","option");const S=document.createElement("span");S.className=`${t}__lineweight-preview`,S.style.setProperty("--ml-lineweight-height",`${wh(v)}px`);const P=document.createElement("span");P.className=`${t}__lineweight-text`,P.textContent=bh(v),x.append(S,P),x.addEventListener("click",A=>{A.preventDefault(),A.stopPropagation(),p(v),m(v),g(),s(v)}),h.appendChild(x)};for(const v of i)w(v);return o.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),n?g():f()}),r.append(o,h),p(i[0]??25),m(i[0]??25),{root:r,setValue:v=>{v>0&&(h.querySelector(`[data-value="${v}"]`)||w(v),p(v),m(v))},setTitle:v=>{o.title=v},close:g,isOpen:()=>n,contains:v=>!!v&&r.contains(v)}}function rb(){if(typeof document>"u")return;let s=document.getElementById(yh);s||(s=document.createElement("style"),s.id=yh,document.head.appendChild(s)),s.textContent=Jf}class vh{constructor(e){this.view=e,this.colorPanelOpen=!1,rb(),this.root=document.createElement("div"),this.root.className="ml-draw-style-toolbar",this.root.setAttribute("role","toolbar"),vr(kr(e.container),this.root),this.colorWrap=document.createElement("div"),this.colorWrap.className="ml-draw-style-toolbar__color",this.swatch=document.createElement("button"),this.swatch.type="button",this.swatch.className="ml-draw-style-toolbar__swatch",this.swatchFill=document.createElement("span"),this.swatchFill.className="ml-draw-style-toolbar__swatch-fill",this.swatch.appendChild(this.swatchFill),this.colorPanel=document.createElement("div"),this.colorPanel.className="ml-draw-style-toolbar__color-panel",this.colorPanel.appendChild(this.createAciPalette(tb,"ml-draw-style-toolbar__aci-large")),this.colorPanel.appendChild(this.createAciPalette(eb,"ml-draw-style-toolbar__aci-small")),this.colorPanel.appendChild(this.createAciPalette(ib,"ml-draw-style-toolbar__aci-gray")),this.colorWrap.appendChild(this.swatch),this.colorWrap.appendChild(this.colorPanel),this.root.appendChild(this.colorWrap),this.lineWeightPicker=sb(i=>this.applyLineWeight(i),()=>this.hideColorPanel()),this.root.appendChild(this.lineWeightPicker.root),this.fontSizeSelect=document.createElement("select"),this.fontSizeSelect.className="ml-draw-style-toolbar__select",this.root.appendChild(this.fontSizeSelect),this.swatch.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.colorPanelOpen?this.hideColorPanel():this.showColorPanel()}),this.colorWrap.addEventListener("mouseenter",()=>this.clearColorLeaveTimer()),this.colorWrap.addEventListener("mouseleave",()=>this.scheduleHideColorPanel()),this.fontSizeSelect.addEventListener("change",()=>{const i=Number(this.fontSizeSelect.value);i>0&&this.applyFontSize(i)}),this.root.addEventListener("pointerdown",i=>i.stopPropagation()),this.root.addEventListener("mousedown",i=>i.stopPropagation()),this.onDocumentPointerDown=i=>{const n=i.target,r=!!n&&this.colorWrap.contains(n),o=this.lineWeightPicker.contains(n),a=this.colorPanelOpen,l=this.lineWeightPicker.isOpen();!a&&!l||(a&&!r&&this.hideColorPanel(),l&&!o&&this.lineWeightPicker.close(),!r&&!o&&(i.preventDefault(),i.stopPropagation()))},document.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.onCommandWillStart=i=>{this.commandKind=uh(i.command.globalName),this.refreshKindAndVisibility()},this.onCommandEnded=()=>{this.commandKind=void 0,this.refreshKindAndVisibility()};const t=e.container;getComputedStyle(t).position==="static"&&(t.style.position="relative"),t.appendChild(this.root),e.editor.events.commandWillStart.addEventListener(this.onCommandWillStart),e.editor.events.commandEnded.addEventListener(this.onCommandEnded),this.onSettingsModified=i=>{i.key==="isShowRibbon"&&this.refreshKindAndVisibility()},ue.instance.events.modified.addEventListener(this.onSettingsModified),this.unsubscribeMarkupStore=K().subscribe(()=>{this.refreshKindAndVisibility()}),this.unsubscribeMeasurementSelection=Ca(()=>{this.refreshKindAndVisibility()}),this.relabel()}dispose(){this.hideColorPanel(),this.lineWeightPicker.close(),document.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.view.editor.events.commandWillStart.removeEventListener(this.onCommandWillStart),this.view.editor.events.commandEnded.removeEventListener(this.onCommandEnded),ue.instance.events.modified.removeEventListener(this.onSettingsModified),this.unsubscribeMarkupStore(),this.unsubscribeMeasurementSelection(),this.root.remove(),Lo(!1)}refreshKindAndVisibility(){this.kind=hh({commandKind:this.commandKind,markupSelected:K().selectedId!=null,measurementSelected:Pa()!=null}),this.refreshVisibility()}refreshVisibility(){const e=mh(this.kind);this.root.classList.toggle("is-visible",e),Lo(e),e?(this.relabel(),this.syncFromSession()):(this.hideColorPanel(),this.lineWeightPicker.close())}relabel(){this.swatch.title=u.t("main.drawStyle.color"),this.lineWeightPicker.setTitle(u.t("main.drawStyle.lineWeight")),this.fontSizeSelect.title=u.t("main.drawStyle.fontSize")}syncFromSession(){if(this.kind==="measure"){const r=Aa(),o=d.acdbHostApplicationServices().workingDatabase,a=(r==null?void 0:r.color)??(o?Oe(o):qs("#7b8794")),l=(r==null?void 0:r.lineWeight)??tt(),c=(r==null?void 0:r.fontSize)??Be();this.paint(a,l,c);return}const e=K().selectedId?K().get(K().selectedId):void 0,t=e?xo(e.style.color):J(),i=(e==null?void 0:e.style.lineWeight)??Ae(),n=(e==null?void 0:e.style.fontSize)??qe();this.paint(t,i,n)}paint(e,t,i){const n=ve(e);this.swatchFill.style.background=n,this.markSelectedAci(fh(e)),this.lineWeightPicker.setValue(t);const r=new Set(qf);Number.isFinite(i)&&i>0&&r.add(Math.round(i));const o=[...r].sort((a,l)=>a-l);this.fontSizeSelect.replaceChildren();for(const a of o){const l=document.createElement("option");l.value=String(a),l.textContent=`${a} px`,this.fontSizeSelect.appendChild(l)}this.fontSizeSelect.value=String(Number.isFinite(i)&&i>0?Math.round(i):12)}applyColor(e){if(this.swatchFill.style.background=ve(e),this.markSelectedAci(fh(e)),this.kind==="measure"){oa(e),hn(this.view,{color:e});return}tu(e),Ss(this.view,{color:Tt(e)})}createAciPalette(e,t){const i=document.createElement("div");i.className=t;for(const n of e){const r=document.createElement("button");r.type="button",r.className="ml-draw-style-toolbar__aci-cell",r.dataset.aci=String(n),r.style.background=Qf(n),r.title=String(n),r.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),this.applyColor(gh(n)),this.hideColorPanel()}),i.appendChild(r)}return i}markSelectedAci(e){this.colorPanel.querySelectorAll(".ml-draw-style-toolbar__aci-cell").forEach(t=>{const i=t;i.classList.toggle("is-selected",i.dataset.aci===String(e))})}showColorPanel(){this.lineWeightPicker.close(),this.clearColorLeaveTimer(),this.colorPanelOpen=!0,this.colorPanel.classList.add("is-open")}hideColorPanel(){this.clearColorLeaveTimer(),this.colorPanelOpen=!1,this.colorPanel.classList.remove("is-open")}scheduleHideColorPanel(){this.clearColorLeaveTimer(),this.colorLeaveTimer=window.setTimeout(()=>this.hideColorPanel(),180)}clearColorLeaveTimer(){this.colorLeaveTimer!=null&&(window.clearTimeout(this.colorLeaveTimer),this.colorLeaveTimer=void 0)}applyLineWeight(e){if(this.kind==="measure"){aa(e),hn(this.view,{lineWeight:e});return}iu(e),Ss(this.view,{lineWeight:e})}applyFontSize(e){if(this.kind==="measure"){la(e),hn(this.view,{fontSize:e});return}nu(e),Ss(this.view,{fontSize:e})}}function To(s){if(!s)return[];const t=(s.includes(`
766
917
  `)||s.includes("\r")?s:s.replace(/\\n/g,`
767
918
  `)).replace(/\r\n/g,`
768
919
  `).replace(/\r/g,`
769
920
  `).split(`
770
- `),i=[];for(const n of t)n.trimStart().startsWith(";")||i.push(n);return i}function ah(s){const e=s.trim().toUpperCase();return e==="QUIT"||e==="EXIT"}const st=class st{constructor(e={}){const t=e.showBrand??!0;this.options={size:e.size??(t?"72px":"48px"),borderWidth:e.borderWidth??(t?"4px":"5px"),color:e.color??"var(--ml-ui-accent, #0b84ff)",host:e.host??document.body,overlay:e.overlay??!0,overlayColor:e.overlayColor??"var(--ml-ui-overlay, rgba(0,0,0,0.5))",message:e.message??"",showBrand:t},st.stylesInjected||this.injectStyles(),this.createDom()}show(){return this.root.style.display="flex",this}hide(){return this.root.style.display="none",this}setMessage(e=""){return this.messageEl.textContent=e,this.messageEl.style.display=e?"block":"none",this}setOverlayColor(e){return this.options.overlay&&this.root&&(this.root.style.background=e),this}destroy(){var e;(e=this.root)!=null&&e.parentNode&&this.root.parentNode.removeChild(this.root)}createDom(){const e=this.options.host;getComputedStyle(e).position==="static"&&(e.style.position="relative");const i=document.createElement("div");i.className="ml-ccl-overlay",i.style.display="flex",i.style.background=this.options.overlay?this.options.overlayColor:"transparent";const n=document.createElement("div");n.className="ml-ccl-spinner-stage",n.style.width=this.options.size,n.style.height=this.options.size;const r=document.createElement("div");if(r.className="ml-ccl-spinner",r.style.borderWidth=this.options.borderWidth,r.style.borderTopColor=this.options.color,n.appendChild(r),this.options.showBrand){const l=Ds({className:"ml-ccl-spinner-icon",size:"60%"});n.appendChild(l);const c=document.createElement("div");c.className="ml-ccl-message",c.textContent=this.options.message,c.style.display=this.options.message?"block":"none";const h=document.createElement("div");h.className="ml-ccl-wrapper",h.appendChild(n),h.appendChild(c),i.appendChild(h),e.appendChild(i),this.root=i,this.spinner=r,this.messageEl=c;return}const o=document.createElement("div");o.className="ml-ccl-message",o.textContent=this.options.message,o.style.display=this.options.message?"block":"none";const a=document.createElement("div");a.className="ml-ccl-wrapper",a.appendChild(n),a.appendChild(o),i.appendChild(a),e.appendChild(i),this.root=i,this.spinner=r,this.messageEl=o}injectStyles(){if(document.getElementById(st.styleId)){st.stylesInjected=!0;return}const e=`
921
+ `),i=[];for(const n of t)n.trimStart().startsWith(";")||i.push(n);return i}function kh(s){const e=s.trim().toUpperCase();return e==="QUIT"||e==="EXIT"}const lt=class lt{constructor(e={}){const t=e.showBrand??!0;this.options={size:e.size??(t?"72px":"48px"),borderWidth:e.borderWidth??(t?"4px":"5px"),color:e.color??"var(--ml-ui-accent, #0b84ff)",host:e.host??document.body,overlay:e.overlay??!0,overlayColor:e.overlayColor??"var(--ml-ui-overlay, rgba(0,0,0,0.5))",message:e.message??"",showBrand:t},lt.stylesInjected||this.injectStyles(),this.createDom()}show(){return this.root.style.display="flex",this}hide(){return this.root.style.display="none",this}setMessage(e=""){return this.messageEl.textContent=e,this.messageEl.style.display=e?"block":"none",this}setOverlayColor(e){return this.options.overlay&&this.root&&(this.root.style.background=e),this}destroy(){var e;(e=this.root)!=null&&e.parentNode&&this.root.parentNode.removeChild(this.root)}createDom(){const e=this.options.host;getComputedStyle(e).position==="static"&&(e.style.position="relative");const i=document.createElement("div");i.className="ml-ccl-overlay",i.style.display="flex",i.style.background=this.options.overlay?this.options.overlayColor:"transparent";const n=document.createElement("div");n.className="ml-ccl-spinner-stage",n.style.width=this.options.size,n.style.height=this.options.size;const r=document.createElement("div");if(r.className="ml-ccl-spinner",r.style.borderWidth=this.options.borderWidth,r.style.borderTopColor=this.options.color,n.appendChild(r),this.options.showBrand){const l=zs({className:"ml-ccl-spinner-icon",size:"60%"});n.appendChild(l);const c=document.createElement("div");c.className="ml-ccl-message",c.textContent=this.options.message,c.style.display=this.options.message?"block":"none";const h=document.createElement("div");h.className="ml-ccl-wrapper",h.appendChild(n),h.appendChild(c),i.appendChild(h),e.appendChild(i),this.root=i,this.spinner=r,this.messageEl=c;return}const o=document.createElement("div");o.className="ml-ccl-message",o.textContent=this.options.message,o.style.display=this.options.message?"block":"none";const a=document.createElement("div");a.className="ml-ccl-wrapper",a.appendChild(n),a.appendChild(o),i.appendChild(a),e.appendChild(i),this.root=i,this.spinner=r,this.messageEl=o}injectStyles(){if(document.getElementById(lt.styleId)){lt.stylesInjected=!0;return}const e=`
771
922
  .ml-ccl-overlay {
772
923
  position: absolute;
773
924
  inset: 0;
@@ -828,5 +979,5 @@
828
979
  @keyframes ml-ccl-rotate {
829
980
  to { transform: rotate(360deg); }
830
981
  }
831
- `.trim(),t=document.createElement("style");t.id=st.styleId,t.textContent=e,document.head.appendChild(t),st.stylesInjected=!0}};st.styleId="ml-ccl-loader-styles",st.stylesInjected=!1;let Ui=st;class Lf{constructor(e){this._refCount=0,this._message="",this._progress=new Ui({host:e}),this._progress.hide()}show(e){e!==void 0?this._message=e:this._refCount===0&&(this._message=""),this._refCount++,this._refCount===1?(this._progress.setMessage(this._message),this._progress.show(),this.emitEvent(!0)):e!==void 0&&(this._progress.setMessage(e),this.emitEvent(!0))}hide(){this._refCount<=0||(this._refCount--,this._refCount===0&&(this._message="",this._progress.hide(),this.emitEvent(!1)))}setMessage(e){this._message=e,this._refCount>0&&(this._progress.setMessage(e),this.emitEvent(!0))}async withBusyIndicator(e,t){this.show(t);try{return await u.accmYieldForPaint(),await e()}finally{this.hide()}}emitEvent(e){Q.emit("busy-indicator",{visible:e,message:e&&this._message||void 0})}}const Po="Untitled";class lh{constructor(){this._fileName="",this._docTitle="",this._openMode=F.Write,this._hiddenObjects=new Set,this._database=new u.AcDbDatabase,this.docTitle=Po,this._openMode=F.Write}async openUri(e,t){this._uri=e,this._openMode=(t==null?void 0:t.mode)??F.Read,this._fileName=this.getFileNameFromUri(e);const i=this._database.lastOpenError;let n=!0;try{const r={...t,readOnly:this._openMode===F.Read};await this._database.openUri(e,r),this.docTitle=this._fileName}catch{n=!1,this.emitOpenFileFailed(e,i)}return n}async openDocument(e,t,i){var o;let n=!0;this._fileName=e,this._openMode=(i==null?void 0:i.mode)??F.Read;const r=this._database.lastOpenError;try{const a=(o=e.split(".").pop())==null?void 0:o.toLocaleLowerCase(),l={...i,readOnly:this._openMode===F.Read};await this._database.read(t,l,a=="dwg"?u.AcDbFileType.DWG:u.AcDbFileType.DXF),this.docTitle=this._fileName}catch{n=!1,this.emitOpenFileFailed(e,r)}return n}resetNewDocumentIdentity(){this._uri=void 0,this._fileName="",this.docTitle=Po}get uri(){return this._uri}get database(){return this._database}get fileName(){return this._fileName}get docTitle(){return this._docTitle}set docTitle(e){this._docTitle=e}get openMode(){return this._openMode}isObjectHidden(e){return this._hiddenObjects.has(e)}addHiddenObject(e){this._hiddenObjects.add(e)}takeHiddenObjects(){const e=[...this._hiddenObjects];return this._hiddenObjects.clear(),e}get layerService(){return this._layerService||(this._layerService=new te(this._database)),this._layerService}get entityService(){return this._entityService||(this._entityService=new Ir(this._database)),this._entityService}get layerStore(){return this._layerStore||(this._layerStore=new ec(this)),this._layerStore}destroy(){var e;(e=this._layerStore)==null||e.destroy(),this._layerStore=void 0,this._layerService=void 0,this._entityService=void 0,this.clearLayerPreviousState(),this.clearLayerIsoSnapshot(),this._hiddenObjects.clear()}captureLayerPreviousState(){const e=this._database;this._layerPreviousSnapshot={clayer:e.clayer,states:[...e.tables.layerTable.newIterator()].map(t=>({name:t.name,isOn:!t.isOff,isFrozen:t.isFrozen,isLocked:((t.standardFlags??0)&Nt)!==0}))}}getLayerPreviousSnapshot(){return this._layerPreviousSnapshot}clearLayerPreviousState(){this._layerPreviousSnapshot=void 0}setLayerIsoSnapshot(e){this._layerIsoSnapshot=e}consumeLayerIsoSnapshot(){const e=this._layerIsoSnapshot;return this._layerIsoSnapshot=void 0,e}clearLayerIsoSnapshot(){this._layerIsoSnapshot=void 0}restoreLayerPreviousState(){const e=this._layerPreviousSnapshot;return e?K(this._database,H,()=>te.applyLayerPreviousSnapshot(this._database,e)):!1}isolateLayers(e,t){const i=this.layerService.isolateLayers(e,t);if(i)return this._layerIsoSnapshot=i.isoSnapshot,{layerNames:i.layerNames,affectedLayerCount:i.affectedLayerCount}}unisolateLayers(){const e=this.consumeLayerIsoSnapshot();if(e)return this.layerService.unisolateFromSnapshot(e)}emitOpenFileFailed(e,t=null){const i=this._database.lastOpenError,n=i!=null&&i!==t;Q.emit("failed-to-open-file",{fileName:e,...n&&{errorCode:i.code,errorMessage:i.message}})}getFileNameFromUri(e){try{const i=new URL(e).pathname.split("/");return i[i.length-1]||""}catch(t){return u.log.error("Invalid URI:",t),""}}}let Hi=null;function ch(){return Hi?{...Hi}:null}function Tf(s){const e=String(s.type??"").toLowerCase();if(e==="mesh"||e==="ttf"||e==="otf"||e==="woff")return!0;const t=String(s.file??"").toLowerCase();return t.endsWith(".ttf")||t.endsWith(".otf")||t.endsWith(".woff")||t.endsWith(".woff2")}class dh{constructor(){this.deferMeshFonts=!0,this._loadChain=Promise.resolve(),this._loader=new M.AcTrFontLoader}get baseUrl(){return this._loader.baseUrl}set baseUrl(e){this._loader.baseUrl=e}get avaiableFonts(){return this._loader.avaiableFonts}async getAvaiableFonts(){return await this._loader.getAvailableFonts()}async load(e){const t=()=>this.loadInternal(e),i=this._loadChain.then(t,t);return this._loadChain=i.then(()=>{},()=>{}),i}async loadInternal(e){const t=performance.now();let i=[];const n=[],r=[];let o=0,a=0,l=0;try{const c=performance.now(),h=await this._loader.getAvailableFonts();o=performance.now()-c;const p=new Map;for(const w of h)for(const v of w.name)p.set(v.toLowerCase(),w);for(const w of e){const v=w.toLowerCase(),x=p.get(v);this.deferMeshFonts&&x&&Tf(x)?r.push(w):n.push(w)}const m=this.deferMeshFonts&&r.length>0&&n.length>0,g=performance.now();if(i=n.length>0?await this._loader.load(n):[],a=performance.now()-g,r.length>0&&!m){const w=performance.now(),v=await this._loader.load(r);l=performance.now()-w,i=[...i,...v]}else m&&(l=null);const f={fontCount:e.length,criticalFonts:[...n],deferredFonts:[...r],metaMs:o,criticalLoadMs:a,deferredLoadMs:l,deferred:m,totalMs:performance.now()-t};if(Hi=f,m&&r.length>0){const w=performance.now();this._loader.load(r).then(v=>{Hi===f&&(f.deferredLoadMs=performance.now()-w),this.emitPartialFailures(v)},v=>{Hi===f&&(f.deferredLoadMs=performance.now()-w),If(v)})}}catch(c){throw new u.AcDbOpenDatabaseError(c instanceof Error?c.message:String(c),"font_load_failed",{cause:c})}this.emitPartialFailures(i)}emitPartialFailures(e){const t=[],i=[];e.forEach(n=>{n.status==="NotFound"?t.push(n.fontName):n.status==="FailedToLoad"&&i.push({fontName:n.fontName,url:n.url})}),t.length>0&&Q.emit("fonts-not-found",{fonts:t}),i.length>0&&Q.emit("fonts-not-loaded",{fonts:i})}}function If(s){console.warn("[AcApFontLoader] Deferred mesh font load failed; text may use SHX fallbacks.",s)}const uh=[".dxf",".dwg"];let ye,Ps=!1,As={};const Mf=s=>{const e=s.toLowerCase();return uh.some(t=>e.endsWith(t))},Df=s=>new Promise((e,t)=>{const i=new FileReader;i.onload=()=>e(i.result),i.onerror=()=>t(i.error??new Error("Failed to read file")),i.readAsArrayBuffer(s)}),Of=async s=>s?s():{minimumChunkSize:1e3},hh=()=>{ye||(ye=document.createElement("input"),ye.type="file",ye.accept=uh.join(","),ye.style.display="none",ye.addEventListener("change",ph),document.body.appendChild(ye)),ye.click()},ph=async s=>{var n;const e=s.target,t=(n=e.files)==null?void 0:n[0];if(e.value="",!t)return;if(!Mf(t.name)){u.log.warn(`Unsupported file type: ${t.name}`);return}let i=null;try{i=await Df(t);const{AcApDocManager:r}=await Promise.resolve().then(()=>Zf),o=await Of(As.getOpenDocumentDefaults);Q.emit("open-local-file-started",{mode:o.mode??F.Read}),await r.instance.openDocument(t.name,i,o)}catch(r){u.log.error("Failed to open selected file:",r)}finally{i=null}};function mh(s={}){s.enabled!==!1&&(As=s,!Ps&&(Q.on("open-file",hh),Ps=!0))}function yh(s){As=s}function gh(){Ps&&(Q.off("open-file",hh),ye==null||ye.removeEventListener("change",ph),ye==null||ye.remove(),ye=void 0,Ps=!1,As={})}const oi=class oi{constructor(){this._active=!1,this._printToConsole=!1,this._t0=0,this._readEndMs=0,this._stages=new Map,this._activeStageStartedAt=0,this._finishScheduled=!1}static getLastSnapshot(){return oi._lastSnapshot}static isEnabled(e){try{return u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.OPENPROF,e)===!0}catch{return!1}}begin(e){this.cancel(),this._active=!0,this._printToConsole=oi.isEnabled(e),this._finishScheduled=!1,this._t0=performance.now(),this._readEndMs=0,this._stages.clear(),this._activeStage=void 0,this._activeStageStartedAt=0,this._database=e,u.AcDbRenderingCache.resetProfile(),u.AcDbRenderingCache.profiling=!0,this._progressListener=t=>{this.onProgress(t)},e.events.openProgress.addEventListener(this._progressListener)}markReadCompleteAndScheduleReport(e){this._active&&(this._readEndMs=performance.now(),this.scheduleReport(e))}cancel(){this.detachProgressListener(),this._active&&(u.AcDbRenderingCache.profiling=!1),this._active=!1,this._printToConsole=!1,this._finishScheduled=!1,this._database=void 0,this._activeStage=void 0,this._stages.clear()}onProgress(e){const t=String(e.subStage??e.stage??"UNKNOWN"),i=performance.now();if(this._activeStage==null){this._activeStage=t,this._activeStageStartedAt=i;return}t!==this._activeStage&&(this.closeActiveStage(i),this._activeStage=t,this._activeStageStartedAt=i)}closeActiveStage(e){if(this._activeStage==null)return;let t=this._stages.get(this._activeStage);t||(t={durationMs:0},this._stages.set(this._activeStage,t)),t.durationMs+=Math.max(0,e-this._activeStageStartedAt),this._activeStage=void 0}scheduleReport(e){!this._active||this._finishScheduled||(this._finishScheduled=!0,this.waitForIdle(e).then(()=>{this._active&&(this.publishReport(performance.now(),e),this.cancel())}).catch(t=>{u.log.warn("OPENPROF: failed to finish open profile",t),this.cancel()}))}async waitForIdle(e){await Promise.resolve(),e.isProcessingEntities&&await new Promise(t=>{const i=()=>{if(!e.isProcessingEntities){t();return}setTimeout(i,16)};i()})}publishReport(e,t){var P,A,_;this.closeActiveStage(this._readEndMs>0?this._readEndMs:e);const i=Math.max(0,this._readEndMs-this._t0),n=Math.max(0,e-this._readEndMs),r=Math.max(0,e-this._t0),o=((P=this._stages.get("PARSE"))==null?void 0:P.durationMs)??0,a=((A=this._stages.get("ENTITY"))==null?void 0:A.durationMs)??0,l={...u.AcDbRenderingCache.profileStats},c=l.topLevel,h=t.progressiveOpenStats,p=t.progressiveRendering,m=[...l.blockMisses].sort((C,O)=>O.buildMs+O.compactMs-(C.buildMs+C.compactMs)).slice(0,10).map(C=>({blockName:C.blockName,buildMs:C.buildMs,compactMs:C.compactMs})),g=[...this._stages.entries()].filter(([,C])=>C.durationMs>0).sort((C,O)=>O[1].durationMs-C[1].durationMs).map(([C,O])=>({name:C,durationMs:O.durationMs})),f={collectedAt:Date.now(),fileName:(_=this._database)==null?void 0:_.dwgname,totalMs:r,readMs:i,convertMs:n,parseMs:o,entityMs:a,stages:g,cache:{hits:l.hits,misses:l.misses,hitMs:l.hitMs,cloneMs:l.cloneMs,missBuildMs:l.missBuildMs,missCompactMs:l.missCompactMs,setCloneMs:l.setCloneMs,applyMs:l.applyMs,topLevel:{...c}},slowBlocks:m,progressive:{enabled:p,paintCount:h.paintCount,yieldCount:h.yieldCount}};if(oi._lastSnapshot=f,!this._printToConsole)return;const w=(C,O)=>O<=0?"0%":`${(C/O*100).toFixed(1)}%`,v=["","========== OPENPROF (open-file profile) ==========","Note: progress-bar % weights (PARSE~12%, ENTITY~98%) are not wall-time shares.","Stage ms = active-stage wall time (first event of stage → first event of next stage).",`progressive: ${p?"on":"off"} (mid-open paints=${h.paintCount}, yields=${h.yieldCount})`,`wall clock total: ${r.toFixed(0)} ms`,` db.read: ${i.toFixed(0)} ms (${w(i,r)})`,` PARSE: ${o.toFixed(0)} ms (${w(o,i)} of read)`,` ENTITY flush: ${a.toFixed(0)} ms (${w(a,i)} of read)`,` scene convert: ${n.toFixed(0)} ms (${w(n,r)})`],x=ch();if(x&&v.push(` explicit font load: critical=${x.criticalLoadMs.toFixed(0)}ms meta=${x.metaMs.toFixed(0)}ms deferredMesh=${x.deferred?"yes":"no"} (critical=[${x.criticalFonts.join(",")}] deferred=[${x.deferredFonts.join(",")}])`),v.push("","--- AcDbRenderingCache (top-level INSERT draws) ---",`hits: ${c.hits}, hit path ${c.hitMs.toFixed(0)} ms (clone ${c.cloneMs.toFixed(0)} ms)`,`misses: ${c.misses}, build ${c.missBuildMs.toFixed(0)} ms (incl. nested), compact ${c.missCompactMs.toFixed(0)} ms, set/clone ${c.setCloneMs.toFixed(0)} ms`,`applyMatrix+attribs: ${c.applyMs.toFixed(0)} ms`,"",`--- AcDbRenderingCache (all depths: hits=${l.hits}, misses=${l.misses}) ---`,`hit ${l.hitMs.toFixed(0)} ms (clone ${l.cloneMs.toFixed(0)}), build ${l.missBuildMs.toFixed(0)}, compact ${l.missCompactMs.toFixed(0)}, set ${l.setCloneMs.toFixed(0)}, apply ${l.applyMs.toFixed(0)}`),m.length>0){v.push("","--- Slowest block template misses (build+compact) ---");for(const C of m){const O=C.blockName.length>40?`${C.blockName.slice(0,37)}...`:C.blockName;v.push(`${O.padEnd(40)} build=${C.buildMs.toFixed(0).padStart(7)}ms compact=${C.compactMs.toFixed(0).padStart(7)}ms total=${(C.buildMs+C.compactMs).toFixed(0).padStart(7)}ms`)}}const S=g.filter(C=>!["PARSE","FONT","ENTITY","START","END"].includes(C.name));if(S.length>0){v.push("","--- Other openProgress sub-stages ---");for(const C of S)v.push(` ${C.name}: ${C.durationMs.toFixed(0)} ms`)}v.push("==================================================",""),console.log(v.join(`
832
- `));try{const C=u.AcCmPerformanceCollector.getInstance();C.getAll().length>0&&(console.log("--- AcCmPerformanceCollector ---"),C.printAll())}catch{}}detachProgressListener(){this._progressListener&&this._database&&this._database.events.openProgress.removeEventListener(this._progressListener),this._progressListener=void 0}};oi._lastSnapshot=null;let Cs=oi;function fh(s){return s.percentage<100?!1:s.subStageStatus==="ERROR"?!0:s.subStageStatus!=="END"?!1:s.stage==="FETCH_FILE"||s.subStage==="END"}const rt=class rt{constructor(e){this._peak=0,this._overlayVisible=!1,this._lastMessage="",this._seeThrough=!1,this._progress=new Ui({host:e,overlayColor:rt.OVERLAY_DEFAULT}),this._progress.hide()}setSeeThroughOverlay(e){this._seeThrough=e,this._progress.setOverlayColor(e?rt.OVERLAY_SEE_THROUGH:rt.OVERLAY_DEFAULT)}setSceneBusyGate(e){this._sceneBusyGate=e}reset(){this.clearHoldPoll(),this._peak=0,this._stage=void 0,this._overlayVisible=!1,this._lastMessage=""}async beginOpen(e){this.handle({database:e,percentage:0,stage:"CONVERSION",subStage:"START",subStageStatus:"START"}),await u.accmYieldForPaint()}handle(e){const t=this.normalize(e);return Q.emit("open-file-progress",t),this.updateOverlay(t),t}normalize(e){const t=e.stage;return t!==this._stage&&(this._stage==="FETCH_FILE"&&t==="CONVERSION"&&(this._peak=0),this._stage=t),this._peak=Math.max(this._peak,e.percentage),{...e,percentage:this._peak}}resolveMessage(e){if(e.stage==="CONVERSION"){if(e.subStage){const t="main.progress."+e.subStage.replace(/_/g,"").toLowerCase();return d.t(t)}return}if(e.stage==="FETCH_FILE")return d.t("main.message.fetchingDrawingFile")}updateOverlay(e){var i;if(fh(e)){if((i=this._sceneBusyGate)!=null&&i.call(this)){this.holdUntilSceneIdle();return}this.hideAndReset();return}this.clearHoldPoll(),this._overlayVisible||(this._progress.show(),this._overlayVisible=!0,this._seeThrough&&this._progress.setOverlayColor(rt.OVERLAY_SEE_THROUGH));const t=this.resolveMessage(e);t!=null&&t!==this._lastMessage&&(this._progress.setMessage(t),this._lastMessage=t)}holdUntilSceneIdle(){this._overlayVisible||(this._progress.show(),this._overlayVisible=!0),this._progress.setOverlayColor(rt.OVERLAY_SEE_THROUGH);const e=d.t("main.progress.rendering");if(e!==this._lastMessage&&(this._progress.setMessage(e),this._lastMessage=e),this._holdPollId!=null)return;const t=()=>{var i;if((i=this._sceneBusyGate)!=null&&i.call(this)){this._holdPollId=setTimeout(t,50);return}this._holdPollId=void 0,this.hideAndReset()};this._holdPollId=setTimeout(t,50)}hideAndReset(){this.clearHoldPoll(),this._progress.hide(),this.reset()}clearHoldPoll(){this._holdPollId!=null&&(clearTimeout(this._holdPollId),this._holdPollId=void 0)}};rt.OVERLAY_DEFAULT="rgba(0,0,0,0.45)",rt.OVERLAY_SEE_THROUGH="rgba(0,0,0,0.16)";let Ao=rt;const jf="libredwg-parser-worker.js",Bf="libredwg-web.wasm",bh="mtext-renderer-worker.js",Ff="dwg-parser-worker.js",zf="dwg-parser-main.js",Nf="@mlightcad/libredwg-converter",Rf="@mlightcad/mtext-renderer",Vf="@mlight-cad/dwg-converter",wh={mtextRender:`./assets/${bh}`};function Gf(s){const e=[(s==null?void 0:s.mtextRender)??wh.mtextRender];return s!=null&&s.dwgParser&&e.push(s.dwgParser),e.map(t=>String(t))}let Co,_o;function Kf(){Co=void 0,_o=void 0}async function Uf(s){try{const e=await fetch(s,{method:"HEAD"});if(e.ok)return!0;if(e.status===405){const t=await fetch(s,{headers:{Range:"bytes=0-0"}});return t.ok||t.status===206}return!1}catch{return!1}}async function vh(s){const e=Gf(s),t=e.join("|");if(Co===t&&_o===!0)return!0;try{const n=(await Promise.all(e.map(Uf))).every(Boolean);return n&&(Co=t,_o=!0),n}catch{return!1}}class It{constructor(){this._sessions=new Map,this._nextId=1}static get instance(){return this._instance||(this._instance=new It),this._instance}get sessions(){return Array.from(this._sessions.values())}getSession(e){return this._sessions.get(e)}getSessionByBlockName(e){for(const t of this._sessions.values())if(t.blockName===e)return t}async attachOverlay(e){const t=this.getSessionByBlockName(e.blockName);t&&this.unload(t.id);let i;if(e.sourceDb)i=await k.instance.registerOverlayDatabase(e.sourceDb);else if(e.content)i=await k.instance.loadOverlay(e.fileName,e.content);else throw new Error("AcApXrefManager.attachOverlay requires sourceDb or content");const n=k.instance.getOverlayLayout(i);n&&e.transform&&Hf(n,e.transform);const r={id:`xref-${this._nextId++}`,blockName:e.blockName,insertId:e.insertId,overlayId:i,sourcePath:e.sourcePath,visible:!0};return this._sessions.set(r.id,r),r}setVisible(e,t){const i=this._sessions.get(e);if(!i)return!1;const n=k.instance.setOverlayVisible(i.overlayId,t);return n&&(i.visible=t),n}setVisibleByBlockName(e,t){const i=this.getSessionByBlockName(e);return i?this.setVisible(i.id,t):!1}unload(e){const t=this._sessions.get(e);return t?(k.instance.removeOverlay(t.overlayId),this._sessions.delete(e),!0):!1}unloadByBlockName(e){const t=this.getSessionByBlockName(e);return t?this.unload(t.id):!1}clearAll(){for(const e of[...this._sessions.keys()])this.unload(e)}static createHostXrefInsert(e,t,i,n,r){const o=new u.AcDbBlockTableRecord({name:t,pathName:i,flags:u.AcDbBlockTableRecordFlag.Xref|u.AcDbBlockTableRecordFlag.Resolved|u.AcDbBlockTableRecordFlag.Referenced,...r?{origin:new u.AcGePoint3d(r)}:{}});e.tables.blockTable.add(o);const a=new u.AcDbBlockReference(t);return a.position=new u.AcGePoint3d(n.position),a.scaleFactors=new u.AcGePoint3d(n.scale,n.scale,n.scale),a.rotation=n.rotationRad,e.tables.blockTable.modelSpace.appendEntity(a),{record:o,insert:a}}}function Hf(s,e){const t=s.internalObject;t.position.set(e.position.x,e.position.y,e.position.z??0),t.scale.set(e.scale,e.scale,e.scale),t.rotation.set(0,0,e.rotationRad)}var Wi=(s=>(s.Extents="extents",s.Saved="saved",s))(Wi||{});const Wf="https://cdn.jsdelivr.net/gh/mlightcad/cad-data",$f="templates/acadiso.dxf",Yf={ARC:["A"],CIRCLE:["C"],ELLIPSE:["EL"],ERASE:["E"],DIMLINEAR:["DLI"],MEASUREDISTANCE:["DI","DIST"],MEASUREAREA:["AA","AREA"],MEASUREANGLE:["ANG"],"-HATCH":["-H"],IMAGEATTACH:["IAT"],"-INSERT":["I"],XATTACH:["XA"],LAYER:["LA"],"-LAYER":["-LA"],LINE:["L"],MLINE:["ML"],MTEXT:["T"],MOVE:["M"],OFFSET:["O"],COPY:["CO"],ROTATE:["RO"],OPEN:["OP"],PAN:["P"],POINT:["PO"],POLYGON:["POL"],PLINE:["PL"],RAY:["RA"],RECTANG:["REC"],REGEN:["RE"],SELECT:["SE"],SPLINE:["SPL"],XLINE:["XL"],ZOOM:["Z"],UNDO:["U"],REDO:["REDO"]},kh="modern";class k{constructor(e={}){var l;this._openFileProfiler=new Cs,this._workersReady=null,this._overlays=new Map,this._nextOverlayId=1,this.events={documentToBeOpened:new u.AcCmEventManager,documentCreated:new u.AcCmEventManager,documentActivated:new u.AcCmEventManager,workersReady:new u.AcCmEventManager},this._baseUrl=e.baseUrl??Wf,this._commandAliasOverrides=this.normalizeCommandAliasConfig(e.commandAliases),this._openDocumentDefaults=e.openDocumentDefaults,e.useMainThreadDraw?M.AcTrMTextRenderer.getInstance().setRenderMode("main"):M.AcTrMTextRenderer.getInstance().setRenderMode("worker"),D.FontManager.instance.setDefaultFonts(kh),D.FontManager.instance.lazyFontLoading=!0,D.FontManager.instance.awaitFontsBeforeDraw=!0,M.AcTrMTextRenderer.getInstance().setLazyFontLoading(!0),M.AcTrMTextRenderer.getInstance().setAwaitFontsBeforeDraw(!0);const t=new lh,i=((l=e.container)==null?void 0:l.getBoundingClientRect())??{width:300,height:150},n=()=>{var c;if(e.autoResize){const h=e.container;if(h)return{width:Math.max(1,Math.floor(h.clientWidth)),height:Math.max(1,Math.floor(h.clientHeight))};const p=(c=e.container)==null?void 0:c.getBoundingClientRect();return{width:Math.max(1,Math.floor((p==null?void 0:p.width)??i.width)),height:Math.max(1,Math.floor((p==null?void 0:p.height)??i.height))}}else return{width:e.width??i.width,height:e.height??i.height}},r=new Yi({container:e.container,calculateSizeCallback:n});this._context=new Mh(r,t),this._drawStyleToolbar=new oh(r),this._fontLoader=new dh;const o=this.resolveFontsBaseUrl();this._fontLoader.baseUrl=o,D.FontManager.instance.baseUrl=o,u.acdbHostApplicationServices().workingDatabase=t.database,this._commandManager=new ce,this.registerCommands(),this._pluginManager=new Xu(this._context,this._commandManager);const a=e.busyIndicatorHost??r.container;this._openFileProgress=new Ao(a),this._openFileProgress.setSceneBusyGate(()=>this.curView.isProcessingEntities),this._busyIndicator=new Lf(a),hl({showMessage:(c,h,p)=>this.editor.showMessage(c,h,p),showBusyIndicator:c=>this.showBusyIndicator(c),hideBusyIndicator:()=>this.hideBusyIndicator(),withBusyIndicator:(c,h)=>this.withBusyIndicator(c,h)}),this.events.documentToBeOpened.addEventListener(()=>{this._openFileProgress.reset()}),t.database.events.openProgress.addEventListener(c=>{this._openFileProgress.handle({database:t.database,percentage:c.percentage,stage:c.stage,subStage:c.subStage,subStageStatus:c.subStageStatus,data:c.data}),c.subStage==="HEADER"&&(this.curView.ltscale=t.database.ltscale,this.curView.celtscale=t.database.celtscale,this.curView.renderer.showLineWeight=t.database.lwdisplay)}),e.preloadDefaultFonts&&this.loadDefaultFonts(),this._webworkerFileUrls=e.webworkerFileUrls,this.registerWorkers(e.webworkerFileUrls),e.checkWorkersOnInit&&this.areWorkersReady(),this.loadPlugins(e.plugins).catch(c=>{u.log.error("[AcApDocManager] Error loading plugins:",c)}),mh({enabled:e.builtinOpenFileDialog!==!1,getOpenDocumentDefaults:()=>this.resolveOpenDocumentDefaults()})}static createInstance(e={}){return k._instance==null&&(k._instance=new k(e)),this._instance}static checkWebworkerReadiness(e){return vh(e)}static get instance(){if(!k._instance)throw new Error("AcApDocManager instance is not created yet!");return k._instance}async destroy(){await this._pluginManager.unloadAllPlugins(),this.context.doc.destroy(),gh(),M.AcTrMTextRenderer.resetInstance(),Kf(),k._instance=void 0}get workersReady(){return this._workersReady}areWorkersReady(){return this._workersReady===!0?Promise.resolve(!0):(this._workersReadyCheckPromise||(this._workersReadyCheckPromise=vh(this._webworkerFileUrls).then(e=>(this._workersReady=e,this._workersReadyCheckPromise=void 0,this.events.workersReady.dispatch({ready:e}),e)).catch(()=>(this._workersReady=!1,this._workersReadyCheckPromise=void 0,this.events.workersReady.dispatch({ready:!1}),!1))),this._workersReadyCheckPromise)}get context(){return this._context}get curDocument(){return this._context.doc}get mdiActiveDocument(){return this._context.doc}get curView(){return this._context.view}get editor(){return this._context.view.editor}get commandManager(){return this._commandManager}get pluginManager(){return this._pluginManager}get drawStyleToolbar(){return this._drawStyleToolbar}get baseUrl(){return this._baseUrl}resolveColors(){const e=this.curDocument.database,t=e.tables.layerTable.getAt(e.clayer),i=this.resolveColorToRgb(t==null?void 0:t.color);let n=e.cecolor;return n!=null&&n.isByLayer&&(n=t==null?void 0:t.color),{entityColor:this.resolveColorToRgb(n),layerColor:i}}resolveColorToRgb(e){return!e||e.isByLayer||e.isByBlock||e.isByACI&&e.colorIndex===7?this.resolveAci7ForBackground():e.RGB??this.resolveAci7ForBackground()}resolveAci7ForBackground(){return this.curView.backgroundColor===16777215?0:16777215}get avaiableFonts(){return this._fontLoader.avaiableFonts}async loadFonts(e){await this._fontLoader.load(e)}async loadDefaultFonts(e){e==null?await this._fontLoader.load([...D.FontManager.instance.getFontsToLoad()]):await this._fontLoader.load(e)}async openUrl(e,t){t=this.setOptions(t),this.onBeforeOpenDocument(t);try{await this._openFileProgress.beginOpen(this.context.doc.database);const i=await this.context.doc.openUri(e,t);return this.onAfterOpenDocument(i,t),i}catch(i){throw this._openFileProfiler.cancel(),i}}async openDocument(e,t,i){i=this.setOptions(i),this.onBeforeOpenDocument(i);try{await this._openFileProgress.beginOpen(this.context.doc.database);const n=await this.context.doc.openDocument(e,t,i);return this.onAfterOpenDocument(n,i),n}catch(n){throw this._openFileProfiler.cancel(),n}}async loadOverlay(e,t,i={}){var o;const n=new u.AcDbDatabase,r=(o=e.split(".").pop())==null?void 0:o.toLocaleLowerCase();return await Qr(n,async()=>{await n.read(t,{readOnly:!0,...i},r==="dwg"?u.AcDbFileType.DWG:u.AcDbFileType.DXF)}),this.registerOverlayDatabase(n)}async registerOverlayDatabase(e){const t=this.curView,i=await t.addOverlayEntities(e),n=`overlay-${this._nextOverlayId++}`;return this._overlays.set(n,{db:e,layout:i}),t.isDirty=!0,n}removeOverlay(e){const t=this._overlays.get(e);if(!t)return!1;const i=this.curView;return i.cadScene.internalScene.remove(t.layout.internalObject),t.layout.clear(),this._overlays.delete(e),i.isDirty=!0,!0}setOverlayVisible(e,t){const i=this._overlays.get(e);return i?(i.layout.visible=t,this.curView.isDirty=!0,!0):!1}clearOverlays(){for(const e of[...this._overlays.keys()])this.removeOverlay(e)}get overlayIds(){return Array.from(this._overlays.keys())}getOverlayLayout(e){var t;return(t=this._overlays.get(e))==null?void 0:t.layout}async newDocument(e){const i=`${this.baseUrl.endsWith("/")?this.baseUrl:`${this.baseUrl}/`}${$f}`,n=this.setOptions({...e,mode:F.Write});this.onBeforeOpenDocument(n),await this._openFileProgress.beginOpen(this.context.doc.database);const r=await this.context.doc.openUri(i,n);return r&&this.context.doc.resetNewDocumentIdentity(),this.onAfterOpenDocument(r,n),r}setOpenDocumentDefaults(e){this._openDocumentDefaults=e,yh({enabled:!0,getOpenDocumentDefaults:()=>this.resolveOpenDocumentDefaults()})}resolveOpenDocumentDefaults(){const e=this._openDocumentDefaults;return e==null?{minimumChunkSize:1e3}:typeof e=="function"?e():e}regen(){this.curView.clear(),this.context.doc.database.regen()}resolveFontsBaseUrl(){return`${this._baseUrl.endsWith("/")?this._baseUrl:`${this._baseUrl}/`}fonts/`}lookupLocalCmd(e){return this._commandManager.lookupLocalCmd(e,this.curDocument.openMode)}lookupGlobalCmd(e){return this._commandManager.lookupGlobalCmd(e,this.curDocument.openMode)}searchCommandsByPrefix(e){return this._commandManager.searchCommandsByPrefix(e,this.curDocument.openMode)}registerCommands(){const e=this._commandManager,t=(n,r,o)=>{const a=Yf[n.toUpperCase()]??[];e.addCommand(ce.SYSTEMT_COMMAND_GROUP_NAME,n,r,o,this.resolveCommandAliases(n,a))};t("about","about",new Ou),t("arc","arc",new bc),t("cachefont","cachefont",new Ki),t("circle","circle",new Pc),t("cdxf","cdxf",new $l),t("pngout","pngout",new Xl),t("entout","entout",new Ql),t("ellipse","ellipse",new Tc),t("erase","erase",new _u),t("hideobjects","hideobjects",new Eu),t("dimlinear","dimlinear",new Cc),t("measuredistance","measuredistance",new jd),t("measurearea","measurearea",new Ld),t("measureangle","measureangle",new _d),t("measurearc","measurearc",new Md),t("measurepoint","measurepoint",new Fd),t("clearmeasurements","clearmeasurements",new hd),t("measurementvis","measurementvis",new pd),t("measurementexport","measurementexport",new Pd),t("measurementimport","measurementimport",new Ad),t("-hatch","-hatch",new Xn),t("imageattach","imageattach",new Ic),t("-insert","-insert",new Dc),t("xattach","xattach",new cd),t("-layer","-layer",new hc),t("laycur","laycur",new sc),t("laydel","laydel",new nc),t("layfrz","layfrz",new Vn),t("layiso","layiso",new Gn),t("laylck","laylck",new rc),t("layon","layon",new oc),t("layoff","layoff",new Kn),t("laythw","laythw",new lc),t("layuniso","layuniso",new cc),t("layulk","layulk",new dc),t("layerp","layerp",new ac),t("layerclose","layerclose",new uc),t("line","line",new St),t("mline","mline",new jc),t("mtext","mtext",new Bc),t("copy","copy",new ws),t("move","move",new Tu),t("offset","offset",new Vi),t("rotate","rotate",new ks),t("log","log",new ju),t("open","open",new Vu),t("pan","pan",new Zu),t("point","point",new Fc),t("polygon","polygon",new Qn),t("pline","pline",new Vc),t("qnew","qnew",new Gu),t("ray","ray",new Kc),t("rectang","rectang",new es),t("regen","regen",new Ku),t("revcloud","revcloud",new ts),t("markuptext","markuptext",new Pu),t("markupline","markupline",new vu),t("markuparrow","markuparrow",new cu),t("markupcloud","markupcloud",new hu),t("markuprect","markuprect",new ku),t("markupcircle","markupcircle",new uu),t("markuphighlight","markuphighlight",new pu),t("markupcallout","markupcallout",new du),t("markupstamp","markupstamp",new Su),t("markupvis","markupvis",new Cu),t("clearmarkups","clearmarkups",new lu),t("markupexport","markupexport",new bu),t("markupimport","markupimport",new wu),t("select","select",new Uu),t("sketch","sketch",new rs),t("spline","spline",new rd),t("switchbg","switchbg",new Wu),t("unisolateobjects","unisolateobjects",new Du),t("xline","xline",new dd),t("undo","undo",new $u),t("redo","redo",new Yu),t("zoom","zoom",new Tt),u.AcDbSysVarManager.instance().getAllDescriptors().forEach(n=>{e.addCommand(ce.SYSTEMT_COMMAND_GROUP_NAME,n.name,n.name,new Hu,this.resolveCommandAliases(n.name,[]))})}normalizeCommandAliasConfig(e){const t=new Map;return e&&Object.entries(e).forEach(([i,n])=>{const r=i.trim().toUpperCase();if(!r)return;const o=Array.isArray(n)?n:[n],a=new Set;o.forEach(l=>{const c=l.trim().toUpperCase();c&&c!==r&&a.add(c)}),t.set(r,[...a])}),t}resolveCommandAliases(e,t){const i=e.trim().toUpperCase(),n=this._commandAliasOverrides.get(i);if(n)return[...n];const r=new Set;return t.forEach(o=>{const a=o.trim().toUpperCase();a&&a!==i&&r.add(a)}),[...r]}sendStringToExecute(e){this.executeCommandString(e).catch(t=>{const i=t instanceof Error?t.message:String(t);this.editor.showMessage(i,"error"),u.log.error(`[AcApDocManager] Command failed: ${e}`,t)})}async executeCommandString(e){const t=this.splitCommandScript(e);if(!t.length)throw new Error("Command string is empty");const[i,...n]=t;this.editor.clearScriptInputs(),this.editor.enqueueScriptInputs(n),await this.executeNamedCommand(i,{preserveScriptInputs:!1})}async runScript(e){const t=So(e);for(this.editor.clearScriptInputs(),this.editor.enqueueScriptInputs(t);this.editor.hasScriptInputs();){const i=this.consumeNextScriptCommandName();if(i==null)break;if(ah(i)){this.editor.clearScriptInputs();break}await this.executeNamedCommand(i,{preserveScriptInputs:!0})}}async executeNamedCommand(e,t){const i=this.context.doc.openMode;let n=this._commandManager.lookupGlobalCmd(e)??this._commandManager.lookupLocalCmd(e,i);if(n||await this._pluginManager.loadByTrigger(e)&&(n=this._commandManager.lookupGlobalCmd(e)??this._commandManager.lookupLocalCmd(e,i)),!n)throw new Error(`Command '${e}' not found`);if(i<n.mode)throw new Error(`Command '${e}' requires mode '${F[n.mode]}' but document is in mode '${F[i]}'!`);await this._commandManager.cancelActive();const r=n.trigger(this.context).finally(()=>{t.preserveScriptInputs||this.editor.clearScriptInputs(),this._commandManager.clearActive(n)});this._commandManager.markActive(n,this.curView,r),await r}consumeNextScriptCommandName(){for(;this.editor.hasScriptInputs();){const e=this.editor.consumeScriptInput();if(e==null)return;const t=e.trim();if(t)return t}}splitCommandScript(e){const t=So(e);if(!t.length)return[];let i=0;for(;i<t.length&&!t[i].trim();)i++;return i>=t.length?[]:[t[i].trim(),...t.slice(i+1)]}setActiveLayout(){const e=this.curView,t=this.curDocument.database;e.activeLayoutBtrId=t.currentSpaceId,e.modelSpaceBtrId=t.tables.blockTable.modelSpace.objectId}onBeforeOpenDocument(e){this.events.documentToBeOpened.dispatch({doc:this.context.doc,mode:this.getDocumentEventMode(e)}),It.instance.clearAll(),this.clearOverlays(),this.curView.bindDrawDatabase(this.context.doc.database),this.curView.progressiveRendering=(e==null?void 0:e.progressiveRendering)??!1,this._openFileProgress.setSeeThroughOverlay((e==null?void 0:e.progressiveRendering)??!1),da(),au(),this.curView.clear(),this._openFileProfiler.begin(this.context.doc.database)}onAfterOpenDocument(e,t){const i=!e&&this.hasRecoverablePartialContent();if(e||i){this.context.doc.destroy();const n=this.context.doc;this.events.documentActivated.dispatch({doc:n,mode:this.getDocumentEventMode(t)}),this.setActiveLayout(),this.curView.syncDisplaySysVars(n.database);const r=n.database,o=r.tables.blockTable.modelSpace.objectId,a=r.currentSpaceId!==o,l=u.acdbHostApplicationServices().layoutManager.getActiveLayout(r),c=l==null?void 0:l.limits,h=this.resolveOpenViewMode(t),p=this.curView,m=(t==null?void 0:t.progressiveRendering)??!1;if(a&&c&&!c.isEmpty())p.zoomTo(c);else if(h===Wi.Extents)m&&p.beginProgressiveOpenFit(),p.zoomToFitDrawing();else if(a)m&&p.beginProgressiveOpenFit(),p.zoomToFitDrawing();else{const g=p.width/Math.max(p.height,1),f=r.tables.viewportTable.getActiveVport(),w=f==null?void 0:f.modelViewBox(g);w?p.zoomTo(w):this.hasUsableDrawingExtents(r)?p.zoomTo(new u.AcGeBox2d(r.extmin,r.extmax)):(m&&p.beginProgressiveOpenFit(),p.zoomToFitDrawing())}this.curView.markLayoutAsInitialized(r.currentSpaceId),this._openFileProfiler.markReadCompleteAndScheduleReport(p)}else this._openFileProfiler.cancel(),this.curView.endProgressiveOpenFit(),this.regen()}hasUsableDrawingExtents(e){if(e.extents.isEmpty())return!1;const t=1e15,i=[e.extmin.x,e.extmin.y,e.extmax.x,e.extmax.y];return i.some(n=>!Number.isFinite(n))||i.some(n=>Math.abs(n)>=t)?!1:e.extmax.x>e.extmin.x&&e.extmax.y>e.extmin.y}hasRecoverablePartialContent(){const e=this.context.doc.database,t=e.tables.blockTable.modelSpace;return t?t.newIterator().count>0:!e.extents.isEmpty()}setOptions(e){return e==null?e={drawNoPlotLayers:!1,progressiveRendering:!1}:(this.stripObsoleteFontOpenOptions(e),e.drawNoPlotLayers==null&&(e.drawNoPlotLayers=!1),e.progressiveRendering==null&&(e.progressiveRendering=!1)),e}stripObsoleteFontOpenOptions(e){const t=e,i=t.fontLoader!=null,n=t.failOnFontLoadError!=null;!i&&!n||(delete t.fontLoader,delete t.failOnFontLoadError,console.warn("[AcApDocManager] Ignoring obsolete open options "+[i?"fontLoader":null,n?"failOnFontLoadError":null].filter(Boolean).join(", ")+"; fonts load on demand via FontManager.lazyFontLoading."))}getDocumentEventMode(e){return(e==null?void 0:e.mode)??F.Read}resolveOpenViewMode(e){return(e==null?void 0:e.openViewMode)!=null?e.openViewMode:this.getDocumentEventMode(e)===F.Write?Wi.Saved:Wi.Extents}showBusyIndicator(e){this._busyIndicator.show(e)}hideBusyIndicator(){this._busyIndicator.hide()}setBusyIndicatorMessage(e){this._busyIndicator.setMessage(e)}async withBusyIndicator(e,t){return this._busyIndicator.withBusyIndicator(e,t)}registerWorkers(e){const t=M.AcTrMTextRenderer.getInstance();t.initialize((e==null?void 0:e.mtextRender)??wh.mtextRender),t.setDefaultFonts(kh)}async loadPlugins(e){if(e){if(e.fromConfig&&e.fromConfig.length>0)try{const t=await this._pluginManager.loadPluginsFromConfig(e.fromConfig,{continueOnError:!0});t.loaded.length>0&&u.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from config:`,t.loaded),t.failed.length>0&&u.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s):`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){u.log.error("[AcApDocManager] Error loading plugins from config:",t)}if(e.fromFolder)try{const t=await this._pluginManager.loadPluginsFromFolder(e.fromFolder.folderPath,{pluginList:e.fromFolder.pluginList,continueOnError:e.fromFolder.continueOnError??!0});t.loaded.length>0&&u.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from folder:`,t.loaded),t.failed.length>0&&u.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s) from folder:`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){u.log.error("[AcApDocManager] Error loading plugins from folder:",t)}}}}const Zf=Object.freeze(Object.defineProperty({__proto__:null,AcApDocManager:k},Symbol.toStringTag,{value:"Module"}));class $i{static isFontLoaded(e){return D.FontManager.instance.isFontLoaded(e)}static getFontType(e){return D.FontManager.instance.getFontType(e)}static getReplacementFontName(e){return D.FontManager.instance.findAndReplaceFont(e)}static getShxCodePoints(e){var r;const t=D.FontManager.instance.getFontByName(e,!1);if(!t||t.type!=="shx")return[];const i=t.data;return Object.keys(((r=i.content)==null?void 0:r.data)??{}).map(o=>Number(o)).filter(o=>Number.isFinite(o)).sort((o,a)=>o-a)}static getLoadedShxFontData(e){const t=D.FontManager.instance.getFontByName(e,!1);if(!(!t||t.type!=="shx"))return t.data}static createShxParserFont(e){return new D.ShxParserFont(e)}static findFontInfoByName(e){var n;const t=((n=k.instance)==null?void 0:n.avaiableFonts)??[],i=e.trim().toLowerCase();if(i)return t.find(r=>r.name.some(o=>o.trim().toLowerCase()===i))}static getCatalogFontType(e){var t;return(t=$i.findFontInfoByName(e))==null?void 0:t.type}static async ensureDrawingFontLoaded(e){const t=k.instance;t&&($i.isFontLoaded(e)||await t.loadFonts([e]))}static async cacheFont(e,t,i,n){return D.FontManager.instance.cacheFont(e,t,i,n)}}const xh=s=>new u.AcGeBox3d(s.min,s.max),Sh=s=>new u.AcGeBox2d(s.min,s.max),Ph=s=>new T.Box3(s.min,s.max),Ah=s=>new u.AcGeBox2d(s.min,s.max),Ch=s=>new T.Box2(s.min,s.max),_h=s=>new u.AcGeBox2d(s.min,s.max),Eh=s=>{const e=new T.Box3;return e.min.set(s.min.x,s.min.y,0),e.max.set(s.max.x,s.max.y,0),e},Eo={threeBo2dToGeBox2d:Ah,geBox2dToThreeBox2d:Ch,threeBox3dToGeBox3d:xh,geBox3dToThreeBox3d:Ph,goBox3dToGeBox2d:Sh,threeBox3dToGeBox2d:_h,geBox2dToThreeBox3d:Eh};class Xf{constructor(e){this.getLayerInfo=e}shouldConvert(e){if(!e.visibility)return!1;const t=this.getLayerInfo(e.layer);return t?this.isBlockReference(e)?!t.isFrozen:Kt.isLayerVisible(t):!0}shouldConvertForExport(e,t=!0){return e.visibility?t?!0:this.shouldConvert(e):!1}layerVisibilityMayHaveChanged(e){return e.isOff!==void 0||e.standardFlags!==void 0}collectMissingEntitiesOnLayer(e,t,i){return this.collectMissingEntities(t,i,n=>n.layer===e&&this.shouldConvert(n))}collectMissingEntitiesForExport(e,t,i=!0){return this.collectMissingEntities(e,t,n=>this.shouldConvertForExport(n,i))}isBlockReference(e){return e instanceof u.AcDbBlockReference}collectMissingEntities(e,t,i){const n=[],r=e.newIterator();for(const o of r)i(o)&&(t(o.objectId)||n.push(o));return n}}var _s=(s=>(s[s.LEFT_BOTTOM=0]="LEFT_BOTTOM",s[s.LEFT_TOP=1]="LEFT_TOP",s[s.RIGHT_TOP=2]="RIGHT_TOP",s[s.RIGHT_BOTTOM=4]="RIGHT_BOTTOM",s))(_s||{});class qf extends T.Object3D{constructor(e,t,i=150,n=2){super(),this.camera=e,this.renderer=t,this.gizmoCamera=new T.OrthographicCamera(-2,2,2,-2,0,4),this.gizmoCamera.position.set(0,0,2),this.gizmoDim=i,this.gizmoPos=n,this.initialize()}initialize(){}update(){this.updateOrientation();const e=this.renderer.autoClear;this.renderer.autoClear=!1,this.renderer.clearDepth();const t=new T.Vector4;this.renderer.getViewport(t);const i=this.calculateViewportPos();this.renderer.setViewport(i.x,i.y,this.gizmoDim,this.gizmoDim),this.renderer.render(this,this.gizmoCamera),this.renderer.setViewport(t.x,t.y,t.z,t.w),this.renderer.autoClear=e}dispose(){}updateOrientation(){this.quaternion.copy(this.camera.quaternion).invert(),this.updateMatrixWorld()}calculatePosInViewport(e,t,i){const n=(e-i.min.x)/this.gizmoDim*2-1,r=-((t-i.min.y)/this.gizmoDim)*2+1;return{x:n,y:r}}calculateViewportPos(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,r=this.gizmoDim;let o=t-r,a=i-r;switch(n){case 0:o=0,a=0;break;case 1:o=0;break;case 4:a=0;break}return{x:o,y:a}}calculateViewportBbox(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,r=this.gizmoDim,o=new T.Box2(new T.Vector2(t-r,0),new T.Vector2(t,r));switch(n){case 0:o.set(new T.Vector2(0,i-r),new T.Vector2(r,i));break;case 1:o.set(new T.Vector2(0,0),new T.Vector2(r,r));break;case 4:o.set(new T.Vector2(t-r,i-r),new T.Vector2(t,i));break}return o}}function Jf(s,e){const t=e.font||"Helvetica",i=e.fontSize||30,n=e.width||200,r=e.height||200,o=e.bgColor?e.bgColor.join(", "):"255, 255, 255, 1.0",a=e.color?e.color.join(", "):"0, 0, 0, 1.0",l=document.createElement("canvas");l.width=n,l.height=r;const c=l.getContext("2d");if(c){c.font=`bold ${i}px ${t}`,c.fillStyle=`rgba(${o})`,c.fillRect(0,0,n,r);const m=c.measureText(s).width;c.fillStyle=`rgba(${a})`,c.fillText(s,n/2-m/2,r/2+i/2-2)}const h=new T.Texture(l);return h.minFilter=T.LinearFilter,h.needsUpdate=!0,h}function Lo(s){const e=Jf(s,{fontSize:100,font:"Arial Narrow, sans-serif",color:[255,255,255,1],bgColor:[0,0,0,0]}),t=new T.SpriteMaterial({map:e,transparent:!0});return new T.Sprite(t)}_s.RIGHT_TOP;const Qf={pos:_s.LEFT_BOTTOM,size:100,hasZAxis:!0};class eb extends qf{constructor(e,t,i){const n={...Qf,...i};super(e,t,n.size,i.pos),this.hasZAxis=n.hasZAxis;const r=[0,0,0,2,0,0,0,0,0,0,2,0],o=[1,0,0,1,.6,0,0,1,0,.6,1,0];this.hasZAxis&&(r.push(0,0,0,0,0,2),o.push(0,0,1,0,.6,1));const a=new T.BufferGeometry;a.setAttribute("position",new T.Float32BufferAttribute(r,3)),a.setAttribute("color",new T.Float32BufferAttribute(o,3));const l=new T.LineBasicMaterial({vertexColors:!0,toneMapped:!1});this.axes=new T.LineSegments(a,l),this.axes.position.set(-1,-1,-1),this.add(this.axes),this.xText=Lo("X"),this.xText.position.set(1.5,-1,-1),this.add(this.xText),this.yText=Lo("Y"),this.yText.position.set(-1,1.5,-1),this.add(this.yText),this.hasZAxis&&(this.zText=Lo("Z"),this.zText.position.set(-1,-1,1.5),this.add(this.zText))}setLineColors(e,t){const i=new T.Color,n=this.axes.geometry.attributes.color.array;return i.set(e),i.toArray(n,0),i.toArray(n,3),i.set(t),i.toArray(n,6),i.toArray(n,9),this.axes.geometry.attributes.color.needsUpdate=!0,this}setTextColor(e){this.xText.material.color=e,this.yText.material.color=e}dispose(){var e,t;this.axes.geometry.dispose(),this.axes.material.dispose(),this.xText.geometry.dispose(),this.xText.material.dispose(),this.yText.geometry.dispose(),this.yText.material.dispose(),this.hasZAxis&&((e=this.zText)==null||e.geometry.dispose(),(t=this.zText)==null||t.material.dispose())}}class tb extends M.AcTrBaseView{constructor(e,t,i,n){super(e,i,n),this._layoutBtrId=t,this._mode=me.SELECTION,this._axesGizmo=this.createAxesGizmo(),this._viewportViews=new Map}get layoutBtrId(){return this._layoutBtrId}get mode(){return this._mode}set mode(e){e==me.SELECTION?this._cameraControls.mouseButtons={MIDDLE:T.MOUSE.PAN}:e==me.PAN&&(this._cameraControls.mouseButtons={LEFT:T.MOUSE.PAN}),this._cameraControls.update(),this._mode=e}get viewportCount(){return this._viewportViews.size}get viewportViews(){return this._viewportViews.values()}get internalCamera(){return this._camera.internalCamera}get viewportsBoundingBox(){if(this._viewportViews.size===0)return;const e=new u.AcGeBox2d;return this._viewportViews.forEach(t=>{const i=t.viewport.box;e.expandByPoint(i.min),e.expandByPoint(i.max)}),e.isEmpty()?void 0:e}addViewport(e){this._viewportViews.set(e.viewport.id,e)}removeViewport(e){this._viewportViews.delete(e)}resize(e,t){this._height=t,this._width=e,this._frustum=t/2,this.updateCameraFrustum(),this._viewportViews.forEach(i=>{i.update()})}render(e){var n;this._renderer.clear();const t=this._renderer.render(e.internalScene,this._camera),i=e.modelSpaceLayout;return i&&this.drawViewports(i.internalObject),(n=this._axesGizmo)==null||n.update(),t}createAxesGizmo(){return new eb(this._camera.internalCamera,this._renderer.internalRenderer,{hasZAxis:!1,pos:_s.LEFT_BOTTOM})}drawViewports(e){if(this._viewportViews.size>0){const t=this._renderer.autoClear;this._renderer.autoClear=!1;const i=new T.Vector4;this._renderer.getViewport(i),this._renderer.clearDepth();const n=e.visible;e.visible=!0,this._viewportViews.forEach(r=>{r.render(e)}),e.visible=n,this._renderer.setViewport(i.x,i.y,i.z,i.w),this._renderer.autoClear=t}}}class ib{constructor(){this._activeLayoutBtrId="",this._layoutViews=new Map}get activeLayoutBtrId(){return this._activeLayoutBtrId}set activeLayoutBtrId(e){this._activeLayoutBtrId=e,this._layoutViews.forEach(t=>{t.enabled=t.layoutBtrId==e})}get activeLayoutView(){return this._layoutViews.get(this._activeLayoutBtrId)}has(e){return this._layoutViews.has(e)}getAt(e){return this._layoutViews.get(e)}resize(e,t){this._layoutViews.forEach(i=>{i.resize(e,t)})}add(e){this._layoutViews.set(e.layoutBtrId,e)}render(e){var t;return((t=this.activeLayoutView)==null?void 0:t.render(e))??!1}}function nb(s,e){return[...s].sort((t,i)=>sb(t,i,e))}function sb(s,e,t){const i=Lh(s)-Lh(e);if(Math.abs(i)>Number.EPSILON)return i;const n=Th(t,s)-Th(t,e);return Math.abs(n)>Number.EPSILON?n:0}function Lh(s){return Math.max(s.maxX-s.minX,0)*Math.max(s.maxY-s.minY,0)}function Th(s,e){const t=s.x<e.minX?e.minX-s.x:s.x>e.maxX?s.x-e.maxX:0,i=s.y<e.minY?e.minY-s.y:s.y>e.maxY?s.y-e.maxY:0;return t*t+i*i}const ot=class ot{constructor(e){this.zoomTo=e,this.active=!1,this.userAdjusted=!1,this.programmaticDepth=0,this.incrementalEnabled=!1,this.initialPendingCount=0,this.convertedCount=0,this.lastZoomAt=0}get isActive(){return this.active}begin(e){if(this.active){this.initialPendingCount=Math.max(this.initialPendingCount,e),this.maybeEnableIncrementalFit();return}this.active=!0,this.userAdjusted=!1,this.lastZoomAt=0,this.initialPendingCount=e,this.convertedCount=0,this.lastFittedBox=void 0,this.incrementalEnabled=!1,this.maybeEnableIncrementalFit()}end(){this.active=!1,this.incrementalEnabled=!1,this.lastFittedBox=void 0,this.convertedCount=0}applyFinalFit(e){if(this.userAdjusted)return;const t=e();t&&this.applyZoom(t)}onLayoutViewChanged(){!this.active||this.userAdjusted||this.programmaticDepth>0||(this.userAdjusted=!0,this.end())}afterGeometryBatch(e,t){this.active&&(this.convertedCount++,this.maybeEnableIncrementalFit(),this.maybeIncrementalFit(e))}maybeEnableIncrementalFit(){this.incrementalEnabled||(this.initialPendingCount>=ot.SMALL_ENTITY_THRESHOLD||this.convertedCount>=ot.SMALL_ENTITY_THRESHOLD)&&(this.incrementalEnabled=!0)}maybeIncrementalFit(e){if(!this.active||!this.incrementalEnabled||this.userAdjusted)return;const t=performance.now();if(t-this.lastZoomAt<ot.FIT_INTERVAL_MS)return;const i=e();!i||!this.shouldApplyIncrementalFit(i)||(this.lastZoomAt=t,this.applyZoom(i))}shouldApplyIncrementalFit(e){const t=this.lastFittedBox;if(!t)return!0;const i=this.estimateBoxArea(t);return i<=Number.EPSILON?!0:this.estimateBoxArea(e)>=i*ot.BBOX_GROWTH_RATIO}applyZoom(e,t=1.1){this.programmaticDepth++;try{this.zoomTo(e,t),this.lastFittedBox=this.snapshotFitBox(e)}finally{this.programmaticDepth--}}estimateBoxArea(e){const t=new u.AcGeVector2d;return e.getSize(t),Math.abs(t.x)*Math.abs(t.y)}snapshotFitBox(e){return new u.AcGeBox2d({x:e.min.x,y:e.min.y},{x:e.max.x,y:e.max.y})}};ot.SMALL_ENTITY_THRESHOLD=500,ot.BBOX_GROWTH_RATIO=1.5,ot.FIT_INTERVAL_MS=500;let To=ot;const Io={background:u.ACGI_MODEL_SPACE_BACKGROUND},ai=class ai extends Ul{constructor(e=Io){const t={...Io,...e},i=t.container??document.createElement("div");t.container=i,i.style.overflow="hidden";const n=new T.WebGLRenderer({antialias:!0,alpha:!0});i.appendChild(n.domElement),n.domElement.style.display="block",n.domElement.style.maxWidth="100%",n.domElement.style.maxHeight="100%",super(n.domElement,i),this._rafId=null,this._loadingLayouts=new Set,this._initializedLayouts=new Set,this._externallyFramedLayouts=new Set,this._convertingLayers=new Set,this._progressiveRendering=!1,this._convertQueue=[],this._convertDrainPromise=null,this._convertEpoch=0,this._lastProgressivePaintAt=0,this._progressivePaintCount=0,this._progressiveYieldCount=0,this._pendingGeometryJobs=0,this.animate=()=>{var x;this._rafId=requestAnimationFrame(this.animate),this.events.renderFrame.dispatch({render:this._renderer,camera:this.internalCamera});const f=this._numOfEntitiesToProcess>0,w=f&&!this._progressiveRendering;if(!this._isDirty&&!this._htmlDirty&&!f||w||!this._isDirty&&!this._htmlDirty)return;let v=!1;this._isDirty&&(this._progressiveRendering&&f&&this._progressivePaintCount++,v=this._layoutViewManager.render(this._scene)),this.internalCamera&&(this._isDirty||this._htmlDirty)&&this._css2dRenderer.render(this._scene.internalScene,this.internalCamera),(x=this._stats)==null||x.update(),this._isDirty=v,this._htmlDirty=!1},this._gripManager=new kl(this),this._keyHandler=new vn(this),e.calculateSizeCallback&&this.setCalculateSizeCallback(e.calculateSizeCallback),n.setPixelRatio(Math.min(window.devicePixelRatio,2)),n.setSize(this.width,this.height),this._renderer=new M.AcTrRenderer(n);const r=we.instance.fontMapping;this._renderer.setFontMapping(r),this._renderer.events.fontNotFound.addEventListener(f=>{Q.emit("font-not-found",{fontName:f.fontName,count:f.count??0})}),this._scene=this.createScene(),this._layerAppearance=new Qa(this._scene,this._renderer),this._inheritedLayerMaterialMapper=new Xa(f=>this._layerAppearance.getEffectiveLayerTraits(f),this._renderer),this.backgroundColor=t.background??u.ACGI_MODEL_SPACE_BACKGROUND,this._stats=this.createStats(we.instance.isShowStats);const o=u.AcDbSysVarManager.instance(),a=u.AcDbSystemVariables.MODELBKCOLOR.toLowerCase(),l=u.AcDbSystemVariables.PAPERBKCOLOR.toLowerCase();o.events.sysVarChanged.addEventListener(f=>{const w=f.name.toLowerCase();if(w===a||w===l){const v=this.isModelSpaceLayout(f.database);if(!(w===a&&v||w===l&&!v))return;this.applyCanvasBackground(fn(f.database,v))}}),we.instance.events.modified.addEventListener(f=>{f.key=="isShowStats"&&this.toggleStatsVisibility(this._stats,f.value)});let c=null,h=null,p=null;const m=()=>this.mode===me.SELECTION&&!this.editor.isActive&&!Ke.getActiveInputBox()&&!dl()&&!this._gripManager.isDragging,g=()=>{p==null||p.remove(),p=null};this.canvas.addEventListener("mousedown",f=>{f.button===0&&m()&&(h=this.viewportToCanvas({x:f.clientX,y:f.clientY}),c=this.screenToWorld(h),p=document.createElement("div"),p.className="ml-jig-preview-rect",this.container.appendChild(p))}),this.canvas.addEventListener("mousemove",f=>{if(!c||!p||!h)return;const w=this.viewportToCanvas({x:f.clientX,y:f.clientY}),v=this.screenToWorld(w),x=this.worldToScreen(c),S=this.worldToScreen(v),P=Math.min(x.x,S.x),A=Math.min(x.y,S.y),_=Math.abs(x.x-S.x),C=Math.abs(x.y-S.y),O=this.getSelectionMode(h,w),j=this.getPointerSelectionAction(f),L=this.getSelectionPreviewStyle(O,j);Object.assign(p.style,{left:`${P}px`,top:`${A}px`,width:`${_}px`,height:`${C}px`,borderStyle:L.borderStyle,background:L.background}),p.style.setProperty("--line-color",L.lineColor)}),this.canvas.addEventListener("mouseup",f=>{if(this._gripManager.isDragging){c=null,h=null,g();return}if(!c||!h)return;const w=this.viewportToCanvas({x:f.clientX,y:f.clientY}),v=this.screenToWorld(w);g();const x=this.getPointerSelectionAction(f);if(this.isSelectionClick(h,w))if(La(this,w.x,w.y,x))x==="replace"&&this.selectionSet.clear();else{const S=this.pick(v);S.length>0?(x==="replace"&&this.htmlTransientManager.deselectAll(),this.applySelection([S[0].id],x)):x==="replace"&&this.selectionSet.clear()}else{const S=new u.AcGeBox2d().expandByPoint(c).expandByPoint(v),P=this.getSelectionMode(h,w);this.selectByBoxWithMode(S,P,x),Ta(this,S,P,x)}c=null,h=null}),this.canvas.addEventListener("dblclick",f=>{f.button===0&&m()&&k.instance.curDocument.openMode===F.Write&&this.openPickedEntityEditor(f)}),document.addEventListener("keydown",f=>{this._keyHandler.handleKeyDown(f)}),u.acdbHostApplicationServices().layoutManager.events.layoutSwitched.addEventListener(f=>{const w=f.layout.blockTableRecordId,v=!this._initializedLayouts.has(w);this._initializedLayouts.add(w),this.activeLayoutBtrId=w,this.createLayoutViewIfNeeded(w),this.loadLayoutEntitiesIfNeeded(w),this.refreshCanvasBackgroundForActiveLayout(),this._isDirty=!0,v&&this.applyInitialZoom(w,f.layout)}),this._css2dRenderer=new Nh.CSS2DRenderer,this._css2dRenderer.setSize(this.width,this.height),this._css2dRenderer.domElement.style.position="absolute",this._css2dRenderer.domElement.style.top="0px",this._css2dRenderer.domElement.style.left="0px",this._css2dRenderer.domElement.style.pointerEvents="none",this._css2dRenderer.domElement.style.zIndex="99998",this._css2dRenderer.domElement.style.maxWidth="100%",this._css2dRenderer.domElement.style.maxHeight="100%",i.appendChild(this._css2dRenderer.domElement),this._missedImages=new Map,this._layoutViewManager=new ib,this._progressiveOpenFit=new To((f,w)=>{this.activeLayoutView.zoomTo(f,w??1.1),this._isDirty=!0}),this._entityDisplay=new Xf(f=>this.resolveLayerInfo(f)),this.initialize(),this.onWindowResize(),this._isDirty=!0,this._htmlDirty=!1,this.startAnimationLoop(),this._numOfEntitiesToProcess=0,this._pendingGeometryJobs=0}getPointerSelectionAction(e){return Kl(e)}initialize(){this.setCursor(Ce.Crosshair)}get mode(){const e=this.activeLayoutView;return e?e.mode:me.SELECTION}set mode(e){this.activeLayoutView.mode=e}get renderer(){return this._renderer}get gripManager(){return this._gripManager}get isDirty(){return this._isDirty}get isProcessingEntities(){return this._numOfEntitiesToProcess>0||this._pendingGeometryJobs>0}async waitUntilIdle(e=6e4){const t=Date.now()+Math.max(0,e);let i=0;for(;;){if(this.isProcessingEntities)i=0;else if(i++,i>=2)return!0;if(Date.now()>t)return!this.isProcessingEntities;await new Promise(n=>setTimeout(n,16))}}get progressiveRendering(){return this._progressiveRendering}set progressiveRendering(e){this._progressiveRendering=e,this.resetProgressiveOpenStats()}get progressiveOpenStats(){return{paintCount:this._progressivePaintCount,yieldCount:this._progressiveYieldCount}}resetProgressiveOpenStats(){this._progressivePaintCount=0,this._progressiveYieldCount=0,this._lastProgressivePaintAt=0}beginProgressiveOpenFit(){this._progressiveOpenFit.begin(this._numOfEntitiesToProcess)}endProgressiveOpenFit(){this._progressiveOpenFit.end()}set isDirty(e){this._isDirty=e}get isHtmlDirty(){return this._htmlDirty}set isHtmlDirty(e){this._htmlDirty=e}get missedData(){return{fonts:this._renderer.missedFonts,images:this._missedImages,xrefs:this.collectUnresolvedXrefs()}}collectUnresolvedXrefs(){var e,t;try{const i=(t=(e=k.instance)==null?void 0:e.curDocument)==null?void 0:t.database;if(!i)return[];const n=i.tables.blockTable;return typeof n.getUnresolvedXrefs!="function"?[]:n.getUnresolvedXrefs().map(r=>({name:r.name,pathName:r.pathName,isOverlay:r.isOverlayReference}))}catch{return[]}}get center(){return this.activeLayoutView.center}set center(e){this.activeLayoutView.center=e}get backgroundColor(){return this._renderer.getClearColor()}set backgroundColor(e){this.applyCanvasBackground(e)}applyCanvasBackground(e){this._renderer.setClearColor(e),this._renderer.currentBackgroundColor=e,this._layerAppearance.refreshTextMaterialsInObjectTree(this._scene.internalScene),this.resyncForegroundLayersForBackground(),this.editor.syncCursorBackground(e),this._isDirty=!0}resyncForegroundLayersForBackground(){var t;const e=this._renderer.context.database;if(e)for(const i of e.tables.layerTable.newIterator())(t=i.color)!=null&&t.isForeground&&this._layerAppearance.syncFromLiveRecord(i)}isModelSpaceLayout(e){return e?Ha(e):this.activeLayoutBtrId===this.modelSpaceBtrId}bindDrawDatabase(e){this._renderer.context.database=e}syncDisplaySysVars(e){this.bindDrawDatabase(e),this.applyCanvasBackground(fn(e,this.isModelSpaceLayout(e)))}async addOverlayEntities(e){const t=new rl;t.isReference=!0,t.internalObject.userData.isReference=!0,this._scene.internalScene.add(t.internalObject);for(const n of e.tables.layerTable.newIterator())t.addLayer({name:n.name,isOff:n.isOff,isFrozen:n.isFrozen,color:n.color});const i=this._renderer.context.database;this._renderer.context.database=e;try{const n=e.tables.blockTable.modelSpace;for(const r of n.newIterator())if(!(r instanceof u.AcDbViewport))try{const o=this.drawEntity(r,!1);if(!o)continue;o.objectId=r.objectId,o.ownerId=r.ownerId,o.layerName=r.layer,o.visible=r.visibility!==!1,o instanceof M.AcTrGroup&&o.isOnTheSameLayer&&this._inheritedLayerMaterialMapper.remap(o.children,"0",o.layerName),await this.finishEntityGeometry(o,!1),t.addEntity(o),o.dispose()}catch(o){u.log.error(`[AcTrView2d] Failed to convert overlay entity ${r.objectId} (${r.type}):`,o)}}finally{this._renderer.context.database=i}return t}refreshCanvasBackgroundForActiveLayout(){var n,r;const t=(r=(n=k._instance)==null?void 0:n.curDocument)==null?void 0:r.database;if(!t)return;const i=this.activeLayoutBtrId===this.modelSpaceBtrId;this.applyCanvasBackground(fn(t,i))}get modelSpaceBtrId(){return this._scene.modelSpaceBtrId}set modelSpaceBtrId(e){this._scene.modelSpaceBtrId=e}get activeLayoutBtrId(){return this._scene.activeLayoutBtrId}set activeLayoutBtrId(e){this._layoutViewManager.activeLayoutBtrId=e,this._scene.activeLayoutBtrId=e,this.htmlTransientManager.setActiveLayoutId(e),this._isDirty=!0}get activeLayoutView(){return this._layoutViewManager.activeLayoutView}get stats(){return this._scene.stats}get cadScene(){return this._scene}async ensureEntitiesConvertedForExport(e){const t=(e==null?void 0:e.includeInvisibleLayers)!==!1,i=k.instance.curDocument.database,n=[];for(const[o]of this._scene.layouts){const a=i.tables.blockTable.getIdAt(o);a&&n.push(...this._entityDisplay.collectMissingEntitiesForExport(a,l=>this.hasEntity(l),t))}n.length>0&&(this._numOfEntitiesToProcess+=n.length,await this.batchConvert(n,{forExport:!0})),await this.waitUntilIdle()||u.log.warn("[AcTrView2d] Timed out waiting for deferred geometry before export")}get internalScene(){return this._scene.internalScene}get htmlTransientManager(){return this._scene.htmlTransientManager}get internalCamera(){var e;return(e=this.activeLayoutView)==null?void 0:e.internalCamera}set ltscale(e){this._renderer.ltscale=e}set celtscale(e){this._renderer.celtscale=e}screenToWorld(e){const t=this.activeLayoutView;return t?t.screenToWorld(e):new u.AcGePoint2d(e)}worldToScreen(e){const t=this.activeLayoutView;return t?t.worldToScreen(e):new u.AcGePoint2d(e)}zoomTo(e,t=1.1){this.activeLayoutView.zoomTo(e,t),this._isDirty=!0}rerenderPoints(e){const t=this._scene.activeLayout;t&&(t.rerenderPoints(e),this._isDirty=!0)}zoomToFitDrawing(e=0,t){new yr(()=>!this.isProcessingEntities,()=>{if(t&&this._externallyFramedLayouts.delete(t)){this.endProgressiveOpenFit();return}this._progressiveOpenFit.applyFinalFit(()=>this.resolveLayoutFitBox()),this.endProgressiveOpenFit()},300,e).start()}zoomToFitLayer(e){const t=this._scene.activeLayout;if(t){const i=t.getLayer(e);if(i&&!i.box.isEmpty()){const n=Eo.threeBox3dToGeBox2d(i.box);return this.zoomTo(n),this._isDirty=!0,!0}}return!1}flyTo(e,t){this.activeLayoutView.flyTo(e,t),this._isDirty=!0}async openPickedEntityEditor(e){const t=this.viewportToCanvas({x:e.clientX,y:e.clientY}),i=this.screenToWorld(t),n=this.pick(i,void 0,!0);if(!n.length)return;const r=k.instance.curDocument.database.tables.blockTable.getEntityById(n[0].id);if(!r)return;const o=this.resolveAttributedBlockReference(r);if(o){e.preventDefault(),this.selectionSet.clear(),this.selectionSet.add(o.objectId),k.instance.sendStringToExecute("attedit");return}r instanceof u.AcDbMText&&(e.preventDefault(),await this.editMTextEntity(r))}resolveAttributedBlockReference(e){if(e instanceof u.AcDbBlockReference)return e.attributeIterator().count>0?e:void 0;if(e instanceof u.AcDbAttribute){const t=k.instance.curDocument.database.tables.blockTable.getEntityById(e.ownerId);if(t instanceof u.AcDbBlockReference&&t.attributeIterator().count>0)return t}}async editMTextEntity(e){const t=e.database;e.lineSpacingFactor!==Ke.defaultLineSpacingFactor&&ct(t,"Edit MText",()=>{const r=t.openEntityForWrite(e);r instanceof u.AcDbMText&&(r.lineSpacingFactor=Ke.defaultLineSpacingFactor)}),this._isDirty=!0;const i=new Ke;let n=!1;try{const r=await i.open({view:this,location:e.location,width:this.resolveMTextEditorWidth(e),textHeight:this.resolveMTextEditorTextHeight(e),initialText:e.contents,initialAttachmentPoint:e.attachmentPoint,toolbarFontFamilies:this.getMTextToolbarFontFamilies()});if(!r)return;ct(t,"Edit MText",()=>{const o=t.openEntityForWrite(e);o instanceof u.AcDbMText&&(o.location=r.location,o.contents=r.contents,o.width=r.width,o.height=r.height,o.lineSpacingFactor=r.lineSpacingFactor,o.attachmentPoint=r.attachmentPoint)}),n=!0}finally{n||(this.updateEntity(e),this._isDirty=!0)}}resolveMTextEditorWidth(e){const t=Number(e.width);return Number.isFinite(t)&&t>0?t:1e-4}resolveMTextEditorTextHeight(e){const t=Number(e.height);return Number.isFinite(t)&&t>0?t:this.pixelsToWorldY(24)}pixelsToWorldY(e){const t=this.screenToWorld({x:0,y:0}),i=this.screenToWorld({x:0,y:e});return Math.max(Math.abs(i.y-t.y),1e-4)}getMTextToolbarFontFamilies(){return Array.from(new Set(k.instance.avaiableFonts.flatMap(e=>e.name).map(e=>e.trim()).filter(e=>e.length>0)))}pick(e,t,i){e==null&&(e=this.curPos);const n=[],r=this._scene.activeLayout;if(!r)return n;const o=this.activeLayoutView,a=t??this.selectionBoxSize,l=o.pointToBox(e,a),c=Math.max(l.size.width/2,l.size.height/2),h=o.layoutBtrId!==this._scene.modelSpaceBtrId,p=(l.size.width+l.size.height)/2,m=[],g=new Set;if(h)for(const x of o.viewportViews)x.containsPaperPoint(e)&&!x.isNearPaperBorder(e,p)&&(m.push(x),g.add(x.viewport.id));const f=this._scene.search(l),w=o.resetRaycaster(e,c);f.forEach(x=>{g.has(x.id)||xn(x)&&r.isIntersectWith(x.id,w)&&n.push(x)}),m.length>0&&this.pickThroughViewports(e,l,m,n);const v=nb(n,e);return i?v.slice(0,1):v}pickThroughViewports(e,t,i,n){const r=this._scene.modelSpaceLayout;if(!r)return;const o=(t.size.width+t.size.height)/4;for(const a of i){const l=a.paperPointToModel(e),c=o*a.paperToModelScale;if(c<=0)continue;const h=new u.AcGeBox2d().setFromPoints([new u.AcGePoint2d(l.x-c,l.y-c),new u.AcGePoint2d(l.x+c,l.y+c)]),p=a.resetRaycaster(l,c);r.search(h).forEach(g=>{xn(g)&&r.isIntersectWith(g.id,p)&&n.push(g)})}}search(e,t){return this._scene.search(e,t)}select(e){const t=[];this.pick(e).forEach(n=>t.push(n.id)),t.length>0&&this.selectionSet.add(t)}selectByBox(e){this.selectByBoxWithMode(e,"crossing","add")}addLayer(e){this._scene.addLayer(this.toLayerInfo(e)),this._layerAppearance.syncFromLiveRecord(e),this._isDirty=!0}updateLayer(e,t){const{touchedObjectIds:i}=this._scene.updateLayer(this.toLayerInfo(e));if(this._layerAppearance.layerStyleMayHaveChanged(t)&&this._layerAppearance.syncFromLiveRecord(e),this._entityDisplay.layerVisibilityMayHaveChanged(t)){const n=this.toLayerInfo(e);(Kt.isLayerVisible(n)||!n.isFrozen)&&this.convertMissingEntitiesOnLayer(e.name)}for(const n of i)this.applySessionHiddenObjectState(n);this._isDirty=!0}addTransientEntity(e){const t=Array.isArray(e)?e:[e],i=this._convertEpoch,n=this._renderer.forceShowLineWeight;this._renderer.forceShowLineWeight=!0;try{for(let r=0;r<t.length;++r){const o=t[r],a=this.drawEntity(o,!0);a&&(a.objectId=o.objectId,a.asyncDraw().then(()=>{if(i!==this._convertEpoch){a.dispose();return}this._scene.addTransientEntity(a),this._isDirty=!0}).catch(l=>{u.log.error("[AcTrView2d] Transient entity geometry failed:",l),a.dispose()}))}}finally{this._renderer.forceShowLineWeight=n}}removeTransientEntity(e){this._scene.removeTransientEntity(e),this._isDirty=!0}setTransientEntityVisible(e,t){this._scene.setTransientEntityVisible(e,t)&&(this._isDirty=!0)}canCreateEntityPreview(e){return this._scene.canCreatePreview(e)}createEntityPreview(e){const t=this._scene.createPreview(e);return t&&(this._isDirty=!0),t}updateEntityPreview(e,t){this._scene.updatePreview(e,M.AcTrMatrixUtil.createMatrix4(t))&&(this._isDirty=!0)}removeEntityPreview(e){this._scene.removePreview(e)&&(this._isDirty=!0)}updateTransientPreviewTransforms(e){const t=this._scene.updateTransientPreviewTransforms(e.map(i=>({objectId:i.objectId,matrix:M.AcTrMatrixUtil.createMatrix4(i.matrix)})));t.webgl&&(this._isDirty=!0),t.html&&(this._htmlDirty=!0)}addEntity(e){const t=Array.isArray(e)?e:[e];this._numOfEntitiesToProcess+=t.length,this._progressiveRendering?(this._convertQueue.push(...t),this.drainConvertQueue()):this.batchConvert(t)}removeEntity(e){(Array.isArray(e)?e:[e]).forEach(i=>this._scene.removeEntity(i.objectId)),this._isDirty=!0}hasEntity(e){return this._scene.hasEntity(e)}getEntityVisible(e){return this._scene.getEntityVisible(e)}updateEntityVisibility(e){return this._scene.setEntityVisible(e.objectId,e.visibility)?(this._isDirty=!0,!0):!1}setEntitySceneVisible(e,t){return this._scene.setEntityVisible(e,t)?(this._isDirty=!0,!0):!1}applySessionHiddenObjectState(e){k.instance.curDocument.isObjectHidden(e)&&this._scene.setEntityVisible(e,!1)}updateEntity(e){const t=this.resolveSceneUpdateEntities(Array.isArray(e)?e:[e]);if(t.length===0)return;const i=t.map(n=>n.objectId).filter(n=>this.selectionSet.has(n));for(let n=0;n<t.length;++n){const r=t[n];this._scene.hasEntity(r.objectId)&&this._scene.removeEntity(r.objectId)}(async()=>(await this.batchConvert(t),await this.waitUntilDeferredGeometryIdle(),i.length>0&&this.highlight(i),this._gripManager.refresh()))(),this._isDirty=!0,setTimeout(()=>{this._isDirty=!0},100)}resolveSceneUpdateEntities(e){var r;const t=(r=k.instance.curDocument)==null?void 0:r.database,i=[],n=new Set;for(const o of e){let a=o;if(o instanceof u.AcDbAttribute){const l=t==null?void 0:t.tables.blockTable.getEntityById(o.ownerId);if(!(l instanceof u.AcDbBlockReference))continue;a=l}n.has(a.objectId)||(n.add(a.objectId),i.push(a))}return i}addLayout(e){this._scene.addEmptyLayout(e.blockTableRecordId),this.createLayoutViewIfNeeded(e.blockTableRecordId),this._isDirty=!0}markLayoutAsInitialized(e){this._initializedLayouts.add(e),this._externallyFramedLayouts.add(e)}resolveLayoutFitBox(){const e=this._scene.box;if(e&&!e.isEmpty())return Eo.threeBox3dToGeBox2d(e)}applyInitialZoom(e,t){new yr(()=>!this.isProcessingEntities,()=>{if(this._externallyFramedLayouts.delete(e))return;const n=t.limits,r=this._layoutViewManager.getAt(e),o=r==null?void 0:r.viewportsBoundingBox,a=!n||n.isEmpty()?!1:o?n.min.x<=o.min.x&&n.min.y<=o.min.y&&n.max.x>=o.max.x&&n.max.y>=o.max.y:!0;if(n&&!n.isEmpty()&&a)this.zoomTo(n);else if(o)this.zoomTo(o);else if(t.extents&&!t.extents.isEmpty()){const l=t.extents;this.zoomTo(new u.AcGeBox2d({x:l.min.x,y:l.min.y},{x:l.max.x,y:l.max.y}))}else{const l=this.resolveLayoutFitBox();l&&this.zoomTo(l)}this._isDirty=!0},300,0).start()}clear(){this._convertEpoch++,this._convertQueue.length=0,this._numOfEntitiesToProcess=0,this._pendingGeometryJobs=0,this._scene.clear(),this._isDirty=!0,this._missedImages.clear(),this._renderer.dispose()}async drainConvertQueue(){if(this._convertDrainPromise){await this._convertDrainPromise,this._convertQueue.length>0&&await this.drainConvertQueue();return}this._convertDrainPromise=(async()=>{for(;this._convertQueue.length>0;){const e=this._convertQueue.splice(0,this._convertQueue.length);await this.batchConvert(e)}})().finally(()=>{this._convertDrainPromise=null}),await this._convertDrainPromise}markProgressiveDirty(e=!1){const t=performance.now();(e||t-this._lastProgressivePaintAt>=ai.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS)&&(this._isDirty=!0,this._lastProgressivePaintAt=t)}highlight(e){this._isDirty=this._scene.select(e)}unhighlight(e){this._isDirty=this._scene.unselect(e)}stopAnimationLoop(){this._rafId!=null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}onHover(e){this._isDirty=this._scene.hover([e])}onUnhover(e){this._isDirty=this._scene.unhover([e])}createScene(){return new ol}createStats(e){const t=new zh;document.body.appendChild(t.dom);const i=t.dom;return i.style.position="fixed",i.style.inset="unset",i.style.bottom="30px",i.style.right="0px",this.toggleStatsVisibility(t,e),t}onWindowResize(){super.onWindowResize(),this._renderer.setSize(this.width,this.height),this._css2dRenderer.setSize(this.width,this.height),this._layoutViewManager.resize(this.width,this.height),this._isDirty=!0}startAnimationLoop(){this._rafId==null&&(this._rafId=requestAnimationFrame(this.animate))}createLayoutViewIfNeeded(e){let t=this._layoutViewManager.getAt(e);return t==null&&(t=new tb(this._renderer,e,this.width,this.height),t.events.viewChanged.addEventListener(()=>{this._progressiveOpenFit.onLayoutViewChanged(),this._isDirty=!0,this.events.viewChanged.dispatch(),this.clearHover()}),this._layoutViewManager.add(t)),t}loadLayoutEntitiesIfNeeded(e){try{const i=k.instance.curDocument.database.tables.blockTable.getIdAt(e);if(!i)return;const n=this._scene.layouts.get(e);if(n&&n.isLoaded||this._loadingLayouts.has(e))return;const r=this._layoutViewManager.getAt(e);if(n&&n.entityCount>0&&r&&r.viewportCount===0&&this.ensureViewportViews(i,r),n&&n.entityCount>0){n.isLoaded=!0;return}n||this._scene.addEmptyLayout(e);const o=[],a=i.newIterator();for(const c of a)o.push(c);if(o.length===0){const c=this._scene.layouts.get(e);c&&(c.isLoaded=!0);return}this._loadingLayouts.add(e),this._numOfEntitiesToProcess+=o.length,(async()=>{try{this._progressiveRendering?(this._convertQueue.push(...o),await this.drainConvertQueue()):await this.batchConvert(o);const c=this._scene.layouts.get(e);c&&(c.isLoaded=!0)}finally{this._loadingLayouts.delete(e)}})()}catch(t){u.log.error("[AcTrView2d] Error loading layout entities:",t)}}toggleStatsVisibility(e,t){t?e.dom.style.display="block":e.dom.style.display="none"}toLayerInfo(e){return{name:e.name,isFrozen:e.isFrozen,isOff:e.isOff,color:e.color}}resolveLayerInfo(e){const t=k.instance.curDocument.database.tables.layerTable.getAt(e);return t?this.toLayerInfo(t):void 0}async convertMissingEntitiesOnLayer(e){if(!this._convertingLayers.has(e)){this._convertingLayers.add(e);try{const i=k.instance.curDocument.database.tables.blockTable.getIdAt(this.activeLayoutBtrId);if(!i)return;const n=this._entityDisplay.collectMissingEntitiesOnLayer(e,i,r=>this.hasEntity(r));if(n.length===0)return;this._numOfEntitiesToProcess+=n.length,await this.batchConvert(n)}finally{this._convertingLayers.delete(e)}}}drawEntity(e,t){return e.worldDraw(this._renderer,t)}async finishEntityGeometry(e,t){if(e instanceof M.AcTrGroup){if(e.getSourceEntities().length===0&&!this.groupHasPendingGlyphGeometry(e))return;await e.asyncDraw();return}e.hasDrawableGeometry()||await e.asyncDraw()}needsDeferredFontGeometry(e){return e instanceof M.AcTrGlyphEntity||e instanceof M.AcTrGroup}groupHasPendingGlyphGeometry(e){let t=!1;return e.traverse(i=>{i instanceof M.AcTrGlyphEntity&&!i.hasDrawableGeometry()&&(t=!0)}),t}enqueueDeferredGeometry(e,t){t===this._convertEpoch&&(this._pendingGeometryJobs++,e().then(()=>{t===this._convertEpoch&&(this._isDirty=!0)}).catch(i=>{u.log.error("[AcTrView2d] Deferred entity geometry failed:",i)}).finally(()=>{t===this._convertEpoch&&(this._pendingGeometryJobs=Math.max(0,this._pendingGeometryJobs-1),this._pendingGeometryJobs===0&&(this._isDirty=!0))}))}async waitUntilDeferredGeometryIdle(){const e=this._convertEpoch;for(;e===this._convertEpoch&&this._pendingGeometryJobs>0;)await new Promise(t=>setTimeout(t,0))}ensureViewportViews(e,t){const i=e.newIterator();for(const n of i){if(!(n instanceof u.AcDbViewport)||M.AcTrViewportView.isDefaultPaperSpaceViewport(n))continue;const r=new M.AcTrViewportView(t,n.toGiViewport(),this._renderer);t.addViewport(r)}}async batchConvert(e,t={}){const i=this._convertEpoch,n=this._progressiveRendering&&!t.forExport,r=n?new u.AcCmUiYieldGate(ai.PROGRESSIVE_OPEN_YIELD_BUDGET_MS):void 0,o=()=>new Promise(a=>setTimeout(a,0));for(let a=0;a<e.length;++a){const l=e[a];try{if(i!==this._convertEpoch||l instanceof u.AcDbViewport&&M.AcTrViewportView.isDefaultPaperSpaceViewport(l)||!(t.forExport?this._entityDisplay.shouldConvertForExport(l):this._entityDisplay.shouldConvert(l)))continue;const h=Ya(l,this._renderer);if(h){let m=!1;try{m=this._scene.addDirectEntity(h,Za(l)),m&&(this.applySessionHiddenObjectState(l.objectId),n&&(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.resolveLayoutFitBox(),a)))}finally{h.geometry.dispose()}if(m)continue}const p=this.drawEntity(l,!1);if(!p&&!(l instanceof u.AcDbViewport))continue;if(p){p.objectId=l.objectId,p.ownerId=l.ownerId,p.layerName=l.layer,p.visible=l.visibility!==!1,p instanceof M.AcTrGroup&&p.isOnTheSameLayer&&(this._inheritedLayerMaterialMapper.remap(p.children,"0",p.layerName),p.userData.insertLayerName=p.layerName);const m=p instanceof M.AcTrGroup&&!p.isOnTheSameLayer,g=!t.forExport&&this.needsDeferredFontGeometry(p);if(m)g?this.enqueueDeferredGeometry(()=>this.handleGroup(p,n,i),i):await this.handleGroup(p,n,i);else{const f=!(l instanceof u.AcDbRay||l instanceof u.AcDbXline),w=async()=>{if(await this.finishEntityGeometry(p,n),i!==this._convertEpoch){p.dispose();return}p instanceof M.AcTrGroup&&this.syncGroupSpatialBoundsForIndexing(p),this._scene.addEntity(p,f),this.applySessionHiddenObjectState(l.objectId),p.dispose(),n&&(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.resolveLayoutFitBox(),a))};g?this.enqueueDeferredGeometry(w,i):await w()}}if(i!==this._convertEpoch)continue;if(l instanceof u.AcDbViewport){if(!M.AcTrViewportView.isDefaultPaperSpaceViewport(l)){const m=this._layoutViewManager.getAt(l.ownerId);if(m){const g=new M.AcTrViewportView(m,l.toGiViewport(),this._renderer);m.addViewport(g)}}}else if(l instanceof u.AcDbRasterImage){const m=l.imageFileName;m&&!l.image&&this._missedImages.set(l.objectId,m)}}catch(c){u.log.error(`[AcTrView2d] Failed to convert entity ${l.objectId} (${l.type}):`,c)}finally{i===this._convertEpoch&&this.decreaseNumOfEntitiesToProcess()}i===this._convertEpoch&&r&&await r.maybeYield(o)&&this._progressiveYieldCount++}}syncGroupSpatialBoundsForIndexing(e){if(e.refreshWcsChildBoxesFromChildren(),e.wcsChildBoxes.length===0)return;const t=e.wcsChildBoxes.map(n=>({minX:n.minX,minY:n.minY,maxX:n.maxX,maxY:n.maxY,id:n.id}));e.wcsBbox=cr(e);const i=e.userData;i.spatialIndexChildBoxes=t}async handleGroup(e,t,i=this._convertEpoch){if(await this.finishEntityGeometry(e,t),i!==this._convertEpoch){e.dispose();return}this.syncGroupSpatialBoundsForIndexing(e);const n=e.children,r=new Map;n.forEach(p=>{var g;if(p.visible===!1)return;const m=p.userData.layerName;r.has(m)||r.set(m,[]),(g=r.get(m))==null||g.push(p)}),e.children=[];for(const p of n)p.parent=null;const o=e.renderContext,a=e.objectId,l=e.layerName;process.env.NODE_ENV!=="production"&&Up(e);const c=e.wcsChildBoxes.map(p=>({minX:p.minX,minY:p.minY,maxX:p.maxX,maxY:p.maxY,id:p.id})),h=c.length>0?cr(e):e.wcsBbox.clone();c.length>0&&(e.wcsBbox=h.clone()),r.forEach((p,m)=>{const g=m==="0"?l:m,f=p.some(x=>(x.userData.authoredLayerName??m)==="0")?"0":m;this._inheritedLayerMaterialMapper.remap(p,f,g);const w=new M.AcTrEntity(o);w.applyMatrix4(e.matrix),w.objectId=a,w.ownerId=e.ownerId,w.layerName=g,w.userData.insertLayerName=l,w.wcsBbox=h.clone();const v=w.userData;v.spatialIndexChildBoxes=c;for(let x=0;x<p.length;x++)w.add(p[x]);this._layerAppearance.refreshTextMaterialsInObjectTree(w),this._scene.addEntity(w,!0),this.applySessionHiddenObjectState(a),w.dispose()}),e.dispose(),t&&(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.resolveLayoutFitBox()))}decreaseNumOfEntitiesToProcess(){this._numOfEntitiesToProcess--,this._numOfEntitiesToProcess<0?(this._numOfEntitiesToProcess=0,u.log.warn("Something wrong! The number of entities to process should not be less than 0.")):this._numOfEntitiesToProcess===0&&(this._isDirty=!0)}};ai.PROGRESSIVE_OPEN_YIELD_BUDGET_MS=300,ai.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS=1e3;let Yi=ai;function rb(s){if(!s)return!1;const e=Object.keys(s);return e.length>0&&e.every(t=>t==="visibility")}function ob(s,e,t){const{entity:i,changes:n}=s,r=i.objectId;if(!e(r))return!1;if(rb(n))return!(n.visibility===!0&&t(r)===void 0);if(n&&Object.keys(n).length>0)return!1;const o=t(r);return o===void 0?!1:o&&!i.visibility}function Ih(s){return Array.isArray(s)?s:[s]}class Mh{constructor(e,t){this._view=e,this._doc=t,t.database.events.entityAppended.addEventListener(i=>{const n=Ih(i.entity).filter(r=>!this.view.hasEntity(r.objectId));n.length!==0&&this.view.addEntity(n.length===1?n[0]:n)}),t.database.events.entityModified.addEventListener(i=>{const n=i,r=this.view;r instanceof Yi&&ob(n,o=>r.hasEntity(o),o=>r.getEntityVisible(o))&&r.updateEntityVisibility(n.entity)||this.view.updateEntity(n.entity)}),t.database.events.entityErased.addEventListener(i=>{const n=Ih(i.entity).filter(r=>this.view.hasEntity(r.objectId));n.length!==0&&this.view.removeEntity(n.length===1?n[0]:n)}),t.database.events.layerAppended.addEventListener(i=>{this._view.addLayer(i.layer)}),t.database.events.layerModified.addEventListener(i=>{this._view.updateLayer(i.layer,i.changes)}),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(i=>{if(i.name==u.AcDbSystemVariables.PDMODE.toLowerCase())this._view.rerenderPoints(i.database.pdmode);else if(i.name==u.AcDbSystemVariables.LWDISPLAY.toLowerCase()){const n=this._view,r=!!i.database.lwdisplay;n.renderer.showLineWeight!==r&&(n.renderer.showLineWeight=r,n.clear(),i.database.regen())}}),t.database.events.dictObjetSet.addEventListener(i=>{i.object instanceof u.AcDbLayout&&this._view.addLayout(i.object)}),e.selectionSet.events.selectionAdded.addEventListener(i=>{e.highlight(i.ids)}),e.selectionSet.events.selectionRemoved.addEventListener(i=>{e.unhighlight(i.ids)})}get view(){return this._view}get doc(){return this._doc}}function Mo(s){return typeof s.hasEntity=="function"&&typeof s.setEntitySceneVisible=="function"}function ab(s,e,t){!s.isObjectHidden(t)||!Mo(e)||e.setEntitySceneVisible(t,!1)}function Dh(s,e){const t=s.view;if(!Mo(t))return 0;const i=s.doc,n=i.database;let r=0;for(const o of e){if(i.isObjectHidden(o))continue;const a=n.tables.blockTable.getEntityById(o);!(a!=null&&a.visibility)||!t.hasEntity(o)||t.setEntitySceneVisible(o,!1)&&(i.addHiddenObject(o),r++)}return r>0&&t.selectionSet.clear(),r}function Oh(s){const e=s.view;if(!Mo(e))return 0;const t=s.doc,i=t.database,n=t.takeHiddenObjects();let r=0;for(const o of n){const a=i.tables.blockTable.getEntityById(o);!a||!e.hasEntity(o)||e.setEntitySceneVisible(o,a.visibility)&&r++}return e.selectionSet.clear(),r}class lb extends z{async execute(e){u.log.info("Hello from ExamplePlugin!"),u.log.info("Current document:",e.doc),u.log.info("Current view:",e.view)}}class cb{constructor(){this.name="ExamplePlugin",this.version="1.0.0",this.description="An example plugin demonstrating the plugin system",this.registeredCommands=[]}onLoad(e,t){t.addCommand("USER","HELLO","Hello",new lb),this.registeredCommands.push({group:"USER",name:"HELLO"}),u.log.info(`[${this.name}] Plugin loaded successfully`),u.log.info(`[${this.name}] Registered command: HELLO`)}onUnload(e,t){for(const i of this.registeredCommands)t.removeCmd(i.group,i.name);this.registeredCommands=[],u.log.info(`[${this.name}] Plugin unloaded`)}}Object.defineProperty(y,"ACGI_DARK_THEME_FOREGROUND",{enumerable:!0,get:()=>u.ACGI_DARK_THEME_FOREGROUND}),Object.defineProperty(y,"ACGI_LIGHT_THEME_FOREGROUND",{enumerable:!0,get:()=>u.ACGI_LIGHT_THEME_FOREGROUND}),Object.defineProperty(y,"ACGI_MODEL_SPACE_BACKGROUND",{enumerable:!0,get:()=>u.ACGI_MODEL_SPACE_BACKGROUND}),Object.defineProperty(y,"ACGI_PAPER_SPACE_BACKGROUND",{enumerable:!0,get:()=>u.ACGI_PAPER_SPACE_BACKGROUND}),Object.defineProperty(y,"acgiContrastingForegroundColor",{enumerable:!0,get:()=>u.acgiContrastingForegroundColor}),Object.defineProperty(y,"acgiForegroundColorForBackground",{enumerable:!0,get:()=>u.acgiForegroundColorForBackground}),Object.defineProperty(y,"acgiIsLightBackground",{enumerable:!0,get:()=>u.acgiIsLightBackground}),Object.defineProperty(y,"AcGiTextParagraphAlignment",{enumerable:!0,get:()=>D.MTextParagraphAlignment}),Object.defineProperty(y,"MTextColor",{enumerable:!0,get:()=>D.MTextColor}),Object.defineProperty(y,"MTextParagraphAlignment",{enumerable:!0,get:()=>D.MTextParagraphAlignment}),Object.defineProperty(y,"ShxParserFont",{enumerable:!0,get:()=>D.ShxParserFont}),y.ACAP_UNTITLED_DOC_TITLE=Po,y.AcApAboutCmd=Ou,y.AcApArcCmd=bc,y.AcApBlockInsertSession=qn,y.AcApBlockPreviewConvertor=Tr,y.AcApCacheFontCmd=Ki,y.AcApCircleCmd=Pc,y.AcApCircleJig=Fr,y.AcApClearMarkupsCmd=lu,y.AcApClearMeasurementsCmd=hd,y.AcApContext=Mh,y.AcApConvertToDxfCmd=$l,y.AcApConvertToPngCmd=Xl,y.AcApCopyCmd=ws,y.AcApDimJig=Ac,y.AcApDimLinearCmd=Cc,y.AcApDocManager=k,y.AcApDocument=lh,y.AcApDrawStyleToolbar=oh,y.AcApDxfConvertor=Wl,y.AcApEllipseCmd=Tc,y.AcApEntityPreviewCmd=Ql,y.AcApEntityPreviewConvertor=ql,y.AcApEntityService=Ir,y.AcApEraseCmd=_u,y.AcApExamplePlugin=cb,y.AcApFontLoader=dh,y.AcApFontUtil=$i,y.AcApHatchCmd=Xn,y.AcApHideObjectsCmd=Eu,y.AcApI18n=d,y.AcApImageAttachCmd=Ic,y.AcApInsertCmd=Dc,y.AcApLayerCloseCmd=uc,y.AcApLayerCmd=hc,y.AcApLayerCurCmd=sc,y.AcApLayerDelCmd=nc,y.AcApLayerFreezeCmd=Vn,y.AcApLayerIsoCmd=Gn,y.AcApLayerLockCmd=rc,y.AcApLayerOnCmd=oc,y.AcApLayerPCmd=ac,y.AcApLayerService=te,y.AcApLayerStore=ec,y.AcApLayerThawCmd=lc,y.AcApLayerUnisoCmd=cc,y.AcApLayerUnlockCmd=dc,y.AcApLayoffCmd=Kn,y.AcApLineCmd=St,y.AcApLineJig=Wn,y.AcApLogCmd=ju,y.AcApMLineCmd=jc,y.AcApMLineJig=Oc,y.AcApMTextCmd=Bc,y.AcApMarkupArrowCmd=cu,y.AcApMarkupCalloutCmd=du,y.AcApMarkupCalloutEntity=eu,y.AcApMarkupCircleCmd=uu,y.AcApMarkupCloudCmd=hu,y.AcApMarkupEntity=Lt,y.AcApMarkupExportCmd=bu,y.AcApMarkupHighlightCmd=pu,y.AcApMarkupHighlightEntity=tu,y.AcApMarkupHistory=sa,y.AcApMarkupImportCmd=wu,y.AcApMarkupLineCmd=vu,y.AcApMarkupPresenter=ou,y.AcApMarkupRectCmd=ku,y.AcApMarkupSegmentEntity=iu,y.AcApMarkupShapeEntity=nu,y.AcApMarkupStampCmd=Su,y.AcApMarkupStampEntity=su,y.AcApMarkupStore=Wo,y.AcApMarkupTextCmd=Pu,y.AcApMarkupTextEntity=ru,y.AcApMarkupVisibilityCmd=Cu,y.AcApMeasureAngleCmd=_d,y.AcApMeasureAngleEntity=Ii,y.AcApMeasureArcCmd=Md,y.AcApMeasureArcEntity=Mi,y.AcApMeasureAreaCmd=Ld,y.AcApMeasureAreaEntity=Di,y.AcApMeasureDistanceCmd=jd,y.AcApMeasureDistanceEntity=Oi,y.AcApMeasureDistanceJig=Od,y.AcApMeasureEntity=ti,y.AcApMeasurePointCmd=Fd,y.AcApMeasurePointEntity=ji,y.AcApMeasurementExportCmd=Pd,y.AcApMeasurementHistory=aa,y.AcApMeasurementImportCmd=Ad,y.AcApMeasurementVisibilityCmd=pd,y.AcApMemoryProfiler=mf,y.AcApMoveCmd=Tu,y.AcApOffsetCmd=Vi,y.AcApOpenCmd=Vu,y.AcApOpenFileProfiler=Cs,y.AcApOpenViewMode=Wi,y.AcApOverlayEntity=so,y.AcApPanCmd=Zu,y.AcApPluginManager=Xu,y.AcApPngConvertor=Yl,y.AcApPointCmd=Fc,y.AcApPolygonCmd=Qn,y.AcApPolylineCmd=Vc,y.AcApPolylineJig=Rc,y.AcApProgress=Ui,y.AcApQNewCmd=Gu,y.AcApRayCmd=Kc,y.AcApRectCmd=es,y.AcApRectJig=Hc,y.AcApRedoCmd=Yu,y.AcApRegenCmd=Ku,y.AcApRevCloudCmd=ts,y.AcApRevCloudJig=ed,y.AcApRotateCmd=ks,y.AcApSelectCmd=Uu,y.AcApSessionUndo=ra,y.AcApSettingManager=we,y.AcApSketchCmd=rs,y.AcApSketchJig=nd,y.AcApSplineCmd=rd,y.AcApSplineJig=sd,y.AcApSwitchBgCmd=Wu,y.AcApSysVarCmd=Hu,y.AcApUndoCmd=$u,y.AcApUnisolateObjectsCmd=Du,y.AcApXAttachCmd=cd,y.AcApXLineCmd=dd,y.AcApXrefManager=It,y.AcApZoomCmd=Tt,y.AcEdBaseView=Ul,y.AcEdBatchedPreview=Cr,y.AcEdCommand=z,y.AcEdCommandLine=Bl,y.AcEdCommandStack=ce,y.AcEdConditionWaiter=yr,y.AcEdCorsorType=Ce,y.AcEdCursorManager=xl,y.AcEdGripEditSession=bl,y.AcEdGripHandle=En,y.AcEdGripManager=kl,y.AcEdGripPreviewJig=fl,y.AcEdHoverController=Gl,y.AcEdInputManager=zn,y.AcEdKeyword=wr,y.AcEdKeywordCollection=Ml,y.AcEdMTextEditor=Ke,y.AcEdMarker=_n,y.AcEdMarkerManager=br,y.AcEdOpenMode=F,y.AcEdOsnapResolver=Ut,y.AcEdPreviewJig=G,y.AcEdPromptAngleOptions=xe,y.AcEdPromptBoxOptions=In,y.AcEdPromptBoxResult=Mn,y.AcEdPromptDistanceOptions=be,y.AcEdPromptDoubleOptions=ie,y.AcEdPromptDoubleResult=Se,y.AcEdPromptEntityOptions=He,y.AcEdPromptEntityResult=On,y.AcEdPromptIntegerOptions=kr,y.AcEdPromptIntegerResult=jn,y.AcEdPromptKeywordOptions=ne,y.AcEdPromptNumericalOptions=Dn,y.AcEdPromptNumericalResult=vr,y.AcEdPromptOptions=Ue,y.AcEdPromptPointOptions=I,y.AcEdPromptPointResult=Bn,y.AcEdPromptResult=Ie,y.AcEdPromptSelectionOptions=xt,y.AcEdPromptSelectionResult=ki,y.AcEdPromptStateMachine=We,y.AcEdPromptStatus=b,y.AcEdPromptStringOptions=le,y.AcEdSelectionFilter=Hm,y.AcEdSelectionSet=Tn,y.AcEdSelectionStaticPreviewJig=Vl,y.AcEdSelectionTransformPreviewJig=Wt,y.AcEdViewKeyHandler=vn,y.AcEdViewMode=me,y.AcEditor=Rl,y.AcTrGeometryUtil=Eo,y.AcTrInheritedLayerMaterialMapper=Xa,y.AcTrLayerAppearanceController=Qa,y.AcTrScene=ol,y.AcTrView2d=Yi,y.AcUiAboutDialog=Ss,y.AcUiDialog=xs,y.DEFAULT_VIEW_2D_OPTIONS=Io,y.DWG_CONVERTER_PACKAGE=Vf,y.DWG_PARSER_MAIN_FILE=zf,y.DWG_PARSER_WORKER_FILE=Ff,y.ENTITY_EDIT_LABEL=Ja,y.LAYER_EDIT_LABEL=H,y.LAYER_FROZEN_FLAG=ar,y.LAYER_LOCKED_FLAG=Nt,y.LIBREDWG_CONVERTER_PACKAGE=Nf,y.LIBREDWG_PARSER_WASM_FILE=Bf,y.LIBREDWG_PARSER_WORKER_FILE=jf,y.MARKUP_FONT_SIZE=zd,y.MARKUP_LAYER=an,y.MARKUP_LINE_WEIGHT=ds,y.MARKUP_LIVE_LAYER=ae,y.MARKUP_OPEN_MODE=Yd,y.MARKUP_STATUSES=$o,y.MEASUREMENT_ANGLE_FORMAT_OPTIONS=qo,y.MEASUREMENT_FONT_SIZE=Ot,y.MEASUREMENT_LAYER=Y,y.MEASUREMENT_LENGTH_FORMAT_OPTIONS=Xo,y.MEASUREMENT_LINE_WEIGHT=Dt,y.MEASUREMENT_LIVE_LAYER=ue,y.MLIGHTCAD_BRAND_NAME=tn,y.MLIGHTCAD_DOCS_URL=No,y.MLIGHTCAD_ICON_SVG=Fo,y.MLIGHTCAD_REPO_URL=Ro,y.MLIGHTCAD_WEBSITE_URL=zo,y.ML_UI_COMPACT_MAX_WIDTH=yl,y.ML_UI_COMPACT_MEDIA_QUERY=gl,y.ML_UI_MOBILE_MAX_WIDTH=pl,y.ML_UI_MOBILE_MEDIA_QUERY=ml,y.MTEXT_RENDERER_PACKAGE=Rf,y.MTEXT_RENDERER_WORKER_FILE=bh,y.POLARMODE_ADDITIONAL_ANGLES=Al,y.POLARMODE_POLAR_TRACKING=Ht,y.REVCLOUD_BULGE=Yr,y.REVIEW_OVERLAY_HIT_THRESHOLD_PX=Aa,y.acapBindCommandServices=hl,y.acapBindOverlayCalloutGrips=cs,y.acapBindOverlayPointerDrag=_t,y.acapCloneMeasurementStyle=li,y.acapColorToCssAlpha=Ws,y.acapCommandServices=wi,y.acapCreateMlightcadBrandMark=Vo,y.acapCreateMlightcadIcon=Ds,y.acapCssColor=ge,y.acapCssToMeasurementColor=$s,y.acapDrawOverlayArrowHead=ls,y.acapDrawOverlayHighlight=no,y.acapDrawOverlayLeader=io,y.acapDrawStyleKindForCommand=Qu,y.acapFitOverlayCanvas=Ct,y.acapGetCurrentMeasurementStyle=at,y.acapGetMeasurementColor=Je,y.acapGetMeasurementFontSize=wt,y.acapGetMeasurementLineWeight=jt,y.acapInstallOpenFileDialog=mh,y.acapIsDrawStyleHostRibbonVisible=eh,y.acapIsDrawStyleToolbarVisible=wf,y.acapMeasurementCanvasLineWidth=Ve,y.acapNotifyUndoStackChanged=lt,y.acapPlaceOverlayHtml=Ye,y.acapPointerEventToOverlayWorld=ro,y.acapResetMeasurementDrawStyle=Zh,y.acapRunDatabaseEdit=ct,y.acapRunServiceEdit=K,y.acapSetDrawStyleHostHasRibbon=bf,y.acapSetDrawStyleToolbarVisible=xo,y.acapSetMeasurementDrawColor=ea,y.acapSetMeasurementDrawFontSize=ia,y.acapSetMeasurementDrawLineWeight=ta,y.acapShouldShowDrawStyleToolbar=th,y.acapSubscribeDrawStyleToolbarVisibility=vf,y.acapUninstallOpenFileDialog=gh,y.acapUpdateOpenFileDialogOptions=yh,y.acapWithSecondaryDatabase=Qr,y.accumulateSketchPoint=td,y.acedAlert=am,y.acedApplyUiTheme=gr,y.acedIsCompactUiLayout=dm,y.acedIsMobileUiLayout=cm,y.applyMarkupStyleToSelection=bs,y.applyMeasurementStyle=er,y.applyMeasurementStyleToSelection=un,y.applySessionHiddenObjectState=ab,y.bindMarkupCalloutGrips=Wg,y.bindMarkupCenterMove=Ri,y.bindMarkupInlineTextEdit=Cn,y.bindMarkupPointerDrag=Hg,y.bindMeasurementOverlayHistory=ua,y.bindOverlayHistory=na,y.buildMarkupCloud=Dg,y.buildMarkupRect=Og,y.buildRevCloud=qc,y.canvasBackgroundFromColor=Wa,y.clearLayoutMeasurements=ud,y.cmdDescription=xr,y.collectMeasurementRecords=va,y.collectMemorySnapshot=Ru,y.collectReviewOverlayIdsByBox=Ea,y.commitMarkup=ze,y.commitMeasurementGroup=xa,y.computeLeaderTipOnShape=ni,y.configureMarkupCommand=Be,y.constrainToOrtho=Pl,y.constrainToTracking=Il,y.createDefaultMarkupColor=co,y.createMarkupEntity=Rg,y.createMarkupEntityFromRecord=fs,y.createMarkupId=Hd,y.createMarkupMeta=Fe,y.createMeasureEntityFromRecord=xd,y.createRotationMatrix=$t,y.cssToMarkupColor=mo,y.cursorColorForBackground=bn,y.defaultMarkupColor=ee,y.defaultMarkupStyle=us,y.defaultRevCloudArcLength=$c,y.deserializeMeasurementStyle=ha,y.distPointToArcPx=Bs,y.distPointToCirclePx=js,y.distPointToPolylinePx=Os,y.distPointToRectOutlinePx=nn,y.distPointToSegmentPx=bt,y.distance2d=Pt,y.drawMeasureAngleArcOnCanvas=yd,y.drawMeasureArcOnCanvas=fd,y.drawMeasureAreaOnCanvas=gd,y.drawMeasureSegmentOnCanvas=md,y.editMarkupHtmlText=pr,y.ensureCounterClockwise=Zc,y.eventBus=Q,y.foregroundColorFromColorTheme=zp,y.formatMeasurementAngle=ln,y.formatMeasurementLength=Te,y.formatMeasurementValue=Ks,y.formatMemoryBytes=Bu,y.geBox2dToThreeBox2d=Ch,y.geBox2dToThreeBox3d=Eh,y.geBox3dToGeBox2d=Sh,y.geBox3dToThreeBox3d=Ph,y.getActiveMeasurementStyle=ba,y.getDrawingExportBaseName=Hl,y.getEffectiveMeasurementUnits=Gs,y.getLastFontLoadStats=ch,y.getLayerIsoState=lr,y.getMarkupAuthor=$d,y.getMarkupFontSize=tt,y.getMarkupHistory=fe,y.getMarkupLineWeight=Pe,y.getMarkupPresenter=it,y.getMarkupStore=U,y.getMeasurementGeometry=tr,y.getMeasurementHistory=Qe,y.getMeasurementStyle=kt,y.getMeasurementUnitOverride=Wh,y.getPolaraddang=El,y.getPolarang=_l,y.getPolarmode=Ln,y.getSessionUndo=vt,y.hideObjects=Dh,y.hitTestMarkupGeometry=zs,y.hitTestMeasurementGeometry=Vs,y.isDirectBatchCandidate=Vp,y.isEffectiveSpatialQueryHit=xn,y.isInsertableBlockName=Mc,y.isLightColorTheme=Np,y.isMarkupDoublePointer=ul,y.isMarkupHtmlTextEditing=dl,y.isMarkupShapeCalloutEnabled=jg,y.isMarkupVisible=of,y.isMeasurementVisible=Js,y.isModelSpaceDatabase=Ha,y.isOpenFileProgressComplete=fh,y.isOrthoModeEnabled=Sl,y.isPolarTrackingEnabled=Ll,y.isRevCloudCloseToStart=Xr,y.isSameLayerIsoState=qa,y.isScriptQuitCommand=ah,y.layoutBackgroundSysVar=or,y.markupCanvasLineWidth=je,y.markupCloudVertices=zi,y.markupColorToCss=Et,y.markupDrawStyleFromRecord=Xd,y.markupGeometryBounds=Ho,y.markupGeometryCenter=rn,y.markupNow=Wd,y.markupRectCorners=qd,y.markupSidecarFileName=fu,y.measureAngleDeg=vd,y.measureCentroid=to,y.measureShoelaceArea=wd,y.measureShortArcLength=bd,y.measureShortArcMid=eo,y.measurementGeometryBounds=Zo,y.measurementSidecarFileName=ya,y.migrateStoredSettings=qu,y.parseMarkupSidecar=yu,y.parseMeasurementSidecar=pa,y.parseScriptLines=So,y.pickMeasurementAt=Sa,y.placeAngleMeasurement=Cd,y.placeArcMeasurement=Id,y.placeAreaMeasurement=Ed,y.placeDistanceMeasurement=Dd,y.placeMarkupHtml=Ug,y.placeMeasurementRecord=Sd,y.placePointMeasurement=Bd,y.pointInPolygonPx=Ko,y.pointInRectPx=Go,y.pointerEventToMarkupWorld=Kg,y.promptAttachedCallout=gs,y.promptMarkupCapsuleText=hs,y.promptMarkupText=yo,y.promptShapeFirstCorner=ys,y.publishAttachedCallout=Qd,y.readLayoutBackgroundColor=fn,y.rectanglePath=Zr,y.refreshMeasurementValueLabels=op,y.registerMarkupPublish=Zd,y.republishMarkup=Fi,y.resetExportDownloadNamesForTests=Wm,y.resetMarkupSession=au,y.resetMeasurementSession=da,y.resetMeasurementStyleState=ka,y.resetMeasurementUnitOverride=Jo,y.resetMeasurementVisibility=ga,y.resolveExportDownloadName=Lr,y.resolvePointerSelectionAction=Kl,y.resolveSelectedEntities=Rn,y.resolveSelectedIds=ic,y.resolveSelectionActionFromEvent=_r,y.resolveUiTheme=fr,y.runMarkupEdit=ve,y.runMeasurementEdit=Bt,y.sampleEntityPath=Qc,y.scaleCopyDisplacement=Nn,y.selectMarkupGroup=Ni,y.serializeMeasurementStyle=dt,y.setMarkupDrawColor=Gd,y.setMarkupDrawFontSize=Ud,y.setMarkupDrawLineWeight=Kd,y.setMarkupShapeCalloutEnabled=Bg,y.setMarkupVisible=Au,y.setMeasurementUnitOverride=$h,y.setMeasurementVisible=fa,y.shouldExtendBboxForDirectEntity=Za,y.signedArea=Yc,y.simplifySketchPoints=id,y.stringifyMarkupSidecar=gu,y.stringifyMeasurementSidecar=ma,y.strokeMarkupCloud=Jd,y.subscribeMarkupDrawStyle=po,y.subscribeMeasurementSelection=sp,y.sysCmdDescription=jm,y.tessellateMarkupCloud=ms,y.threeBox2dToGeBox2d=Ah,y.threeBox3dToGeBox2d=_h,y.threeBox3dToGeBox3d=xh,y.toggleBlackWhiteBackgroundColor=$a,y.togglePolarTracking=xm,y.translateAttachedCallout=sn,y.translateMarkupGeometry=Fs,y.translateMarkupPoint=oe,y.tryBuildDirectEntityMeta=Ya,y.trySelectReviewOverlay=La,y.trySelectReviewOverlaysByBox=Ta,y.unionSpatialQueryItems=kn,y.uniquifySpatialItemIds=el,y.unisolateObjects=Oh,y.userCmdDescription=Bm,y.viewDiagonalLength=Wc,y.withMarkupInput=Ze,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
982
+ `.trim(),t=document.createElement("style");t.id=lt.styleId,t.textContent=e,document.head.appendChild(t),lt.stylesInjected=!0}};lt.styleId="ml-ccl-loader-styles",lt.stylesInjected=!1;let Hi=lt;class ob{constructor(e){this._refCount=0,this._message="",this._progress=new Hi({host:e}),this._progress.hide()}show(e){e!==void 0?this._message=e:this._refCount===0&&(this._message=""),this._refCount++,this._refCount===1?(this._progress.setMessage(this._message),this._progress.show(),this.emitEvent(!0)):e!==void 0&&(this._progress.setMessage(e),this.emitEvent(!0))}hide(){this._refCount<=0||(this._refCount--,this._refCount===0&&(this._message="",this._progress.hide(),this.emitEvent(!1)))}setMessage(e){this._message=e,this._refCount>0&&(this._progress.setMessage(e),this.emitEvent(!0))}async withBusyIndicator(e,t){this.show(t);try{return await d.accmYieldForPaint(),await e()}finally{this.hide()}}emitEvent(e){ee.emit("busy-indicator",{visible:e,message:e&&this._message||void 0})}}const Io="Untitled";class xh{constructor(){this._fileName="",this._docTitle="",this._openMode=F.Write,this._hiddenObjects=new Set,this._database=new d.AcDbDatabase,this.docTitle=Io,this._openMode=F.Write}async openUri(e,t){this._uri=e,this._openMode=(t==null?void 0:t.mode)??F.Read,this._fileName=this.getFileNameFromUri(e);const i=this._database.lastOpenError;let n=!0;try{const r={...t,readOnly:this._openMode===F.Read};await this._database.openUri(e,r),this.docTitle=this._fileName}catch{n=!1,this.emitOpenFileFailed(e,i)}return n}async openDocument(e,t,i){var o;let n=!0;this._fileName=e,this._openMode=(i==null?void 0:i.mode)??F.Read;const r=this._database.lastOpenError;try{const a=(o=e.split(".").pop())==null?void 0:o.toLocaleLowerCase(),l={...i,readOnly:this._openMode===F.Read};await this._database.read(t,l,a=="dwg"?d.AcDbFileType.DWG:d.AcDbFileType.DXF),this.docTitle=this._fileName}catch{n=!1,this.emitOpenFileFailed(e,r)}return n}resetNewDocumentIdentity(){this._uri=void 0,this._fileName="",this.docTitle=Io}get uri(){return this._uri}get database(){return this._database}get fileName(){return this._fileName}get docTitle(){return this._docTitle}set docTitle(e){this._docTitle=e}get openMode(){return this._openMode}isObjectHidden(e){return this._hiddenObjects.has(e)}addHiddenObject(e){this._hiddenObjects.add(e)}takeHiddenObjects(){const e=[...this._hiddenObjects];return this._hiddenObjects.clear(),e}get layerService(){return this._layerService||(this._layerService=new te(this._database)),this._layerService}get entityService(){return this._entityService||(this._entityService=new zr(this._database)),this._entityService}get layerStore(){return this._layerStore||(this._layerStore=new dc(this)),this._layerStore}destroy(){var e;(e=this._layerStore)==null||e.destroy(),this._layerStore=void 0,this._layerService=void 0,this._entityService=void 0,this.clearLayerPreviousState(),this.clearLayerIsoSnapshot(),this._hiddenObjects.clear()}captureLayerPreviousState(){const e=this._database;this._layerPreviousSnapshot={clayer:e.clayer,states:[...e.tables.layerTable.newIterator()].map(t=>({name:t.name,isOn:!t.isOff,isFrozen:t.isFrozen,isLocked:((t.standardFlags??0)&Rt)!==0}))}}getLayerPreviousSnapshot(){return this._layerPreviousSnapshot}clearLayerPreviousState(){this._layerPreviousSnapshot=void 0}setLayerIsoSnapshot(e){this._layerIsoSnapshot=e}consumeLayerIsoSnapshot(){const e=this._layerIsoSnapshot;return this._layerIsoSnapshot=void 0,e}clearLayerIsoSnapshot(){this._layerIsoSnapshot=void 0}restoreLayerPreviousState(){const e=this._layerPreviousSnapshot;return e?U(this._database,H,()=>te.applyLayerPreviousSnapshot(this._database,e)):!1}isolateLayers(e,t){const i=this.layerService.isolateLayers(e,t);if(i)return this._layerIsoSnapshot=i.isoSnapshot,{layerNames:i.layerNames,affectedLayerCount:i.affectedLayerCount}}unisolateLayers(){const e=this.consumeLayerIsoSnapshot();if(e)return this.layerService.unisolateFromSnapshot(e)}emitOpenFileFailed(e,t=null){const i=this._database.lastOpenError,n=i!=null&&i!==t;ee.emit("failed-to-open-file",{fileName:e,...n&&{errorCode:i.code,errorMessage:i.message}})}getFileNameFromUri(e){try{const i=new URL(e).pathname.split("/");return i[i.length-1]||""}catch(t){return d.log.error("Invalid URI:",t),""}}}let Wi=null;function Sh(){return Wi?{...Wi}:null}function ab(s){const e=String(s.type??"").toLowerCase();if(e==="mesh"||e==="ttf"||e==="otf"||e==="woff")return!0;const t=String(s.file??"").toLowerCase();return t.endsWith(".ttf")||t.endsWith(".otf")||t.endsWith(".woff")||t.endsWith(".woff2")}class Ph{constructor(){this.deferMeshFonts=!0,this._loadChain=Promise.resolve(),this._loader=new M.AcTrFontLoader}get baseUrl(){return this._loader.baseUrl}set baseUrl(e){this._loader.baseUrl=e}get avaiableFonts(){return this._loader.avaiableFonts}async getAvaiableFonts(){return await this._loader.getAvailableFonts()}async load(e){const t=()=>this.loadInternal(e),i=this._loadChain.then(t,t);return this._loadChain=i.then(()=>{},()=>{}),i}async loadInternal(e){const t=performance.now();let i=[];const n=[],r=[];let o=0,a=0,l=0;try{const c=performance.now(),h=await this._loader.getAvailableFonts();o=performance.now()-c;const p=new Map;for(const w of h)for(const v of w.name)p.set(v.toLowerCase(),w);for(const w of e){const v=w.toLowerCase(),x=p.get(v);this.deferMeshFonts&&x&&ab(x)?r.push(w):n.push(w)}const m=this.deferMeshFonts&&r.length>0&&n.length>0,g=performance.now();if(i=n.length>0?await this._loader.load(n):[],a=performance.now()-g,r.length>0&&!m){const w=performance.now(),v=await this._loader.load(r);l=performance.now()-w,i=[...i,...v]}else m&&(l=null);const f={fontCount:e.length,criticalFonts:[...n],deferredFonts:[...r],metaMs:o,criticalLoadMs:a,deferredLoadMs:l,deferred:m,totalMs:performance.now()-t};if(Wi=f,m&&r.length>0){const w=performance.now();this._loader.load(r).then(v=>{Wi===f&&(f.deferredLoadMs=performance.now()-w),this.emitPartialFailures(v)},v=>{Wi===f&&(f.deferredLoadMs=performance.now()-w),lb(v)})}}catch(c){throw new d.AcDbOpenDatabaseError(c instanceof Error?c.message:String(c),"font_load_failed",{cause:c})}this.emitPartialFailures(i)}emitPartialFailures(e){const t=[],i=[];e.forEach(n=>{n.status==="NotFound"?t.push(n.fontName):n.status==="FailedToLoad"&&i.push({fontName:n.fontName,url:n.url})}),t.length>0&&ee.emit("fonts-not-found",{fonts:t}),i.length>0&&ee.emit("fonts-not-loaded",{fonts:i})}}function lb(s){console.warn("[AcApFontLoader] Deferred mesh font load failed; text may use SHX fallbacks.",s)}const Ah=[".dxf",".dwg"];let ge,Ls=!1,Ts={};const cb=s=>{const e=s.toLowerCase();return Ah.some(t=>e.endsWith(t))},db=s=>new Promise((e,t)=>{const i=new FileReader;i.onload=()=>e(i.result),i.onerror=()=>t(i.error??new Error("Failed to read file")),i.readAsArrayBuffer(s)}),ub=async s=>s?s():{minimumChunkSize:1e3},Ch=()=>{ge||(ge=document.createElement("input"),ge.type="file",ge.accept=Ah.join(","),ge.style.display="none",ge.addEventListener("change",_h),document.body.appendChild(ge)),ge.click()},_h=async s=>{var n;const e=s.target,t=(n=e.files)==null?void 0:n[0];if(e.value="",!t)return;if(!cb(t.name)){d.log.warn(`Unsupported file type: ${t.name}`);return}let i=null;try{i=await db(t);const{AcApDocManager:r}=await Promise.resolve().then(()=>Cb),o=await ub(Ts.getOpenDocumentDefaults);ee.emit("open-local-file-started",{mode:o.mode??F.Read}),await r.instance.openDocument(t.name,i,o)}catch(r){d.log.error("Failed to open selected file:",r)}finally{i=null}};function Eh(s={}){s.enabled!==!1&&(Ts=s,!Ls&&(ee.on("open-file",Ch),Ls=!0))}function Lh(s){Ts=s}function Th(){Ls&&(ee.off("open-file",Ch),ge==null||ge.removeEventListener("change",_h),ge==null||ge.remove(),ge=void 0,Ls=!1,Ts={})}const oi=class oi{constructor(){this._active=!1,this._printToConsole=!1,this._t0=0,this._readEndMs=0,this._stages=new Map,this._activeStageStartedAt=0,this._finishScheduled=!1}static getLastSnapshot(){return oi._lastSnapshot}static isEnabled(e){try{return d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.OPENPROF,e)===!0}catch{return!1}}begin(e){this.cancel(),this._active=!0,this._printToConsole=oi.isEnabled(e),this._finishScheduled=!1,this._t0=performance.now(),this._readEndMs=0,this._stages.clear(),this._activeStage=void 0,this._activeStageStartedAt=0,this._database=e,d.AcDbRenderingCache.resetProfile(),d.AcDbRenderingCache.profiling=!0,this._progressListener=t=>{this.onProgress(t)},e.events.openProgress.addEventListener(this._progressListener)}markReadCompleteAndScheduleReport(e){this._active&&(this._readEndMs=performance.now(),this.scheduleReport(e))}cancel(){this.detachProgressListener(),this._active&&(d.AcDbRenderingCache.profiling=!1),this._active=!1,this._printToConsole=!1,this._finishScheduled=!1,this._database=void 0,this._activeStage=void 0,this._stages.clear()}onProgress(e){const t=String(e.subStage??e.stage??"UNKNOWN"),i=performance.now();if(this._activeStage==null){this._activeStage=t,this._activeStageStartedAt=i;return}t!==this._activeStage&&(this.closeActiveStage(i),this._activeStage=t,this._activeStageStartedAt=i)}closeActiveStage(e){if(this._activeStage==null)return;let t=this._stages.get(this._activeStage);t||(t={durationMs:0},this._stages.set(this._activeStage,t)),t.durationMs+=Math.max(0,e-this._activeStageStartedAt),this._activeStage=void 0}scheduleReport(e){!this._active||this._finishScheduled||(this._finishScheduled=!0,this.waitForIdle(e).then(()=>{this._active&&(this.publishReport(performance.now(),e),this.cancel())}).catch(t=>{d.log.warn("OPENPROF: failed to finish open profile",t),this.cancel()}))}async waitForIdle(e){await Promise.resolve(),e.isProcessingEntities&&await new Promise(t=>{const i=()=>{if(!e.isProcessingEntities){t();return}setTimeout(i,16)};i()})}publishReport(e,t){var P,A,_;this.closeActiveStage(this._readEndMs>0?this._readEndMs:e);const i=Math.max(0,this._readEndMs-this._t0),n=Math.max(0,e-this._readEndMs),r=Math.max(0,e-this._t0),o=((P=this._stages.get("PARSE"))==null?void 0:P.durationMs)??0,a=((A=this._stages.get("ENTITY"))==null?void 0:A.durationMs)??0,l={...d.AcDbRenderingCache.profileStats},c=l.topLevel,h=t.progressiveOpenStats,p=t.progressiveRendering,m=[...l.blockMisses].sort((C,O)=>O.buildMs+O.compactMs-(C.buildMs+C.compactMs)).slice(0,10).map(C=>({blockName:C.blockName,buildMs:C.buildMs,compactMs:C.compactMs})),g=[...this._stages.entries()].filter(([,C])=>C.durationMs>0).sort((C,O)=>O[1].durationMs-C[1].durationMs).map(([C,O])=>({name:C,durationMs:O.durationMs})),f={collectedAt:Date.now(),fileName:(_=this._database)==null?void 0:_.dwgname,totalMs:r,readMs:i,convertMs:n,parseMs:o,entityMs:a,stages:g,cache:{hits:l.hits,misses:l.misses,hitMs:l.hitMs,cloneMs:l.cloneMs,missBuildMs:l.missBuildMs,missCompactMs:l.missCompactMs,setCloneMs:l.setCloneMs,applyMs:l.applyMs,topLevel:{...c}},slowBlocks:m,progressive:{enabled:p,paintCount:h.paintCount,yieldCount:h.yieldCount}};if(oi._lastSnapshot=f,!this._printToConsole)return;const w=(C,O)=>O<=0?"0%":`${(C/O*100).toFixed(1)}%`,v=["","========== OPENPROF (open-file profile) ==========","Note: progress-bar % weights (PARSE~12%, ENTITY~98%) are not wall-time shares.","Stage ms = active-stage wall time (first event of stage → first event of next stage).",`progressive: ${p?"on":"off"} (mid-open paints=${h.paintCount}, yields=${h.yieldCount})`,`wall clock total: ${r.toFixed(0)} ms`,` db.read: ${i.toFixed(0)} ms (${w(i,r)})`,` PARSE: ${o.toFixed(0)} ms (${w(o,i)} of read)`,` ENTITY flush: ${a.toFixed(0)} ms (${w(a,i)} of read)`,` scene convert: ${n.toFixed(0)} ms (${w(n,r)})`],x=Sh();if(x&&v.push(` explicit font load: critical=${x.criticalLoadMs.toFixed(0)}ms meta=${x.metaMs.toFixed(0)}ms deferredMesh=${x.deferred?"yes":"no"} (critical=[${x.criticalFonts.join(",")}] deferred=[${x.deferredFonts.join(",")}])`),v.push("","--- AcDbRenderingCache (top-level INSERT draws) ---",`hits: ${c.hits}, hit path ${c.hitMs.toFixed(0)} ms (clone ${c.cloneMs.toFixed(0)} ms)`,`misses: ${c.misses}, build ${c.missBuildMs.toFixed(0)} ms (incl. nested), compact ${c.missCompactMs.toFixed(0)} ms, set/clone ${c.setCloneMs.toFixed(0)} ms`,`applyMatrix+attribs: ${c.applyMs.toFixed(0)} ms`,"",`--- AcDbRenderingCache (all depths: hits=${l.hits}, misses=${l.misses}) ---`,`hit ${l.hitMs.toFixed(0)} ms (clone ${l.cloneMs.toFixed(0)}), build ${l.missBuildMs.toFixed(0)}, compact ${l.missCompactMs.toFixed(0)}, set ${l.setCloneMs.toFixed(0)}, apply ${l.applyMs.toFixed(0)}`),m.length>0){v.push("","--- Slowest block template misses (build+compact) ---");for(const C of m){const O=C.blockName.length>40?`${C.blockName.slice(0,37)}...`:C.blockName;v.push(`${O.padEnd(40)} build=${C.buildMs.toFixed(0).padStart(7)}ms compact=${C.compactMs.toFixed(0).padStart(7)}ms total=${(C.buildMs+C.compactMs).toFixed(0).padStart(7)}ms`)}}const S=g.filter(C=>!["PARSE","FONT","ENTITY","START","END"].includes(C.name));if(S.length>0){v.push("","--- Other openProgress sub-stages ---");for(const C of S)v.push(` ${C.name}: ${C.durationMs.toFixed(0)} ms`)}v.push("==================================================",""),console.log(v.join(`
983
+ `));try{const C=d.AcCmPerformanceCollector.getInstance();C.getAll().length>0&&(console.log("--- AcCmPerformanceCollector ---"),C.printAll())}catch{}}detachProgressListener(){this._progressListener&&this._database&&this._database.events.openProgress.removeEventListener(this._progressListener),this._progressListener=void 0}};oi._lastSnapshot=null;let Is=oi;function Ih(s){return s.percentage<100?!1:s.subStageStatus==="ERROR"?!0:s.subStageStatus!=="END"?!1:s.stage==="FETCH_FILE"||s.subStage==="END"}const ct=class ct{constructor(e){this._peak=0,this._overlayVisible=!1,this._lastMessage="",this._seeThrough=!1,this._progress=new Hi({host:e,overlayColor:ct.OVERLAY_DEFAULT}),this._progress.hide()}setSeeThroughOverlay(e){this._seeThrough=e,this._progress.setOverlayColor(e?ct.OVERLAY_SEE_THROUGH:ct.OVERLAY_DEFAULT)}setSceneBusyGate(e){this._sceneBusyGate=e}reset(){this.clearHoldPoll(),this._peak=0,this._stage=void 0,this._overlayVisible=!1,this._lastMessage=""}async beginOpen(e){this.handle({database:e,percentage:0,stage:"CONVERSION",subStage:"START",subStageStatus:"START"}),await d.accmYieldForPaint()}handle(e){const t=this.normalize(e);return ee.emit("open-file-progress",t),this.updateOverlay(t),t}normalize(e){const t=e.stage;return t!==this._stage&&(this._stage==="FETCH_FILE"&&t==="CONVERSION"&&(this._peak=0),this._stage=t),this._peak=Math.max(this._peak,e.percentage),{...e,percentage:this._peak}}resolveMessage(e){if(e.stage==="CONVERSION"){if(e.subStage){const t="main.progress."+e.subStage.replace(/_/g,"").toLowerCase();return u.t(t)}return}if(e.stage==="FETCH_FILE")return u.t("main.message.fetchingDrawingFile")}updateOverlay(e){var i;if(Ih(e)){if((i=this._sceneBusyGate)!=null&&i.call(this)){this.holdUntilSceneIdle();return}this.hideAndReset();return}this.clearHoldPoll(),this._overlayVisible||(this._progress.show(),this._overlayVisible=!0,this._seeThrough&&this._progress.setOverlayColor(ct.OVERLAY_SEE_THROUGH));const t=this.resolveMessage(e);t!=null&&t!==this._lastMessage&&(this._progress.setMessage(t),this._lastMessage=t)}holdUntilSceneIdle(){this._overlayVisible||(this._progress.show(),this._overlayVisible=!0),this._progress.setOverlayColor(ct.OVERLAY_SEE_THROUGH);const e=u.t("main.progress.rendering");if(e!==this._lastMessage&&(this._progress.setMessage(e),this._lastMessage=e),this._holdPollId!=null)return;const t=()=>{var i;if((i=this._sceneBusyGate)!=null&&i.call(this)){this._holdPollId=setTimeout(t,50);return}this._holdPollId=void 0,this.hideAndReset()};this._holdPollId=setTimeout(t,50)}hideAndReset(){this.clearHoldPoll(),this._progress.hide(),this.reset()}clearHoldPoll(){this._holdPollId!=null&&(clearTimeout(this._holdPollId),this._holdPollId=void 0)}};ct.OVERLAY_DEFAULT="rgba(0,0,0,0.45)",ct.OVERLAY_SEE_THROUGH="rgba(0,0,0,0.16)";let Mo=ct;const hb="libredwg-parser-worker.js",pb="libredwg-web.wasm",Mh="mtext-renderer-worker.js",mb="dwg-parser-worker.js",yb="dwg-parser-main.js",gb="@mlightcad/libredwg-converter",fb="@mlightcad/mtext-renderer",bb="@mlight-cad/dwg-converter",Dh={mtextRender:`./assets/${Mh}`};function wb(s){const e=[(s==null?void 0:s.mtextRender)??Dh.mtextRender];return s!=null&&s.dwgParser&&e.push(s.dwgParser),e.map(t=>String(t))}let Do,Oo;function vb(){Do=void 0,Oo=void 0}async function kb(s){try{const e=await fetch(s,{method:"HEAD"});if(e.ok)return!0;if(e.status===405){const t=await fetch(s,{headers:{Range:"bytes=0-0"}});return t.ok||t.status===206}return!1}catch{return!1}}async function Oh(s){const e=wb(s),t=e.join("|");if(Do===t&&Oo===!0)return!0;try{const n=(await Promise.all(e.map(kb))).every(Boolean);return n&&(Do=t,Oo=!0),n}catch{return!1}}class Dt{constructor(){this._sessions=new Map,this._nextId=1}static get instance(){return this._instance||(this._instance=new Dt),this._instance}get sessions(){return Array.from(this._sessions.values())}getSession(e){return this._sessions.get(e)}getSessionByBlockName(e){for(const t of this._sessions.values())if(t.blockName===e)return t}async attachOverlay(e){const t=this.getSessionByBlockName(e.blockName);t&&this.unload(t.id);let i;if(e.sourceDb)i=await k.instance.registerOverlayDatabase(e.sourceDb);else if(e.content)i=await k.instance.loadOverlay(e.fileName,e.content);else throw new Error("AcApXrefManager.attachOverlay requires sourceDb or content");const n=k.instance.getOverlayLayout(i);n&&e.transform&&xb(n,e.transform);const r={id:`xref-${this._nextId++}`,blockName:e.blockName,insertId:e.insertId,overlayId:i,sourcePath:e.sourcePath,visible:!0};return this._sessions.set(r.id,r),r}setVisible(e,t){const i=this._sessions.get(e);if(!i)return!1;const n=k.instance.setOverlayVisible(i.overlayId,t);return n&&(i.visible=t),n}setVisibleByBlockName(e,t){const i=this.getSessionByBlockName(e);return i?this.setVisible(i.id,t):!1}unload(e){const t=this._sessions.get(e);return t?(k.instance.removeOverlay(t.overlayId),this._sessions.delete(e),!0):!1}unloadByBlockName(e){const t=this.getSessionByBlockName(e);return t?this.unload(t.id):!1}clearAll(){for(const e of[...this._sessions.keys()])this.unload(e)}static createHostXrefInsert(e,t,i,n,r){const o=new d.AcDbBlockTableRecord({name:t,pathName:i,flags:d.AcDbBlockTableRecordFlag.Xref|d.AcDbBlockTableRecordFlag.Resolved|d.AcDbBlockTableRecordFlag.Referenced,...r?{origin:new d.AcGePoint3d(r)}:{}});e.tables.blockTable.add(o);const a=new d.AcDbBlockReference(t);return a.position=new d.AcGePoint3d(n.position),a.scaleFactors=new d.AcGePoint3d(n.scale,n.scale,n.scale),a.rotation=n.rotationRad,e.tables.blockTable.modelSpace.appendEntity(a),{record:o,insert:a}}}function xb(s,e){const t=s.internalObject;t.position.set(e.position.x,e.position.y,e.position.z??0),t.scale.set(e.scale,e.scale,e.scale),t.rotation.set(0,0,e.rotationRad)}var $i=(s=>(s.Extents="extents",s.Saved="saved",s))($i||{});const Sb="https://cdn.jsdelivr.net/gh/mlightcad/cad-data",Pb="templates/acadiso.dxf",Ab={ARC:["A"],CIRCLE:["C"],ELLIPSE:["EL"],ERASE:["E"],DIMLINEAR:["DLI"],MEASUREDISTANCE:["DI","DIST"],MEASUREAREA:["AA","AREA"],MEASUREANGLE:["ANG"],"-HATCH":["-H"],IMAGEATTACH:["IAT"],"-INSERT":["I"],XATTACH:["XA"],LAYER:["LA"],"-LAYER":["-LA"],LINE:["L"],MLINE:["ML"],MTEXT:["T"],MOVE:["M"],OFFSET:["O"],COPY:["CO"],ROTATE:["RO"],OPEN:["OP"],PAN:["P"],POINT:["PO"],POLYGON:["POL"],PLINE:["PL"],RAY:["RA"],RECTANG:["REC"],REGEN:["RE"],SELECT:["SE"],SPLINE:["SPL"],XLINE:["XL"],ZOOM:["Z"],UNDO:["U"],REDO:["REDO"]},Bh="modern";class k{constructor(e={}){var l;this._openFileProfiler=new Is,this._workersReady=null,this._overlays=new Map,this._nextOverlayId=1,this.events={documentToBeOpened:new d.AcCmEventManager,documentCreated:new d.AcCmEventManager,documentActivated:new d.AcCmEventManager,workersReady:new d.AcCmEventManager},this._baseUrl=e.baseUrl??Sb,this._commandAliasOverrides=this.normalizeCommandAliasConfig(e.commandAliases),this._openDocumentDefaults=e.openDocumentDefaults,e.useMainThreadDraw?M.AcTrMTextRenderer.getInstance().setRenderMode("main"):M.AcTrMTextRenderer.getInstance().setRenderMode("worker"),D.FontManager.instance.setDefaultFonts(Bh),D.FontManager.instance.lazyFontLoading=!0,D.FontManager.instance.awaitFontsBeforeDraw=!0,M.AcTrMTextRenderer.getInstance().setLazyFontLoading(!0),M.AcTrMTextRenderer.getInstance().setAwaitFontsBeforeDraw(!0);const t=new xh,i=((l=e.container)==null?void 0:l.getBoundingClientRect())??{width:300,height:150},n=()=>{var c;if(e.autoResize){const h=e.container;if(h)return{width:Math.max(1,Math.floor(h.clientWidth)),height:Math.max(1,Math.floor(h.clientHeight))};const p=(c=e.container)==null?void 0:c.getBoundingClientRect();return{width:Math.max(1,Math.floor((p==null?void 0:p.width)??i.width)),height:Math.max(1,Math.floor((p==null?void 0:p.height)??i.height))}}else return{width:e.width??i.width,height:e.height??i.height}},r=new Zi({container:e.container,calculateSizeCallback:n});this._context=new Wh(r,t),this._drawStyleToolbar=new vh(r),this._fontLoader=new Ph;const o=this.resolveFontsBaseUrl();this._fontLoader.baseUrl=o,D.FontManager.instance.baseUrl=o,d.acdbHostApplicationServices().workingDatabase=t.database,this._commandManager=new de,this.registerCommands(),this._pluginManager=new ch(this._context,this._commandManager);const a=e.busyIndicatorHost??r.container;this._openFileProgress=new Mo(a),this._openFileProgress.setSceneBusyGate(()=>this.curView.isProcessingEntities),this._busyIndicator=new ob(a),wl({showMessage:(c,h,p)=>this.editor.showMessage(c,h,p),showBusyIndicator:c=>this.showBusyIndicator(c),hideBusyIndicator:()=>this.hideBusyIndicator(),withBusyIndicator:(c,h)=>this.withBusyIndicator(c,h)}),this.events.documentToBeOpened.addEventListener(()=>{this._openFileProgress.reset()}),t.database.events.openProgress.addEventListener(c=>{this._openFileProgress.handle({database:t.database,percentage:c.percentage,stage:c.stage,subStage:c.subStage,subStageStatus:c.subStageStatus,data:c.data}),c.subStage==="HEADER"&&(this.curView.ltscale=t.database.ltscale,this.curView.celtscale=t.database.celtscale,this.curView.renderer.showLineWeight=t.database.lwdisplay)}),e.preloadDefaultFonts&&this.loadDefaultFonts(),this._webworkerFileUrls=e.webworkerFileUrls,this.registerWorkers(e.webworkerFileUrls),e.checkWorkersOnInit&&this.areWorkersReady(),this.loadPlugins(e.plugins).catch(c=>{d.log.error("[AcApDocManager] Error loading plugins:",c)}),Eh({enabled:e.builtinOpenFileDialog!==!1,getOpenDocumentDefaults:()=>this.resolveOpenDocumentDefaults()})}static createInstance(e={}){return k._instance==null&&(k._instance=new k(e)),this._instance}static checkWebworkerReadiness(e){return Oh(e)}static get instance(){if(!k._instance)throw new Error("AcApDocManager instance is not created yet!");return k._instance}async destroy(){await this._pluginManager.unloadAllPlugins(),this.context.doc.destroy(),Th(),M.AcTrMTextRenderer.resetInstance(),vb(),k._instance=void 0}get workersReady(){return this._workersReady}areWorkersReady(){return this._workersReady===!0?Promise.resolve(!0):(this._workersReadyCheckPromise||(this._workersReadyCheckPromise=Oh(this._webworkerFileUrls).then(e=>(this._workersReady=e,this._workersReadyCheckPromise=void 0,this.events.workersReady.dispatch({ready:e}),e)).catch(()=>(this._workersReady=!1,this._workersReadyCheckPromise=void 0,this.events.workersReady.dispatch({ready:!1}),!1))),this._workersReadyCheckPromise)}get context(){return this._context}get curDocument(){return this._context.doc}get mdiActiveDocument(){return this._context.doc}get curView(){return this._context.view}get editor(){return this._context.view.editor}get commandManager(){return this._commandManager}get pluginManager(){return this._pluginManager}get drawStyleToolbar(){return this._drawStyleToolbar}get baseUrl(){return this._baseUrl}resolveColors(){const e=this.curDocument.database,t=e.tables.layerTable.getAt(e.clayer),i=this.resolveColorToRgb(t==null?void 0:t.color);let n=e.cecolor;return n!=null&&n.isByLayer&&(n=t==null?void 0:t.color),{entityColor:this.resolveColorToRgb(n),layerColor:i}}resolveColorToRgb(e){return!e||e.isByLayer||e.isByBlock||e.isByACI&&e.colorIndex===7?this.resolveAci7ForBackground():e.RGB??this.resolveAci7ForBackground()}resolveAci7ForBackground(){return this.curView.backgroundColor===16777215?0:16777215}get avaiableFonts(){return this._fontLoader.avaiableFonts}async loadFonts(e){await this._fontLoader.load(e)}async loadDefaultFonts(e){e==null?await this._fontLoader.load([...D.FontManager.instance.getFontsToLoad()]):await this._fontLoader.load(e)}async openUrl(e,t){t=this.setOptions(t),this.onBeforeOpenDocument(t);try{await this._openFileProgress.beginOpen(this.context.doc.database);const i=await this.context.doc.openUri(e,t);return this.onAfterOpenDocument(i,t),i}catch(i){throw this._openFileProfiler.cancel(),i}}async openDocument(e,t,i){i=this.setOptions(i),this.onBeforeOpenDocument(i);try{await this._openFileProgress.beginOpen(this.context.doc.database);const n=await this.context.doc.openDocument(e,t,i);return this.onAfterOpenDocument(n,i),n}catch(n){throw this._openFileProfiler.cancel(),n}}async loadOverlay(e,t,i={}){var o;const n=new d.AcDbDatabase,r=(o=e.split(".").pop())==null?void 0:o.toLocaleLowerCase();return await ao(n,async()=>{await n.read(t,{readOnly:!0,...i},r==="dwg"?d.AcDbFileType.DWG:d.AcDbFileType.DXF)}),this.registerOverlayDatabase(n)}async registerOverlayDatabase(e){const t=this.curView,i=await t.addOverlayEntities(e),n=`overlay-${this._nextOverlayId++}`;return this._overlays.set(n,{db:e,layout:i}),t.isDirty=!0,n}removeOverlay(e){const t=this._overlays.get(e);if(!t)return!1;const i=this.curView;return i.cadScene.internalScene.remove(t.layout.internalObject),t.layout.clear(),this._overlays.delete(e),i.isDirty=!0,!0}setOverlayVisible(e,t){const i=this._overlays.get(e);return i?(i.layout.visible=t,this.curView.isDirty=!0,!0):!1}clearOverlays(){for(const e of[...this._overlays.keys()])this.removeOverlay(e)}get overlayIds(){return Array.from(this._overlays.keys())}getOverlayLayout(e){var t;return(t=this._overlays.get(e))==null?void 0:t.layout}async newDocument(e){const i=`${this.baseUrl.endsWith("/")?this.baseUrl:`${this.baseUrl}/`}${Pb}`,n=this.setOptions({...e,mode:F.Write});this.onBeforeOpenDocument(n),await this._openFileProgress.beginOpen(this.context.doc.database);const r=await this.context.doc.openUri(i,n);return r&&this.context.doc.resetNewDocumentIdentity(),this.onAfterOpenDocument(r,n),r}setOpenDocumentDefaults(e){this._openDocumentDefaults=e,Lh({enabled:!0,getOpenDocumentDefaults:()=>this.resolveOpenDocumentDefaults()})}resolveOpenDocumentDefaults(){const e=this._openDocumentDefaults;return e==null?{minimumChunkSize:1e3}:typeof e=="function"?e():e}regen(){this.curView.clear(),this.context.doc.database.regen()}resolveFontsBaseUrl(){return`${this._baseUrl.endsWith("/")?this._baseUrl:`${this._baseUrl}/`}fonts/`}lookupLocalCmd(e){return this._commandManager.lookupLocalCmd(e,this.curDocument.openMode)}lookupGlobalCmd(e){return this._commandManager.lookupGlobalCmd(e,this.curDocument.openMode)}searchCommandsByPrefix(e){return this._commandManager.searchCommandsByPrefix(e,this.curDocument.openMode)}registerCommands(){const e=this._commandManager,t=(n,r,o)=>{const a=Ab[n.toUpperCase()]??[];e.addCommand(de.SYSTEMT_COMMAND_GROUP_NAME,n,r,o,this.resolveCommandAliases(n,a))};t("about","about",new $u),t("arc","arc",new Lc),t("cachefont","cachefont",new Ui),t("circle","circle",new Bc),t("cdxf","cdxf",new nc),t("pngout","pngout",new oc),t("entout","entout",new cc),t("ellipse","ellipse",new Vc),t("erase","erase",new Ru),t("hideobjects","hideobjects",new Vu),t("dimlinear","dimlinear",new Fc),t("measuredistance","measuredistance",new Yd),t("measurearea","measurearea",new Nd),t("measureangle","measureangle",new Fd),t("measurearc","measurearc",new Hd),t("measurepoint","measurepoint",new Xd),t("clearmeasurements","clearmeasurements",new Sd),t("measurementvis","measurementvis",new Pd),t("measurementexport","measurementexport",new Od),t("measurementimport","measurementimport",new Bd),t("-hatch","-hatch",new Qn),t("imageattach","imageattach",new Gc),t("-insert","-insert",new Uc),t("xattach","xattach",new vd),t("-layer","-layer",new xc),t("laycur","laycur",new mc),t("laydel","laydel",new pc),t("layfrz","layfrz",new Hn),t("layiso","layiso",new Wn),t("laylck","laylck",new yc),t("layon","layon",new gc),t("layoff","layoff",new $n),t("laythw","laythw",new bc),t("layuniso","layuniso",new wc),t("layulk","layulk",new vc),t("layerp","layerp",new fc),t("layerclose","layerclose",new kc),t("line","line",new At),t("mline","mline",new Wc),t("mtext","mtext",new $c),t("copy","copy",new Ps),t("move","move",new Ku),t("offset","offset",new Gi),t("rotate","rotate",new Cs),t("log","log",new Yu),t("open","open",new eh),t("pan","pan",new lh),t("point","point",new Yc),t("polygon","polygon",new is),t("pline","pline",new Jc),t("qnew","qnew",new th),t("ray","ray",new ed),t("rectang","rectang",new ns),t("regen","regen",new ih),t("revcloud","revcloud",new ss),t("markuptext","markuptext",new Fu),t("markupline","markupline",new Du),t("markuparrow","markuparrow",new xu),t("markupcloud","markupcloud",new Au),t("markuprect","markuprect",new Ou),t("markupcircle","markupcircle",new Pu),t("markuphighlight","markuphighlight",new Cu),t("markupcallout","markupcallout",new Su),t("markupstamp","markupstamp",new ju),t("markupvis","markupvis",new Nu),t("clearmarkups","clearmarkups",new ku),t("markupexport","markupexport",new Iu),t("markupimport","markupimport",new Mu),t("select","select",new nh),t("sketch","sketch",new ls),t("spline","spline",new gd),t("switchbg","switchbg",new rh),t("unisolateobjects","unisolateobjects",new Wu),t("xline","xline",new kd),t("undo","undo",new oh),t("redo","redo",new ah),t("zoom","zoom",new Mt),d.AcDbSysVarManager.instance().getAllDescriptors().forEach(n=>{e.addCommand(de.SYSTEMT_COMMAND_GROUP_NAME,n.name,n.name,new sh,this.resolveCommandAliases(n.name,[]))})}normalizeCommandAliasConfig(e){const t=new Map;return e&&Object.entries(e).forEach(([i,n])=>{const r=i.trim().toUpperCase();if(!r)return;const o=Array.isArray(n)?n:[n],a=new Set;o.forEach(l=>{const c=l.trim().toUpperCase();c&&c!==r&&a.add(c)}),t.set(r,[...a])}),t}resolveCommandAliases(e,t){const i=e.trim().toUpperCase(),n=this._commandAliasOverrides.get(i);if(n)return[...n];const r=new Set;return t.forEach(o=>{const a=o.trim().toUpperCase();a&&a!==i&&r.add(a)}),[...r]}sendStringToExecute(e){this.executeCommandString(e).catch(t=>{const i=t instanceof Error?t.message:String(t);this.editor.showMessage(i,"error"),d.log.error(`[AcApDocManager] Command failed: ${e}`,t)})}async executeCommandString(e){const t=this.splitCommandScript(e);if(!t.length)throw new Error("Command string is empty");const[i,...n]=t;this.editor.clearScriptInputs(),this.editor.enqueueScriptInputs(n),await this.executeNamedCommand(i,{preserveScriptInputs:!1})}async runScript(e){const t=To(e);for(this.editor.clearScriptInputs(),this.editor.enqueueScriptInputs(t);this.editor.hasScriptInputs();){const i=this.consumeNextScriptCommandName();if(i==null)break;if(kh(i)){this.editor.clearScriptInputs();break}await this.executeNamedCommand(i,{preserveScriptInputs:!0})}}async executeNamedCommand(e,t){const i=this.context.doc.openMode;let n=this._commandManager.lookupGlobalCmd(e)??this._commandManager.lookupLocalCmd(e,i);if(n||await this._pluginManager.loadByTrigger(e)&&(n=this._commandManager.lookupGlobalCmd(e)??this._commandManager.lookupLocalCmd(e,i)),!n)throw new Error(`Command '${e}' not found`);if(i<n.mode)throw new Error(`Command '${e}' requires mode '${F[n.mode]}' but document is in mode '${F[i]}'!`);await this._commandManager.cancelActive();const r=n.trigger(this.context).finally(()=>{t.preserveScriptInputs||this.editor.clearScriptInputs(),this._commandManager.clearActive(n)});this._commandManager.markActive(n,this.curView,r),await r}consumeNextScriptCommandName(){for(;this.editor.hasScriptInputs();){const e=this.editor.consumeScriptInput();if(e==null)return;const t=e.trim();if(t)return t}}splitCommandScript(e){const t=To(e);if(!t.length)return[];let i=0;for(;i<t.length&&!t[i].trim();)i++;return i>=t.length?[]:[t[i].trim(),...t.slice(i+1)]}setActiveLayout(){const e=this.curView,t=this.curDocument.database;e.activeLayoutBtrId=t.currentSpaceId,e.modelSpaceBtrId=t.tables.blockTable.modelSpace.objectId}onBeforeOpenDocument(e){this.events.documentToBeOpened.dispatch({doc:this.context.doc,mode:this.getDocumentEventMode(e)}),Dt.instance.clearAll(),this.clearOverlays(),this.curView.bindDrawDatabase(this.context.doc.database),this.curView.progressiveRendering=(e==null?void 0:e.progressiveRendering)??!1,this._openFileProgress.setSeeThroughOverlay((e==null?void 0:e.progressiveRendering)??!1),ga(),vu(),this.curView.clear(),this._openFileProfiler.begin(this.context.doc.database)}onAfterOpenDocument(e,t){const i=!e&&this.hasRecoverablePartialContent();if(e||i){this.context.doc.destroy();const n=this.context.doc;this.events.documentActivated.dispatch({doc:n,mode:this.getDocumentEventMode(t)}),this.setActiveLayout(),this.curView.syncDisplaySysVars(n.database);const r=n.database,o=r.tables.blockTable.modelSpace.objectId,a=r.currentSpaceId!==o,l=d.acdbHostApplicationServices().layoutManager.getActiveLayout(r),c=l==null?void 0:l.limits,h=this.resolveOpenViewMode(t),p=this.curView,m=(t==null?void 0:t.progressiveRendering)??!1;if(a&&c&&!c.isEmpty())p.zoomTo(c);else if(h===$i.Extents)m&&p.beginProgressiveOpenFit(),p.zoomToFitDrawing();else if(a)m&&p.beginProgressiveOpenFit(),p.zoomToFitDrawing();else{const g=p.width/Math.max(p.height,1),f=r.tables.viewportTable.getActiveVport(),w=f==null?void 0:f.modelViewBox(g);w?p.zoomTo(w):this.hasUsableDrawingExtents(r)?p.zoomTo(new d.AcGeBox2d(r.extmin,r.extmax)):(m&&p.beginProgressiveOpenFit(),p.zoomToFitDrawing())}this.curView.markLayoutAsInitialized(r.currentSpaceId),this._openFileProfiler.markReadCompleteAndScheduleReport(p)}else this._openFileProfiler.cancel(),this.curView.endProgressiveOpenFit(),this.regen()}hasUsableDrawingExtents(e){if(e.extents.isEmpty())return!1;const t=1e15,i=[e.extmin.x,e.extmin.y,e.extmax.x,e.extmax.y];return i.some(n=>!Number.isFinite(n))||i.some(n=>Math.abs(n)>=t)?!1:e.extmax.x>e.extmin.x&&e.extmax.y>e.extmin.y}hasRecoverablePartialContent(){const e=this.context.doc.database,t=e.tables.blockTable.modelSpace;return t?t.newIterator().count>0:!e.extents.isEmpty()}setOptions(e){return e==null?e={drawNoPlotLayers:!1,progressiveRendering:!1}:(this.stripObsoleteFontOpenOptions(e),e.drawNoPlotLayers==null&&(e.drawNoPlotLayers=!1),e.progressiveRendering==null&&(e.progressiveRendering=!1)),e}stripObsoleteFontOpenOptions(e){const t=e,i=t.fontLoader!=null,n=t.failOnFontLoadError!=null;!i&&!n||(delete t.fontLoader,delete t.failOnFontLoadError,console.warn("[AcApDocManager] Ignoring obsolete open options "+[i?"fontLoader":null,n?"failOnFontLoadError":null].filter(Boolean).join(", ")+"; fonts load on demand via FontManager.lazyFontLoading."))}getDocumentEventMode(e){return(e==null?void 0:e.mode)??F.Read}resolveOpenViewMode(e){return(e==null?void 0:e.openViewMode)!=null?e.openViewMode:this.getDocumentEventMode(e)===F.Write?$i.Saved:$i.Extents}showBusyIndicator(e){this._busyIndicator.show(e)}hideBusyIndicator(){this._busyIndicator.hide()}setBusyIndicatorMessage(e){this._busyIndicator.setMessage(e)}async withBusyIndicator(e,t){return this._busyIndicator.withBusyIndicator(e,t)}registerWorkers(e){const t=M.AcTrMTextRenderer.getInstance();t.initialize((e==null?void 0:e.mtextRender)??Dh.mtextRender),t.setDefaultFonts(Bh)}async loadPlugins(e){if(e){if(e.fromConfig&&e.fromConfig.length>0)try{const t=await this._pluginManager.loadPluginsFromConfig(e.fromConfig,{continueOnError:!0});t.loaded.length>0&&d.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from config:`,t.loaded),t.failed.length>0&&d.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s):`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){d.log.error("[AcApDocManager] Error loading plugins from config:",t)}if(e.fromFolder)try{const t=await this._pluginManager.loadPluginsFromFolder(e.fromFolder.folderPath,{pluginList:e.fromFolder.pluginList,continueOnError:e.fromFolder.continueOnError??!0});t.loaded.length>0&&d.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from folder:`,t.loaded),t.failed.length>0&&d.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s) from folder:`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){d.log.error("[AcApDocManager] Error loading plugins from folder:",t)}}}}const Cb=Object.freeze(Object.defineProperty({__proto__:null,AcApDocManager:k},Symbol.toStringTag,{value:"Module"}));class Yi{static isFontLoaded(e){return D.FontManager.instance.isFontLoaded(e)}static getFontType(e){return D.FontManager.instance.getFontType(e)}static getReplacementFontName(e){return D.FontManager.instance.findAndReplaceFont(e)}static getShxCodePoints(e){var r;const t=D.FontManager.instance.getFontByName(e,!1);if(!t||t.type!=="shx")return[];const i=t.data;return Object.keys(((r=i.content)==null?void 0:r.data)??{}).map(o=>Number(o)).filter(o=>Number.isFinite(o)).sort((o,a)=>o-a)}static getLoadedShxFontData(e){const t=D.FontManager.instance.getFontByName(e,!1);if(!(!t||t.type!=="shx"))return t.data}static createShxParserFont(e){return new D.ShxParserFont(e)}static findFontInfoByName(e){var n;const t=((n=k.instance)==null?void 0:n.avaiableFonts)??[],i=e.trim().toLowerCase();if(i)return t.find(r=>r.name.some(o=>o.trim().toLowerCase()===i))}static getCatalogFontType(e){var t;return(t=Yi.findFontInfoByName(e))==null?void 0:t.type}static async ensureDrawingFontLoaded(e){const t=k.instance;t&&(Yi.isFontLoaded(e)||await t.loadFonts([e]))}static async cacheFont(e,t,i,n){return D.FontManager.instance.cacheFont(e,t,i,n)}}const jh=s=>new d.AcGeBox3d(s.min,s.max),Fh=s=>new d.AcGeBox2d(s.min,s.max),zh=s=>new L.Box3(s.min,s.max),Nh=s=>new d.AcGeBox2d(s.min,s.max),Rh=s=>new L.Box2(s.min,s.max),Vh=s=>new d.AcGeBox2d(s.min,s.max),Gh=s=>{const e=new L.Box3;return e.min.set(s.min.x,s.min.y,0),e.max.set(s.max.x,s.max.y,0),e},Bo={threeBo2dToGeBox2d:Nh,geBox2dToThreeBox2d:Rh,threeBox3dToGeBox3d:jh,geBox3dToThreeBox3d:zh,goBox3dToGeBox2d:Fh,threeBox3dToGeBox2d:Vh,geBox2dToThreeBox3d:Gh};class _b{constructor(e){this.getLayerInfo=e}shouldConvert(e){if(!e.visibility)return!1;const t=this.getLayerInfo(e.layer);return t?this.isBlockReference(e)?!t.isFrozen:Ut.isLayerVisible(t):!0}shouldConvertForExport(e,t=!0){return e.visibility?t?!0:this.shouldConvert(e):!1}layerVisibilityMayHaveChanged(e){return e.isOff!==void 0||e.standardFlags!==void 0}collectMissingEntitiesOnLayer(e,t,i){return this.collectMissingEntities(t,i,n=>n.layer===e&&this.shouldConvert(n))}collectMissingEntitiesForExport(e,t,i=!0){return this.collectMissingEntities(e,t,n=>this.shouldConvertForExport(n,i))}isBlockReference(e){return e instanceof d.AcDbBlockReference}collectMissingEntities(e,t,i){const n=[],r=e.newIterator();for(const o of r)i(o)&&(t(o.objectId)||n.push(o));return n}}var Ms=(s=>(s[s.LEFT_BOTTOM=0]="LEFT_BOTTOM",s[s.LEFT_TOP=1]="LEFT_TOP",s[s.RIGHT_TOP=2]="RIGHT_TOP",s[s.RIGHT_BOTTOM=4]="RIGHT_BOTTOM",s))(Ms||{});class Eb extends L.Object3D{constructor(e,t,i=150,n=2){super(),this.camera=e,this.renderer=t,this.gizmoCamera=new L.OrthographicCamera(-2,2,2,-2,0,4),this.gizmoCamera.position.set(0,0,2),this.gizmoDim=i,this.gizmoPos=n,this.initialize()}initialize(){}update(){this.updateOrientation();const e=this.renderer.autoClear;this.renderer.autoClear=!1,this.renderer.clearDepth();const t=new L.Vector4;this.renderer.getViewport(t);const i=this.calculateViewportPos();this.renderer.setViewport(i.x,i.y,this.gizmoDim,this.gizmoDim),this.renderer.render(this,this.gizmoCamera),this.renderer.setViewport(t.x,t.y,t.z,t.w),this.renderer.autoClear=e}dispose(){}updateOrientation(){this.quaternion.copy(this.camera.quaternion).invert(),this.updateMatrixWorld()}calculatePosInViewport(e,t,i){const n=(e-i.min.x)/this.gizmoDim*2-1,r=-((t-i.min.y)/this.gizmoDim)*2+1;return{x:n,y:r}}calculateViewportPos(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,r=this.gizmoDim;let o=t-r,a=i-r;switch(n){case 0:o=0,a=0;break;case 1:o=0;break;case 4:a=0;break}return{x:o,y:a}}calculateViewportBbox(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,r=this.gizmoDim,o=new L.Box2(new L.Vector2(t-r,0),new L.Vector2(t,r));switch(n){case 0:o.set(new L.Vector2(0,i-r),new L.Vector2(r,i));break;case 1:o.set(new L.Vector2(0,0),new L.Vector2(r,r));break;case 4:o.set(new L.Vector2(t-r,i-r),new L.Vector2(t,i));break}return o}}function Lb(s,e){const t=e.font||"Helvetica",i=e.fontSize||30,n=e.width||200,r=e.height||200,o=e.bgColor?e.bgColor.join(", "):"255, 255, 255, 1.0",a=e.color?e.color.join(", "):"0, 0, 0, 1.0",l=document.createElement("canvas");l.width=n,l.height=r;const c=l.getContext("2d");if(c){c.font=`bold ${i}px ${t}`,c.fillStyle=`rgba(${o})`,c.fillRect(0,0,n,r);const m=c.measureText(s).width;c.fillStyle=`rgba(${a})`,c.fillText(s,n/2-m/2,r/2+i/2-2)}const h=new L.Texture(l);return h.minFilter=L.LinearFilter,h.needsUpdate=!0,h}function jo(s){const e=Lb(s,{fontSize:100,font:"Arial Narrow, sans-serif",color:[255,255,255,1],bgColor:[0,0,0,0]}),t=new L.SpriteMaterial({map:e,transparent:!0});return new L.Sprite(t)}Ms.RIGHT_TOP;const Tb={pos:Ms.LEFT_BOTTOM,size:100,hasZAxis:!0};class Ib extends Eb{constructor(e,t,i){const n={...Tb,...i};super(e,t,n.size,i.pos),this.hasZAxis=n.hasZAxis;const r=[0,0,0,2,0,0,0,0,0,0,2,0],o=[1,0,0,1,.6,0,0,1,0,.6,1,0];this.hasZAxis&&(r.push(0,0,0,0,0,2),o.push(0,0,1,0,.6,1));const a=new L.BufferGeometry;a.setAttribute("position",new L.Float32BufferAttribute(r,3)),a.setAttribute("color",new L.Float32BufferAttribute(o,3));const l=new L.LineBasicMaterial({vertexColors:!0,toneMapped:!1});this.axes=new L.LineSegments(a,l),this.axes.position.set(-1,-1,-1),this.add(this.axes),this.xText=jo("X"),this.xText.position.set(1.5,-1,-1),this.add(this.xText),this.yText=jo("Y"),this.yText.position.set(-1,1.5,-1),this.add(this.yText),this.hasZAxis&&(this.zText=jo("Z"),this.zText.position.set(-1,-1,1.5),this.add(this.zText))}setLineColors(e,t){const i=new L.Color,n=this.axes.geometry.attributes.color.array;return i.set(e),i.toArray(n,0),i.toArray(n,3),i.set(t),i.toArray(n,6),i.toArray(n,9),this.axes.geometry.attributes.color.needsUpdate=!0,this}setTextColor(e){this.xText.material.color=e,this.yText.material.color=e}dispose(){var e,t;this.axes.geometry.dispose(),this.axes.material.dispose(),this.xText.geometry.dispose(),this.xText.material.dispose(),this.yText.geometry.dispose(),this.yText.material.dispose(),this.hasZAxis&&((e=this.zText)==null||e.geometry.dispose(),(t=this.zText)==null||t.material.dispose())}}class Mb extends M.AcTrBaseView{constructor(e,t,i,n){super(e,i,n),this._layoutBtrId=t,this._mode=ye.SELECTION,this._axesGizmo=this.createAxesGizmo(),this._viewportViews=new Map}get layoutBtrId(){return this._layoutBtrId}get mode(){return this._mode}set mode(e){e==ye.SELECTION?this._cameraControls.mouseButtons={MIDDLE:L.MOUSE.PAN}:e==ye.PAN&&(this._cameraControls.mouseButtons={LEFT:L.MOUSE.PAN}),this._cameraControls.update(),this._mode=e}get viewportCount(){return this._viewportViews.size}get viewportViews(){return this._viewportViews.values()}get internalCamera(){return this._camera.internalCamera}get viewportsBoundingBox(){if(this._viewportViews.size===0)return;const e=new d.AcGeBox2d;return this._viewportViews.forEach(t=>{const i=t.viewport.box;e.expandByPoint(i.min),e.expandByPoint(i.max)}),e.isEmpty()?void 0:e}addViewport(e){this._viewportViews.set(e.viewport.id,e)}removeViewport(e){this._viewportViews.delete(e)}resize(e,t){this._height=t,this._width=e,this._frustum=t/2,this.updateCameraFrustum(),this._viewportViews.forEach(i=>{i.update()})}render(e){var n;this._renderer.clear();const t=this._renderer.render(e.internalScene,this._camera),i=e.modelSpaceLayout;return i&&this.drawViewports(i.internalObject),(n=this._axesGizmo)==null||n.update(),t}createAxesGizmo(){return new Ib(this._camera.internalCamera,this._renderer.internalRenderer,{hasZAxis:!1,pos:Ms.LEFT_BOTTOM})}drawViewports(e){if(this._viewportViews.size>0){const t=this._renderer.autoClear;this._renderer.autoClear=!1;const i=new L.Vector4;this._renderer.getViewport(i),this._renderer.clearDepth();const n=e.visible;e.visible=!0,this._viewportViews.forEach(r=>{r.render(e)}),e.visible=n,this._renderer.setViewport(i.x,i.y,i.z,i.w),this._renderer.autoClear=t}}}class Db{constructor(){this._activeLayoutBtrId="",this._layoutViews=new Map}get activeLayoutBtrId(){return this._activeLayoutBtrId}set activeLayoutBtrId(e){this._activeLayoutBtrId=e,this._layoutViews.forEach(t=>{t.enabled=t.layoutBtrId==e})}get activeLayoutView(){return this._layoutViews.get(this._activeLayoutBtrId)}has(e){return this._layoutViews.has(e)}getAt(e){return this._layoutViews.get(e)}resize(e,t){this._layoutViews.forEach(i=>{i.resize(e,t)})}add(e){this._layoutViews.set(e.layoutBtrId,e)}render(e){var t;return((t=this.activeLayoutView)==null?void 0:t.render(e))??!1}}function Ob(s,e){return[...s].sort((t,i)=>Bb(t,i,e))}function Bb(s,e,t){const i=Kh(s)-Kh(e);if(Math.abs(i)>Number.EPSILON)return i;const n=Uh(t,s)-Uh(t,e);return Math.abs(n)>Number.EPSILON?n:0}function Kh(s){return Math.max(s.maxX-s.minX,0)*Math.max(s.maxY-s.minY,0)}function Uh(s,e){const t=s.x<e.minX?e.minX-s.x:s.x>e.maxX?s.x-e.maxX:0,i=s.y<e.minY?e.minY-s.y:s.y>e.maxY?s.y-e.maxY:0;return t*t+i*i}const dt=class dt{constructor(e){this.zoomTo=e,this.active=!1,this.userAdjusted=!1,this.programmaticDepth=0,this.incrementalEnabled=!1,this.initialPendingCount=0,this.convertedCount=0,this.lastZoomAt=0}get isActive(){return this.active}begin(e){if(this.active){this.initialPendingCount=Math.max(this.initialPendingCount,e),this.maybeEnableIncrementalFit();return}this.active=!0,this.userAdjusted=!1,this.lastZoomAt=0,this.initialPendingCount=e,this.convertedCount=0,this.lastFittedBox=void 0,this.incrementalEnabled=!1,this.maybeEnableIncrementalFit()}end(){this.active=!1,this.incrementalEnabled=!1,this.lastFittedBox=void 0,this.convertedCount=0}applyFinalFit(e){if(this.userAdjusted)return;const t=e();t&&this.applyZoom(t)}onLayoutViewChanged(){!this.active||this.userAdjusted||this.programmaticDepth>0||(this.userAdjusted=!0,this.end())}afterGeometryBatch(e,t){this.active&&(this.convertedCount++,this.maybeEnableIncrementalFit(),this.maybeIncrementalFit(e))}maybeEnableIncrementalFit(){this.incrementalEnabled||(this.initialPendingCount>=dt.SMALL_ENTITY_THRESHOLD||this.convertedCount>=dt.SMALL_ENTITY_THRESHOLD)&&(this.incrementalEnabled=!0)}maybeIncrementalFit(e){if(!this.active||!this.incrementalEnabled||this.userAdjusted)return;const t=performance.now();if(t-this.lastZoomAt<dt.FIT_INTERVAL_MS)return;const i=e();!i||!this.shouldApplyIncrementalFit(i)||(this.lastZoomAt=t,this.applyZoom(i))}shouldApplyIncrementalFit(e){const t=this.lastFittedBox;if(!t)return!0;const i=this.estimateBoxArea(t);return i<=Number.EPSILON?!0:this.estimateBoxArea(e)>=i*dt.BBOX_GROWTH_RATIO}applyZoom(e,t=1.1){this.programmaticDepth++;try{this.zoomTo(e,t),this.lastFittedBox=this.snapshotFitBox(e)}finally{this.programmaticDepth--}}estimateBoxArea(e){const t=new d.AcGeVector2d;return e.getSize(t),Math.abs(t.x)*Math.abs(t.y)}snapshotFitBox(e){return new d.AcGeBox2d({x:e.min.x,y:e.min.y},{x:e.max.x,y:e.max.y})}};dt.SMALL_ENTITY_THRESHOLD=500,dt.BBOX_GROWTH_RATIO=1.5,dt.FIT_INTERVAL_MS=500;let Fo=dt;const zo={background:d.ACGI_MODEL_SPACE_BACKGROUND},ai=class ai extends ec{constructor(e=zo){const t={...zo,...e},i=t.container??document.createElement("div");t.container=i,i.style.overflow="hidden";const n=new L.WebGLRenderer({antialias:!0,alpha:!0});i.appendChild(n.domElement),n.domElement.style.display="block",n.domElement.style.maxWidth="100%",n.domElement.style.maxHeight="100%",super(n.domElement,i),this._rafId=null,this._loadingLayouts=new Set,this._initializedLayouts=new Set,this._externallyFramedLayouts=new Set,this._convertingLayers=new Set,this._progressiveRendering=!1,this._convertQueue=[],this._convertDrainPromise=null,this._convertEpoch=0,this._lastProgressivePaintAt=0,this._progressivePaintCount=0,this._progressiveYieldCount=0,this._pendingGeometryJobs=0,this.animate=()=>{var x;this._rafId=requestAnimationFrame(this.animate),this.events.renderFrame.dispatch({render:this._renderer,camera:this.internalCamera});const f=this._numOfEntitiesToProcess>0,w=f&&!this._progressiveRendering;if(!this._isDirty&&!this._htmlDirty&&!f||w||!this._isDirty&&!this._htmlDirty)return;let v=!1;this._isDirty&&(this._progressiveRendering&&f&&this._progressivePaintCount++,v=this._layoutViewManager.render(this._scene)),this.internalCamera&&(this._isDirty||this._htmlDirty)&&this._css2dRenderer.render(this._scene.internalScene,this.internalCamera),(x=this._stats)==null||x.update(),this._isDirty=v,this._htmlDirty=!1},this._gripManager=new Il(this),this._keyHandler=new kn(this),e.calculateSizeCallback&&this.setCalculateSizeCallback(e.calculateSizeCallback),n.setPixelRatio(Math.min(window.devicePixelRatio,2)),n.setSize(this.width,this.height),this._renderer=new M.AcTrRenderer(n);const r=ue.instance.fontMapping;this._renderer.setFontMapping(r),this._renderer.events.fontNotFound.addEventListener(f=>{ee.emit("font-not-found",{fontName:f.fontName,count:f.count??0})}),this._scene=this.createScene(),this._layerAppearance=new al(this._scene,this._renderer),this._inheritedLayerMaterialMapper=new sl(f=>this._layerAppearance.getEffectiveLayerTraits(f),this._renderer),this.backgroundColor=t.background??d.ACGI_MODEL_SPACE_BACKGROUND,this._stats=this.createStats(ue.instance.isShowStats);const o=d.AcDbSysVarManager.instance(),a=d.AcDbSystemVariables.MODELBKCOLOR.toLowerCase(),l=d.AcDbSystemVariables.PAPERBKCOLOR.toLowerCase();o.events.sysVarChanged.addEventListener(f=>{const w=f.name.toLowerCase();if(w===a||w===l){const v=this.isModelSpaceLayout(f.database);if(!(w===a&&v||w===l&&!v))return;this.applyCanvasBackground(bn(f.database,v))}}),ue.instance.events.modified.addEventListener(f=>{f.key=="isShowStats"&&this.toggleStatsVisibility(this._stats,f.value)});let c=null,h=null,p=null;const m=()=>this.mode===ye.SELECTION&&!this.editor.isActive&&!He.getActiveInputBox()&&!fl()&&!this._gripManager.isDragging,g=()=>{p==null||p.remove(),p=null};this.canvas.addEventListener("mousedown",f=>{f.button===0&&m()&&(h=this.viewportToCanvas({x:f.clientX,y:f.clientY}),c=this.screenToWorld(h),p=document.createElement("div"),p.className="ml-jig-preview-rect",this.container.appendChild(p))}),this.canvas.addEventListener("mousemove",f=>{if(!c||!p||!h)return;const w=this.viewportToCanvas({x:f.clientX,y:f.clientY}),v=this.screenToWorld(w),x=this.worldToScreen(c),S=this.worldToScreen(v),P=Math.min(x.x,S.x),A=Math.min(x.y,S.y),_=Math.abs(x.x-S.x),C=Math.abs(x.y-S.y),O=this.getSelectionMode(h,w),B=this.getPointerSelectionAction(f),I=this.getSelectionPreviewStyle(O,B);Object.assign(p.style,{left:`${P}px`,top:`${A}px`,width:`${_}px`,height:`${C}px`,borderStyle:I.borderStyle,background:I.background}),p.style.setProperty("--line-color",I.lineColor)}),this.canvas.addEventListener("mouseup",f=>{if(this._gripManager.isDragging){c=null,h=null,g();return}if(!c||!h)return;const w=this.viewportToCanvas({x:f.clientX,y:f.clientY}),v=this.screenToWorld(w);g();const x=this.getPointerSelectionAction(f);if(this.isSelectionClick(h,w))if(Fa(this,w.x,w.y,x))x==="replace"&&this.selectionSet.clear();else{const S=this.pick(v);S.length>0?(x==="replace"&&this.htmlTransientManager.deselectAll(),this.applySelection([S[0].id],x)):x==="replace"&&this.selectionSet.clear()}else{const S=new d.AcGeBox2d().expandByPoint(c).expandByPoint(v),P=this.getSelectionMode(h,w);this.selectByBoxWithMode(S,P,x),za(this,S,P,x)}c=null,h=null}),this.canvas.addEventListener("dblclick",f=>{f.button===0&&m()&&k.instance.curDocument.openMode===F.Write&&this.openPickedEntityEditor(f)}),document.addEventListener("keydown",f=>{this._keyHandler.handleKeyDown(f)}),d.acdbHostApplicationServices().layoutManager.events.layoutSwitched.addEventListener(f=>{const w=f.layout.blockTableRecordId,v=!this._initializedLayouts.has(w);this._initializedLayouts.add(w),this.activeLayoutBtrId=w,this.createLayoutViewIfNeeded(w),this.loadLayoutEntitiesIfNeeded(w),this.refreshCanvasBackgroundForActiveLayout(),this._isDirty=!0,v&&this.applyInitialZoom(w,f.layout)}),this._css2dRenderer=new Qh.CSS2DRenderer,this._css2dRenderer.setSize(this.width,this.height),this._css2dRenderer.domElement.style.position="absolute",this._css2dRenderer.domElement.style.top="0px",this._css2dRenderer.domElement.style.left="0px",this._css2dRenderer.domElement.style.pointerEvents="none",this._css2dRenderer.domElement.style.zIndex="99998",this._css2dRenderer.domElement.style.maxWidth="100%",this._css2dRenderer.domElement.style.maxHeight="100%",i.appendChild(this._css2dRenderer.domElement),this._missedImages=new Map,this._layoutViewManager=new Db,this._progressiveOpenFit=new Fo((f,w)=>{this.activeLayoutView.zoomTo(f,w??1.1),this._isDirty=!0}),this._entityDisplay=new _b(f=>this.resolveLayerInfo(f)),this.initialize(),this.onWindowResize(),this._isDirty=!0,this._htmlDirty=!1,this.startAnimationLoop(),this._numOfEntitiesToProcess=0,this._pendingGeometryJobs=0}getPointerSelectionAction(e){return Ql(e)}initialize(){this.setCursor(Le.Crosshair)}get mode(){const e=this.activeLayoutView;return e?e.mode:ye.SELECTION}set mode(e){this.activeLayoutView.mode=e}get renderer(){return this._renderer}get gripManager(){return this._gripManager}get isDirty(){return this._isDirty}get isProcessingEntities(){return this._numOfEntitiesToProcess>0||this._pendingGeometryJobs>0}async waitUntilIdle(e=6e4){const t=Date.now()+Math.max(0,e);let i=0;for(;;){if(this.isProcessingEntities)i=0;else if(i++,i>=2)return!0;if(Date.now()>t)return!this.isProcessingEntities;await new Promise(n=>setTimeout(n,16))}}get progressiveRendering(){return this._progressiveRendering}set progressiveRendering(e){this._progressiveRendering=e,this.resetProgressiveOpenStats()}get progressiveOpenStats(){return{paintCount:this._progressivePaintCount,yieldCount:this._progressiveYieldCount}}resetProgressiveOpenStats(){this._progressivePaintCount=0,this._progressiveYieldCount=0,this._lastProgressivePaintAt=0}beginProgressiveOpenFit(){this._progressiveOpenFit.begin(this._numOfEntitiesToProcess)}endProgressiveOpenFit(){this._progressiveOpenFit.end()}set isDirty(e){this._isDirty=e}get isHtmlDirty(){return this._htmlDirty}set isHtmlDirty(e){this._htmlDirty=e}get missedData(){return{fonts:this._renderer.missedFonts,images:this._missedImages,xrefs:this.collectUnresolvedXrefs()}}collectUnresolvedXrefs(){var e,t;try{const i=(t=(e=k.instance)==null?void 0:e.curDocument)==null?void 0:t.database;if(!i)return[];const n=i.tables.blockTable;return typeof n.getUnresolvedXrefs!="function"?[]:n.getUnresolvedXrefs().map(r=>({name:r.name,pathName:r.pathName,isOverlay:r.isOverlayReference}))}catch{return[]}}get center(){return this.activeLayoutView.center}set center(e){this.activeLayoutView.center=e}get backgroundColor(){return this._renderer.getClearColor()}set backgroundColor(e){this.applyCanvasBackground(e)}applyCanvasBackground(e){this._renderer.setClearColor(e),this._renderer.currentBackgroundColor=e,this._layerAppearance.refreshTextMaterialsInObjectTree(this._scene.internalScene),this.resyncForegroundLayersForBackground(),this.editor.syncCursorBackground(e),this._isDirty=!0}resyncForegroundLayersForBackground(){var t;const e=this._renderer.context.database;if(e)for(const i of e.tables.layerTable.newIterator())(t=i.color)!=null&&t.isForeground&&this._layerAppearance.syncFromLiveRecord(i)}isModelSpaceLayout(e){return e?Qa(e):this.activeLayoutBtrId===this.modelSpaceBtrId}bindDrawDatabase(e){this._renderer.context.database=e}syncDisplaySysVars(e){this.bindDrawDatabase(e),this.applyCanvasBackground(bn(e,this.isModelSpaceLayout(e)))}async addOverlayEntities(e){const t=new pl;t.isReference=!0,t.internalObject.userData.isReference=!0,this._scene.internalScene.add(t.internalObject);for(const n of e.tables.layerTable.newIterator())t.addLayer({name:n.name,isOff:n.isOff,isFrozen:n.isFrozen,color:n.color});const i=this._renderer.context.database;this._renderer.context.database=e;try{const n=e.tables.blockTable.modelSpace;for(const r of n.newIterator())if(!(r instanceof d.AcDbViewport))try{const o=this.drawEntity(r,!1);if(!o)continue;o.objectId=r.objectId,o.ownerId=r.ownerId,o.layerName=r.layer,o.visible=r.visibility!==!1,o instanceof M.AcTrGroup&&o.isOnTheSameLayer&&this._inheritedLayerMaterialMapper.remap(o.children,"0",o.layerName),await this.finishEntityGeometry(o,!1),t.addEntity(o),o.dispose()}catch(o){d.log.error(`[AcTrView2d] Failed to convert overlay entity ${r.objectId} (${r.type}):`,o)}}finally{this._renderer.context.database=i}return t}refreshCanvasBackgroundForActiveLayout(){var n,r;const t=(r=(n=k._instance)==null?void 0:n.curDocument)==null?void 0:r.database;if(!t)return;const i=this.activeLayoutBtrId===this.modelSpaceBtrId;this.applyCanvasBackground(bn(t,i))}get modelSpaceBtrId(){return this._scene.modelSpaceBtrId}set modelSpaceBtrId(e){this._scene.modelSpaceBtrId=e}get activeLayoutBtrId(){return this._scene.activeLayoutBtrId}set activeLayoutBtrId(e){this._layoutViewManager.activeLayoutBtrId=e,this._scene.activeLayoutBtrId=e,this.htmlTransientManager.setActiveLayoutId(e),this._isDirty=!0}get activeLayoutView(){return this._layoutViewManager.activeLayoutView}get stats(){return this._scene.stats}get cadScene(){return this._scene}async ensureEntitiesConvertedForExport(e){var l;const t=(e==null?void 0:e.includeInvisibleLayers)!==!1,i=(e==null?void 0:e.includeLayouts)!==!1,n=k.instance.curDocument.database,r=[],o=(l=n.objects)==null?void 0:l.layout;if(i&&(o!=null&&o.newIterator))for(const c of o.newIterator()){const h=c.blockTableRecordId;h&&this._scene.addEmptyLayout(h)}for(const[c]of this._scene.layouts){if(!i&&c!==this._scene.modelSpaceBtrId)continue;const h=n.tables.blockTable.getIdAt(c);h&&r.push(...this._entityDisplay.collectMissingEntitiesForExport(h,p=>this.hasEntity(p),t))}r.length>0&&(this._numOfEntitiesToProcess+=r.length,await this.batchConvert(r,{forExport:!0})),await this.waitUntilIdle()||d.log.warn("[AcTrView2d] Timed out waiting for deferred geometry before export")}get internalScene(){return this._scene.internalScene}get htmlTransientManager(){return this._scene.htmlTransientManager}get internalCamera(){var e;return(e=this.activeLayoutView)==null?void 0:e.internalCamera}set ltscale(e){this._renderer.ltscale=e}set celtscale(e){this._renderer.celtscale=e}screenToWorld(e){const t=this.activeLayoutView;return t?t.screenToWorld(e):new d.AcGePoint2d(e)}worldToScreen(e){const t=this.activeLayoutView;return t?t.worldToScreen(e):new d.AcGePoint2d(e)}zoomTo(e,t=1.1){this.activeLayoutView.zoomTo(e,t),this._isDirty=!0}rerenderPoints(e){const t=this._scene.activeLayout;t&&(t.rerenderPoints(e),this._isDirty=!0)}zoomToFitDrawing(e=0,t){new wr(()=>!this.isProcessingEntities,()=>{if(t&&this._externallyFramedLayouts.delete(t)){this.endProgressiveOpenFit();return}this._progressiveOpenFit.applyFinalFit(()=>this.resolveLayoutFitBox()),this.endProgressiveOpenFit()},300,e).start()}zoomToFitLayer(e){const t=this._scene.activeLayout;if(t){const i=t.getLayer(e);if(i&&!i.box.isEmpty()){const n=Bo.threeBox3dToGeBox2d(i.box);return this.zoomTo(n),this._isDirty=!0,!0}}return!1}flyTo(e,t){this.activeLayoutView.flyTo(e,t),this._isDirty=!0}async openPickedEntityEditor(e){const t=this.viewportToCanvas({x:e.clientX,y:e.clientY}),i=this.screenToWorld(t),n=this.pick(i,void 0,!0);if(!n.length)return;const r=k.instance.curDocument.database.tables.blockTable.getEntityById(n[0].id);if(!r)return;const o=this.resolveAttributedBlockReference(r);if(o){e.preventDefault(),this.selectionSet.clear(),this.selectionSet.add(o.objectId),k.instance.sendStringToExecute("attedit");return}r instanceof d.AcDbMText&&(e.preventDefault(),await this.editMTextEntity(r))}resolveAttributedBlockReference(e){if(e instanceof d.AcDbBlockReference)return e.attributeIterator().count>0?e:void 0;if(e instanceof d.AcDbAttribute){const t=k.instance.curDocument.database.tables.blockTable.getEntityById(e.ownerId);if(t instanceof d.AcDbBlockReference&&t.attributeIterator().count>0)return t}}async editMTextEntity(e){const t=e.database;e.lineSpacingFactor!==He.defaultLineSpacingFactor&&pt(t,"Edit MText",()=>{const r=t.openEntityForWrite(e);r instanceof d.AcDbMText&&(r.lineSpacingFactor=He.defaultLineSpacingFactor)}),this._isDirty=!0;const i=new He;let n=!1;try{const r=await i.open({view:this,location:e.location,width:this.resolveMTextEditorWidth(e),textHeight:this.resolveMTextEditorTextHeight(e),initialText:e.contents,initialAttachmentPoint:e.attachmentPoint,toolbarFontFamilies:this.getMTextToolbarFontFamilies()});if(!r)return;pt(t,"Edit MText",()=>{const o=t.openEntityForWrite(e);o instanceof d.AcDbMText&&(o.location=r.location,o.contents=r.contents,o.width=r.width,o.height=r.height,o.lineSpacingFactor=r.lineSpacingFactor,o.attachmentPoint=r.attachmentPoint)}),n=!0}finally{n||(this.updateEntity(e),this._isDirty=!0)}}resolveMTextEditorWidth(e){const t=Number(e.width);return Number.isFinite(t)&&t>0?t:1e-4}resolveMTextEditorTextHeight(e){const t=Number(e.height);return Number.isFinite(t)&&t>0?t:this.pixelsToWorldY(24)}pixelsToWorldY(e){const t=this.screenToWorld({x:0,y:0}),i=this.screenToWorld({x:0,y:e});return Math.max(Math.abs(i.y-t.y),1e-4)}getMTextToolbarFontFamilies(){return Array.from(new Set(k.instance.avaiableFonts.flatMap(e=>e.name).map(e=>e.trim()).filter(e=>e.length>0)))}pick(e,t,i){e==null&&(e=this.curPos);const n=[],r=this._scene.activeLayout;if(!r)return n;const o=this.activeLayoutView,a=t??this.selectionBoxSize,l=o.pointToBox(e,a),c=Math.max(l.size.width/2,l.size.height/2),h=o.layoutBtrId!==this._scene.modelSpaceBtrId,p=(l.size.width+l.size.height)/2,m=[],g=new Set;if(h)for(const x of o.viewportViews)x.containsPaperPoint(e)&&!x.isNearPaperBorder(e,p)&&(m.push(x),g.add(x.viewport.id));const f=this._scene.search(l),w=o.resetRaycaster(e,c);f.forEach(x=>{g.has(x.id)||Sn(x)&&r.isIntersectWith(x.id,w)&&n.push(x)}),m.length>0&&this.pickThroughViewports(e,l,m,n);const v=Ob(n,e);return i?v.slice(0,1):v}pickThroughViewports(e,t,i,n){const r=this._scene.modelSpaceLayout;if(!r)return;const o=(t.size.width+t.size.height)/4;for(const a of i){const l=a.paperPointToModel(e),c=o*a.paperToModelScale;if(c<=0)continue;const h=new d.AcGeBox2d().setFromPoints([new d.AcGePoint2d(l.x-c,l.y-c),new d.AcGePoint2d(l.x+c,l.y+c)]),p=a.resetRaycaster(l,c);r.search(h).forEach(g=>{Sn(g)&&r.isIntersectWith(g.id,p)&&n.push(g)})}}search(e,t){return this._scene.search(e,t)}select(e){const t=[];this.pick(e).forEach(n=>t.push(n.id)),t.length>0&&this.selectionSet.add(t)}selectByBox(e){this.selectByBoxWithMode(e,"crossing","add")}addLayer(e){this._scene.addLayer(this.toLayerInfo(e)),this._layerAppearance.syncFromLiveRecord(e),this._isDirty=!0}updateLayer(e,t){const{touchedObjectIds:i}=this._scene.updateLayer(this.toLayerInfo(e));if(this._layerAppearance.layerStyleMayHaveChanged(t)&&this._layerAppearance.syncFromLiveRecord(e),this._entityDisplay.layerVisibilityMayHaveChanged(t)){const n=this.toLayerInfo(e);(Ut.isLayerVisible(n)||!n.isFrozen)&&this.convertMissingEntitiesOnLayer(e.name)}for(const n of i)this.applySessionHiddenObjectState(n);this._isDirty=!0}addTransientEntity(e){const t=Array.isArray(e)?e:[e],i=this._convertEpoch,n=this._renderer.forceShowLineWeight;this._renderer.forceShowLineWeight=!0;try{for(let r=0;r<t.length;++r){const o=t[r],a=this.drawEntity(o,!0);a&&(a.objectId=o.objectId,a.asyncDraw().then(()=>{if(i!==this._convertEpoch){a.dispose();return}this._scene.addTransientEntity(a),this._isDirty=!0}).catch(l=>{d.log.error("[AcTrView2d] Transient entity geometry failed:",l),a.dispose()}))}}finally{this._renderer.forceShowLineWeight=n}}removeTransientEntity(e){this._scene.removeTransientEntity(e),this._isDirty=!0}setTransientEntityVisible(e,t){this._scene.setTransientEntityVisible(e,t)&&(this._isDirty=!0)}canCreateEntityPreview(e){return this._scene.canCreatePreview(e)}createEntityPreview(e){const t=this._scene.createPreview(e);return t&&(this._isDirty=!0),t}updateEntityPreview(e,t){this._scene.updatePreview(e,M.AcTrMatrixUtil.createMatrix4(t))&&(this._isDirty=!0)}removeEntityPreview(e){this._scene.removePreview(e)&&(this._isDirty=!0)}updateTransientPreviewTransforms(e){const t=this._scene.updateTransientPreviewTransforms(e.map(i=>({objectId:i.objectId,matrix:M.AcTrMatrixUtil.createMatrix4(i.matrix)})));t.webgl&&(this._isDirty=!0),t.html&&(this._htmlDirty=!0)}addEntity(e){const t=Array.isArray(e)?e:[e];this._numOfEntitiesToProcess+=t.length,this._progressiveRendering?(this._convertQueue.push(...t),this.drainConvertQueue()):this.batchConvert(t)}removeEntity(e){(Array.isArray(e)?e:[e]).forEach(i=>this._scene.removeEntity(i.objectId)),this._isDirty=!0}hasEntity(e){return this._scene.hasEntity(e)}getEntityVisible(e){return this._scene.getEntityVisible(e)}updateEntityVisibility(e){return this._scene.setEntityVisible(e.objectId,e.visibility)?(this._isDirty=!0,!0):!1}setEntitySceneVisible(e,t){return this._scene.setEntityVisible(e,t)?(this._isDirty=!0,!0):!1}applySessionHiddenObjectState(e){k.instance.curDocument.isObjectHidden(e)&&this._scene.setEntityVisible(e,!1)}updateEntity(e){const t=this.resolveSceneUpdateEntities(Array.isArray(e)?e:[e]);if(t.length===0)return;const i=t.map(n=>n.objectId).filter(n=>this.selectionSet.has(n));for(let n=0;n<t.length;++n){const r=t[n];this._scene.hasEntity(r.objectId)&&this._scene.removeEntity(r.objectId)}(async()=>(await this.batchConvert(t),await this.waitUntilDeferredGeometryIdle(),i.length>0&&this.highlight(i),this._gripManager.refresh()))(),this._isDirty=!0,setTimeout(()=>{this._isDirty=!0},100)}resolveSceneUpdateEntities(e){var r;const t=(r=k.instance.curDocument)==null?void 0:r.database,i=[],n=new Set;for(const o of e){let a=o;if(o instanceof d.AcDbAttribute){const l=t==null?void 0:t.tables.blockTable.getEntityById(o.ownerId);if(!(l instanceof d.AcDbBlockReference))continue;a=l}n.has(a.objectId)||(n.add(a.objectId),i.push(a))}return i}addLayout(e){this._scene.addEmptyLayout(e.blockTableRecordId),this.createLayoutViewIfNeeded(e.blockTableRecordId),this._isDirty=!0}markLayoutAsInitialized(e){this._initializedLayouts.add(e),this._externallyFramedLayouts.add(e)}resolveLayoutFitBox(){const e=this._scene.box;if(e&&!e.isEmpty())return Bo.threeBox3dToGeBox2d(e)}applyInitialZoom(e,t){new wr(()=>!this.isProcessingEntities,()=>{if(this._externallyFramedLayouts.delete(e))return;const n=t.limits,r=this._layoutViewManager.getAt(e),o=r==null?void 0:r.viewportsBoundingBox,a=!n||n.isEmpty()?!1:o?n.min.x<=o.min.x&&n.min.y<=o.min.y&&n.max.x>=o.max.x&&n.max.y>=o.max.y:!0;if(n&&!n.isEmpty()&&a)this.zoomTo(n);else if(o)this.zoomTo(o);else if(t.extents&&!t.extents.isEmpty()){const l=t.extents;this.zoomTo(new d.AcGeBox2d({x:l.min.x,y:l.min.y},{x:l.max.x,y:l.max.y}))}else{const l=this.resolveLayoutFitBox();l&&this.zoomTo(l)}this._isDirty=!0},300,0).start()}clear(){this._convertEpoch++,this._convertQueue.length=0,this._numOfEntitiesToProcess=0,this._pendingGeometryJobs=0,this._scene.clear(),this._isDirty=!0,this._missedImages.clear(),this._renderer.dispose()}async drainConvertQueue(){if(this._convertDrainPromise){await this._convertDrainPromise,this._convertQueue.length>0&&await this.drainConvertQueue();return}this._convertDrainPromise=(async()=>{for(;this._convertQueue.length>0;){const e=this._convertQueue.splice(0,this._convertQueue.length);await this.batchConvert(e)}})().finally(()=>{this._convertDrainPromise=null}),await this._convertDrainPromise}markProgressiveDirty(e=!1){const t=performance.now();(e||t-this._lastProgressivePaintAt>=ai.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS)&&(this._isDirty=!0,this._lastProgressivePaintAt=t)}highlight(e){this._isDirty=this._scene.select(e)}unhighlight(e){this._isDirty=this._scene.unselect(e)}stopAnimationLoop(){this._rafId!=null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}onHover(e){this._isDirty=this._scene.hover([e])}onUnhover(e){this._isDirty=this._scene.unhover([e])}createScene(){return new ml}createStats(e){const t=new Jh;document.body.appendChild(t.dom);const i=t.dom;return i.style.position="fixed",i.style.inset="unset",i.style.bottom="30px",i.style.right="0px",this.toggleStatsVisibility(t,e),t}onWindowResize(){super.onWindowResize(),this._renderer.setSize(this.width,this.height),this._css2dRenderer.setSize(this.width,this.height),this._layoutViewManager.resize(this.width,this.height),this._isDirty=!0}startAnimationLoop(){this._rafId==null&&(this._rafId=requestAnimationFrame(this.animate))}createLayoutViewIfNeeded(e){let t=this._layoutViewManager.getAt(e);return t==null&&(t=new Mb(this._renderer,e,this.width,this.height),t.events.viewChanged.addEventListener(()=>{this._progressiveOpenFit.onLayoutViewChanged(),this._isDirty=!0,this.events.viewChanged.dispatch(),this.clearHover()}),this._layoutViewManager.add(t)),t}loadLayoutEntitiesIfNeeded(e){try{const i=k.instance.curDocument.database.tables.blockTable.getIdAt(e);if(!i)return;const n=this._scene.layouts.get(e);if(n&&n.isLoaded||this._loadingLayouts.has(e))return;const r=this._layoutViewManager.getAt(e);if(n&&n.entityCount>0&&r&&r.viewportCount===0&&this.ensureViewportViews(i,r),n&&n.entityCount>0){n.isLoaded=!0;return}n||this._scene.addEmptyLayout(e);const o=[],a=i.newIterator();for(const c of a)o.push(c);if(o.length===0){const c=this._scene.layouts.get(e);c&&(c.isLoaded=!0);return}this._loadingLayouts.add(e),this._numOfEntitiesToProcess+=o.length,(async()=>{try{this._progressiveRendering?(this._convertQueue.push(...o),await this.drainConvertQueue()):await this.batchConvert(o);const c=this._scene.layouts.get(e);c&&(c.isLoaded=!0)}finally{this._loadingLayouts.delete(e)}})()}catch(t){d.log.error("[AcTrView2d] Error loading layout entities:",t)}}toggleStatsVisibility(e,t){t?e.dom.style.display="block":e.dom.style.display="none"}toLayerInfo(e){return{name:e.name,isFrozen:e.isFrozen,isOff:e.isOff,color:e.color}}resolveLayerInfo(e){const t=k.instance.curDocument.database.tables.layerTable.getAt(e);return t?this.toLayerInfo(t):void 0}async convertMissingEntitiesOnLayer(e){if(!this._convertingLayers.has(e)){this._convertingLayers.add(e);try{const i=k.instance.curDocument.database.tables.blockTable.getIdAt(this.activeLayoutBtrId);if(!i)return;const n=this._entityDisplay.collectMissingEntitiesOnLayer(e,i,r=>this.hasEntity(r));if(n.length===0)return;this._numOfEntitiesToProcess+=n.length,await this.batchConvert(n)}finally{this._convertingLayers.delete(e)}}}drawEntity(e,t){return e.worldDraw(this._renderer,t)}async finishEntityGeometry(e,t){if(e instanceof M.AcTrGroup){if(e.getSourceEntities().length===0&&!this.groupHasPendingGlyphGeometry(e))return;await e.asyncDraw();return}e.hasDrawableGeometry()||await e.asyncDraw()}needsDeferredFontGeometry(e){return e instanceof M.AcTrGlyphEntity||e instanceof M.AcTrGroup}groupHasPendingGlyphGeometry(e){let t=!1;return e.traverse(i=>{i instanceof M.AcTrGlyphEntity&&!i.hasDrawableGeometry()&&(t=!0)}),t}enqueueDeferredGeometry(e,t){t===this._convertEpoch&&(this._pendingGeometryJobs++,e().then(()=>{t===this._convertEpoch&&(this._isDirty=!0)}).catch(i=>{d.log.error("[AcTrView2d] Deferred entity geometry failed:",i)}).finally(()=>{t===this._convertEpoch&&(this._pendingGeometryJobs=Math.max(0,this._pendingGeometryJobs-1),this._pendingGeometryJobs===0&&(this._isDirty=!0))}))}async waitUntilDeferredGeometryIdle(){const e=this._convertEpoch;for(;e===this._convertEpoch&&this._pendingGeometryJobs>0;)await new Promise(t=>setTimeout(t,0))}ensureViewportViews(e,t){const i=e.newIterator();for(const n of i){if(!(n instanceof d.AcDbViewport)||M.AcTrViewportView.isDefaultPaperSpaceViewport(n))continue;const r=new M.AcTrViewportView(t,n.toGiViewport(),this._renderer);t.addViewport(r)}}async batchConvert(e,t={}){const i=this._convertEpoch,n=this._progressiveRendering&&!t.forExport,r=n?new d.AcCmUiYieldGate(ai.PROGRESSIVE_OPEN_YIELD_BUDGET_MS):void 0,o=()=>new Promise(a=>setTimeout(a,0));for(let a=0;a<e.length;++a){const l=e[a];try{if(i!==this._convertEpoch||l instanceof d.AcDbViewport&&M.AcTrViewportView.isDefaultPaperSpaceViewport(l)||!(t.forExport?this._entityDisplay.shouldConvertForExport(l):this._entityDisplay.shouldConvert(l)))continue;const h=il(l,this._renderer);if(h){let m=!1;try{m=this._scene.addDirectEntity(h,nl(l)),m&&(this.applySessionHiddenObjectState(l.objectId),n&&(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.resolveLayoutFitBox(),a)))}finally{h.geometry.dispose()}if(m)continue}const p=this.drawEntity(l,!1);if(!p&&!(l instanceof d.AcDbViewport))continue;if(p){p.objectId=l.objectId,p.ownerId=l.ownerId,p.layerName=l.layer,p.visible=l.visibility!==!1,p instanceof M.AcTrGroup&&p.isOnTheSameLayer&&(this._inheritedLayerMaterialMapper.remap(p.children,"0",p.layerName),p.userData.insertLayerName=p.layerName);const m=p instanceof M.AcTrGroup&&!p.isOnTheSameLayer,g=!t.forExport&&this.needsDeferredFontGeometry(p);if(m)g?this.enqueueDeferredGeometry(()=>this.handleGroup(p,n,i),i):await this.handleGroup(p,n,i);else{const f=!(l instanceof d.AcDbRay||l instanceof d.AcDbXline),w=async()=>{if(await this.finishEntityGeometry(p,n),i!==this._convertEpoch){p.dispose();return}p instanceof M.AcTrGroup&&this.syncGroupSpatialBoundsForIndexing(p),this._scene.addEntity(p,f),this.applySessionHiddenObjectState(l.objectId),p.dispose(),n&&(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.resolveLayoutFitBox(),a))};g?this.enqueueDeferredGeometry(w,i):await w()}}if(i!==this._convertEpoch)continue;if(l instanceof d.AcDbViewport){if(!M.AcTrViewportView.isDefaultPaperSpaceViewport(l)){const m=this._layoutViewManager.getAt(l.ownerId);if(m){const g=new M.AcTrViewportView(m,l.toGiViewport(),this._renderer);m.addViewport(g)}}}else if(l instanceof d.AcDbRasterImage){const m=l.imageFileName;m&&!l.image&&this._missedImages.set(l.objectId,m)}}catch(c){d.log.error(`[AcTrView2d] Failed to convert entity ${l.objectId} (${l.type}):`,c)}finally{i===this._convertEpoch&&this.decreaseNumOfEntitiesToProcess()}i===this._convertEpoch&&r&&await r.maybeYield(o)&&this._progressiveYieldCount++}}syncGroupSpatialBoundsForIndexing(e){if(e.refreshWcsChildBoxesFromChildren(),e.wcsChildBoxes.length===0)return;const t=e.wcsChildBoxes.map(n=>({minX:n.minX,minY:n.minY,maxX:n.maxX,maxY:n.maxY,id:n.id}));e.wcsBbox=pr(e);const i=e.userData;i.spatialIndexChildBoxes=t}async handleGroup(e,t,i=this._convertEpoch){if(await this.finishEntityGeometry(e,t),i!==this._convertEpoch){e.dispose();return}this.syncGroupSpatialBoundsForIndexing(e);const n=e.children,r=new Map;n.forEach(p=>{var g;if(p.visible===!1)return;const m=p.userData.layerName;r.has(m)||r.set(m,[]),(g=r.get(m))==null||g.push(p)}),e.children=[];for(const p of n)p.parent=null;const o=e.renderContext,a=e.objectId,l=e.layerName;process.env.NODE_ENV!=="production"&&nm(e);const c=e.wcsChildBoxes.map(p=>({minX:p.minX,minY:p.minY,maxX:p.maxX,maxY:p.maxY,id:p.id})),h=c.length>0?pr(e):e.wcsBbox.clone();c.length>0&&(e.wcsBbox=h.clone()),r.forEach((p,m)=>{const g=m==="0"?l:m,f=p.some(x=>(x.userData.authoredLayerName??m)==="0")?"0":m;this._inheritedLayerMaterialMapper.remap(p,f,g);const w=new M.AcTrEntity(o);w.applyMatrix4(e.matrix),w.objectId=a,w.ownerId=e.ownerId,w.layerName=g,w.userData.insertLayerName=l,w.wcsBbox=h.clone();const v=w.userData;v.spatialIndexChildBoxes=c;for(let x=0;x<p.length;x++)w.add(p[x]);this._layerAppearance.refreshTextMaterialsInObjectTree(w),this._scene.addEntity(w,!0),this.applySessionHiddenObjectState(a),w.dispose()}),e.dispose(),t&&(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.resolveLayoutFitBox()))}decreaseNumOfEntitiesToProcess(){this._numOfEntitiesToProcess--,this._numOfEntitiesToProcess<0?(this._numOfEntitiesToProcess=0,d.log.warn("Something wrong! The number of entities to process should not be less than 0.")):this._numOfEntitiesToProcess===0&&(this._isDirty=!0)}};ai.PROGRESSIVE_OPEN_YIELD_BUDGET_MS=300,ai.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS=1e3;let Zi=ai;function jb(s){if(!s)return!1;const e=Object.keys(s);return e.length>0&&e.every(t=>t==="visibility")}function Fb(s,e,t){const{entity:i,changes:n}=s,r=i.objectId;if(!e(r))return!1;if(jb(n))return!(n.visibility===!0&&t(r)===void 0);if(n&&Object.keys(n).length>0)return!1;const o=t(r);return o===void 0?!1:o&&!i.visibility}function Hh(s){return Array.isArray(s)?s:[s]}class Wh{constructor(e,t){this._view=e,this._doc=t,t.database.events.entityAppended.addEventListener(i=>{const n=Hh(i.entity).filter(r=>!this.view.hasEntity(r.objectId));n.length!==0&&this.view.addEntity(n.length===1?n[0]:n)}),t.database.events.entityModified.addEventListener(i=>{const n=i,r=this.view;r instanceof Zi&&Fb(n,o=>r.hasEntity(o),o=>r.getEntityVisible(o))&&r.updateEntityVisibility(n.entity)||this.view.updateEntity(n.entity)}),t.database.events.entityErased.addEventListener(i=>{const n=Hh(i.entity).filter(r=>this.view.hasEntity(r.objectId));n.length!==0&&this.view.removeEntity(n.length===1?n[0]:n)}),t.database.events.layerAppended.addEventListener(i=>{this._view.addLayer(i.layer)}),t.database.events.layerModified.addEventListener(i=>{this._view.updateLayer(i.layer,i.changes)}),d.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(i=>{if(i.name==d.AcDbSystemVariables.PDMODE.toLowerCase())this._view.rerenderPoints(i.database.pdmode);else if(i.name==d.AcDbSystemVariables.LWDISPLAY.toLowerCase()){const n=this._view,r=!!i.database.lwdisplay;n.renderer.showLineWeight!==r&&(n.renderer.showLineWeight=r,n.clear(),i.database.regen())}}),t.database.events.dictObjetSet.addEventListener(i=>{i.object instanceof d.AcDbLayout&&this._view.addLayout(i.object)}),e.selectionSet.events.selectionAdded.addEventListener(i=>{e.highlight(i.ids)}),e.selectionSet.events.selectionRemoved.addEventListener(i=>{e.unhighlight(i.ids)})}get view(){return this._view}get doc(){return this._doc}}function No(s){return typeof s.hasEntity=="function"&&typeof s.setEntitySceneVisible=="function"}function zb(s,e,t){!s.isObjectHidden(t)||!No(e)||e.setEntitySceneVisible(t,!1)}function $h(s,e){const t=s.view;if(!No(t))return 0;const i=s.doc,n=i.database;let r=0;for(const o of e){if(i.isObjectHidden(o))continue;const a=n.tables.blockTable.getEntityById(o);!(a!=null&&a.visibility)||!t.hasEntity(o)||t.setEntitySceneVisible(o,!1)&&(i.addHiddenObject(o),r++)}return r>0&&t.selectionSet.clear(),r}function Yh(s){const e=s.view;if(!No(e))return 0;const t=s.doc,i=t.database,n=t.takeHiddenObjects();let r=0;for(const o of n){const a=i.tables.blockTable.getEntityById(o);!a||!e.hasEntity(o)||e.setEntitySceneVisible(o,a.visibility)&&r++}return e.selectionSet.clear(),r}class Nb extends z{async execute(e){d.log.info("Hello from ExamplePlugin!"),d.log.info("Current document:",e.doc),d.log.info("Current view:",e.view)}}class Rb{constructor(){this.name="ExamplePlugin",this.version="1.0.0",this.description="An example plugin demonstrating the plugin system",this.registeredCommands=[]}onLoad(e,t){t.addCommand("USER","HELLO","Hello",new Nb),this.registeredCommands.push({group:"USER",name:"HELLO"}),d.log.info(`[${this.name}] Plugin loaded successfully`),d.log.info(`[${this.name}] Registered command: HELLO`)}onUnload(e,t){for(const i of this.registeredCommands)t.removeCmd(i.group,i.name);this.registeredCommands=[],d.log.info(`[${this.name}] Plugin unloaded`)}}Object.defineProperty(y,"ACGI_DARK_THEME_FOREGROUND",{enumerable:!0,get:()=>d.ACGI_DARK_THEME_FOREGROUND}),Object.defineProperty(y,"ACGI_LIGHT_THEME_FOREGROUND",{enumerable:!0,get:()=>d.ACGI_LIGHT_THEME_FOREGROUND}),Object.defineProperty(y,"ACGI_MODEL_SPACE_BACKGROUND",{enumerable:!0,get:()=>d.ACGI_MODEL_SPACE_BACKGROUND}),Object.defineProperty(y,"ACGI_PAPER_SPACE_BACKGROUND",{enumerable:!0,get:()=>d.ACGI_PAPER_SPACE_BACKGROUND}),Object.defineProperty(y,"acgiContrastingForegroundColor",{enumerable:!0,get:()=>d.acgiContrastingForegroundColor}),Object.defineProperty(y,"acgiForegroundColorForBackground",{enumerable:!0,get:()=>d.acgiForegroundColorForBackground}),Object.defineProperty(y,"acgiIsLightBackground",{enumerable:!0,get:()=>d.acgiIsLightBackground}),Object.defineProperty(y,"AcGiTextParagraphAlignment",{enumerable:!0,get:()=>D.MTextParagraphAlignment}),Object.defineProperty(y,"MTextColor",{enumerable:!0,get:()=>D.MTextColor}),Object.defineProperty(y,"MTextParagraphAlignment",{enumerable:!0,get:()=>D.MTextParagraphAlignment}),Object.defineProperty(y,"ShxParserFont",{enumerable:!0,get:()=>D.ShxParserFont}),y.ACAP_UNTITLED_DOC_TITLE=Io,y.AcApAboutCmd=$u,y.AcApArcCmd=Lc,y.AcApBlockInsertSession=es,y.AcApBlockPreviewConvertor=Fr,y.AcApCacheFontCmd=Ui,y.AcApCircleCmd=Bc,y.AcApCircleJig=Hr,y.AcApClearMarkupsCmd=ku,y.AcApClearMeasurementsCmd=Sd,y.AcApContext=Wh,y.AcApConvertToDxfCmd=nc,y.AcApConvertToPngCmd=oc,y.AcApCopyCmd=Ps,y.AcApDimJig=jc,y.AcApDimLinearCmd=Fc,y.AcApDocManager=k,y.AcApDocument=xh,y.AcApDrawStyleToolbar=vh,y.AcApDxfConvertor=ic,y.AcApEllipseCmd=Vc,y.AcApEntityPreviewCmd=cc,y.AcApEntityPreviewConvertor=ac,y.AcApEntityService=zr,y.AcApEraseCmd=Ru,y.AcApExamplePlugin=Rb,y.AcApFontLoader=Ph,y.AcApFontUtil=Yi,y.AcApHatchCmd=Qn,y.AcApHideObjectsCmd=Vu,y.AcApI18n=u,y.AcApImageAttachCmd=Gc,y.AcApInsertCmd=Uc,y.AcApLayerCloseCmd=kc,y.AcApLayerCmd=xc,y.AcApLayerCurCmd=mc,y.AcApLayerDelCmd=pc,y.AcApLayerFreezeCmd=Hn,y.AcApLayerIsoCmd=Wn,y.AcApLayerLockCmd=yc,y.AcApLayerOnCmd=gc,y.AcApLayerPCmd=fc,y.AcApLayerService=te,y.AcApLayerStore=dc,y.AcApLayerThawCmd=bc,y.AcApLayerUnisoCmd=wc,y.AcApLayerUnlockCmd=vc,y.AcApLayoffCmd=$n,y.AcApLineCmd=At,y.AcApLineJig=Zn,y.AcApLogCmd=Yu,y.AcApMLineCmd=Wc,y.AcApMLineJig=Hc,y.AcApMTextCmd=$c,y.AcApMarkupArrowCmd=xu,y.AcApMarkupCalloutCmd=Su,y.AcApMarkupCalloutEntity=pu,y.AcApMarkupCircleCmd=Pu,y.AcApMarkupCloudCmd=Au,y.AcApMarkupEntity=It,y.AcApMarkupExportCmd=Iu,y.AcApMarkupHighlightCmd=Cu,y.AcApMarkupHighlightEntity=mu,y.AcApMarkupHistory=da,y.AcApMarkupImportCmd=Mu,y.AcApMarkupLineCmd=Du,y.AcApMarkupPresenter=wu,y.AcApMarkupRectCmd=Ou,y.AcApMarkupSegmentEntity=yu,y.AcApMarkupShapeEntity=gu,y.AcApMarkupStampCmd=ju,y.AcApMarkupStampEntity=fu,y.AcApMarkupStore=Qo,y.AcApMarkupTextCmd=Fu,y.AcApMarkupTextEntity=bu,y.AcApMarkupVisibilityCmd=Nu,y.AcApMeasureAngleCmd=Fd,y.AcApMeasureAngleEntity=Di,y.AcApMeasureArcCmd=Hd,y.AcApMeasureArcEntity=Oi,y.AcApMeasureAreaCmd=Nd,y.AcApMeasureAreaEntity=Bi,y.AcApMeasureDistanceCmd=Yd,y.AcApMeasureDistanceEntity=ji,y.AcApMeasureDistanceJig=$d,y.AcApMeasureEntity=ei,y.AcApMeasurePointCmd=Xd,y.AcApMeasurePointEntity=Fi,y.AcApMeasurementExportCmd=Od,y.AcApMeasurementHistory=pa,y.AcApMeasurementImportCmd=Bd,y.AcApMeasurementVisibilityCmd=Pd,y.AcApMemoryProfiler=Hf,y.AcApMoveCmd=Ku,y.AcApOffsetCmd=Gi,y.AcApOpenCmd=eh,y.AcApOpenFileProfiler=Is,y.AcApOpenViewMode=$i,y.AcApOverlayEntity=ho,y.AcApPanCmd=lh,y.AcApPluginManager=ch,y.AcApPngConvertor=sc,y.AcApPointCmd=Yc,y.AcApPolygonCmd=is,y.AcApPolylineCmd=Jc,y.AcApPolylineJig=qc,y.AcApProgress=Hi,y.AcApQNewCmd=th,y.AcApRayCmd=ed,y.AcApRectCmd=ns,y.AcApRectJig=id,y.AcApRedoCmd=ah,y.AcApRegenCmd=ih,y.AcApRevCloudCmd=ss,y.AcApRevCloudJig=ud,y.AcApRotateCmd=Cs,y.AcApSelectCmd=nh,y.AcApSessionUndo=ua,y.AcApSettingManager=ue,y.AcApSketchCmd=ls,y.AcApSketchJig=md,y.AcApSplineCmd=gd,y.AcApSplineJig=yd,y.AcApSwitchBgCmd=rh,y.AcApSysVarCmd=sh,y.AcApUndoCmd=oh,y.AcApUnisolateObjectsCmd=Wu,y.AcApXAttachCmd=vd,y.AcApXLineCmd=kd,y.AcApXrefManager=Dt,y.AcApZoomCmd=Mt,y.AcEdBaseView=ec,y.AcEdBatchedPreview=Dr,y.AcEdCommand=z,y.AcEdCommandLine=Wl,y.AcEdCommandStack=de,y.AcEdConditionWaiter=wr,y.AcEdCorsorType=Le,y.AcEdCursorManager=Ml,y.AcEdGripEditSession=El,y.AcEdGripHandle=Mn,y.AcEdGripManager=Il,y.AcEdGripPreviewJig=_l,y.AcEdHoverController=Jl,y.AcEdInputManager=Gn,y.AcEdKeyword=Cr,y.AcEdKeywordCollection=Gl,y.AcEdMTextEditor=He,y.AcEdMarker=In,y.AcEdMarkerManager=Ar,y.AcEdOpenMode=F,y.AcEdOsnapResolver=ft,y.AcEdPreviewJig=R,y.AcEdPromptAngleOptions=Se,y.AcEdPromptBoxOptions=Bn,y.AcEdPromptBoxResult=jn,y.AcEdPromptDistanceOptions=be,y.AcEdPromptDoubleOptions=ie,y.AcEdPromptDoubleResult=Pe,y.AcEdPromptEntityOptions=$e,y.AcEdPromptEntityResult=zn,y.AcEdPromptIntegerOptions=Er,y.AcEdPromptIntegerResult=Nn,y.AcEdPromptKeywordOptions=ne,y.AcEdPromptNumericalOptions=Fn,y.AcEdPromptNumericalResult=_r,y.AcEdPromptOptions=We,y.AcEdPromptPointOptions=T,y.AcEdPromptPointResult=Rn,y.AcEdPromptResult=Fe,y.AcEdPromptSelectionOptions=Pt,y.AcEdPromptSelectionResult=xi,y.AcEdPromptStateMachine=Ye,y.AcEdPromptStatus=b,y.AcEdPromptStringOptions=ce,y.AcEdSelectionFilter=my,y.AcEdSelectionSet=On,y.AcEdSelectionStaticPreviewJig=ql,y.AcEdSelectionTransformPreviewJig=$t,y.AcEdViewKeyHandler=kn,y.AcEdViewMode=ye,y.AcEditor=Xl,y.AcTrGeometryUtil=Bo,y.AcTrInheritedLayerMaterialMapper=sl,y.AcTrLayerAppearanceController=al,y.AcTrScene=ml,y.AcTrView2d=Zi,y.AcUiAboutDialog=Es,y.AcUiDialog=_s,y.DEFAULT_VIEW_2D_OPTIONS=zo,y.DWG_CONVERTER_PACKAGE=bb,y.DWG_PARSER_MAIN_FILE=yb,y.DWG_PARSER_WORKER_FILE=mb,y.ENTITY_EDIT_LABEL=ol,y.LAYER_EDIT_LABEL=H,y.LAYER_FROZEN_FLAG=ur,y.LAYER_LOCKED_FLAG=Rt,y.LIBREDWG_CONVERTER_PACKAGE=gb,y.LIBREDWG_PARSER_WASM_FILE=pb,y.LIBREDWG_PARSER_WORKER_FILE=hb,y.MARKUP_FONT_SIZE=qd,y.MARKUP_LAYER=ln,y.MARKUP_LINE_WEIGHT=ms,y.MARKUP_LIVE_LAYER=le,y.MARKUP_OPEN_MODE=au,y.MARKUP_STATUSES=ea,y.MEASUREMENT_ANGLE_FORMAT_OPTIONS=na,y.MEASUREMENT_FONT_SIZE=jt,y.MEASUREMENT_LAYER=W,y.MEASUREMENT_LENGTH_FORMAT_OPTIONS=ia,y.MEASUREMENT_LINE_WEIGHT=Bt,y.MEASUREMENT_LIVE_LAYER=oe,y.MLIGHTCAD_BRAND_NAME=nn,y.MLIGHTCAD_DOCS_URL=Wo,y.MLIGHTCAD_ICON_SVG=Uo,y.MLIGHTCAD_REPO_URL=$o,y.MLIGHTCAD_WEBSITE_URL=Ho,y.ML_UI_COMPACT_MAX_WIDTH=xl,y.ML_UI_COMPACT_MEDIA_QUERY=Sl,y.ML_UI_MOBILE_MAX_WIDTH=vl,y.ML_UI_MOBILE_MEDIA_QUERY=kl,y.MTEXT_RENDERER_PACKAGE=fb,y.MTEXT_RENDERER_WORKER_FILE=Mh,y.POLARMODE_ADDITIONAL_ANGLES=Bl,y.POLARMODE_POLAR_TRACKING=Wt,y.REVCLOUD_BULGE=io,y.REVIEW_OVERLAY_HIT_THRESHOLD_PX=Da,y.acapBindCommandServices=wl,y.acapBindOverlayCalloutGrips=hs,y.acapBindOverlayPointerDrag=Lt,y.acapCloneMeasurementStyle=ci,y.acapColorToCssAlpha=Xs,y.acapCommandServices=vi,y.acapCreateMlightcadBrandMark=Yo,y.acapCreateMlightcadIcon=zs,y.acapCssColor=ve,y.acapCssToMeasurementColor=qs,y.acapDrawOverlayArrowHead=us,y.acapDrawOverlayHighlight=uo,y.acapDrawOverlayLeader=co,y.acapDrawStyleKindForCommand=uh,y.acapFitOverlayCanvas=Et,y.acapGetCurrentMeasurementStyle=ut,y.acapGetMeasurementColor=Oe,y.acapGetMeasurementFontSize=Be,y.acapGetMeasurementLineWeight=tt,y.acapInstallOpenFileDialog=Eh,y.acapIsDrawStyleHostRibbonVisible=ph,y.acapIsDrawStyleToolbarVisible=Zf,y.acapMeasurementCanvasLineWidth=Ee,y.acapNotifyUndoStackChanged=ht,y.acapPlaceOverlayHtml=Xe,y.acapPointerEventToOverlayWorld=po,y.acapResetMeasurementDrawStyle=cp,y.acapResolveDrawStyleKind=hh,y.acapRunDatabaseEdit=pt,y.acapRunServiceEdit=U,y.acapSetDrawStyleHostHasRibbon=Yf,y.acapSetDrawStyleToolbarVisible=Lo,y.acapSetMeasurementDrawColor=oa,y.acapSetMeasurementDrawFontSize=la,y.acapSetMeasurementDrawLineWeight=aa,y.acapShouldShowDrawStyleToolbar=mh,y.acapSubscribeDrawStyleToolbarVisibility=Xf,y.acapUninstallOpenFileDialog=Th,y.acapUpdateOpenFileDialogOptions=Lh,y.acapWithSecondaryDatabase=ao,y.accumulateSketchPoint=hd,y.acedAlert=vm,y.acedApplyUiTheme=vr,y.acedIsCompactUiLayout=Sm,y.acedIsMobileUiLayout=xm,y.applyMarkupStyleToSelection=Ss,y.applyMeasurementStyle=sr,y.applyMeasurementStyleToSelection=hn,y.applySessionHiddenObjectState=zb,y.bindMarkupCalloutGrips=Pf,y.bindMarkupCenterMove=Vi,y.bindMarkupInlineTextEdit=En,y.bindMarkupPointerDrag=Sf,y.bindMeasurementOverlayHistory=fa,y.bindOverlayHistory=ca,y.buildMarkupCloud=uf,y.buildMarkupRect=hf,y.buildRevCloud=ld,y.canvasBackgroundFromColor=el,y.clearLayoutMeasurements=xd,y.cmdDescription=Lr,y.collectMeasurementRecords=Ea,y.collectMemorySnapshot=Qu,y.collectReviewOverlayIdsByBox=ja,y.commitMarkup=Ge,y.commitMeasurementGroup=Ta,y.computeLeaderTipOnShape=ni,y.configureMarkupCommand=Re,y.constrainToOrtho=Ol,y.constrainToTracking=Vl,y.createDefaultMarkupColor=wo,y.createMarkupEntity=bf,y.createMarkupEntityFromRecord=xs,y.createMarkupId=su,y.createMarkupMeta=Ve,y.createMeasureEntityFromRecord=Md,y.createRotationMatrix=Yt,y.cssToMarkupColor=xo,y.cursorColorForBackground=wn,y.defaultMarkupColor=J,y.defaultMarkupStyle=gs,y.defaultRevCloudArcLength=sd,y.deserializeMeasurementStyle=ba,y.distPointToArcPx=Vs,y.distPointToCirclePx=Rs,y.distPointToPolylinePx=Ns,y.distPointToRectOutlinePx=sn,y.distPointToSegmentPx=kt,y.distance2d=Ct,y.drawMeasureAngleArcOnCanvas=Cd,y.drawMeasureArcOnCanvas=Ed,y.drawMeasureAreaOnCanvas=_d,y.drawMeasureSegmentOnCanvas=Ad,y.editMarkupHtmlText=fr,y.ensureCounterClockwise=od,y.eventBus=ee,y.foregroundColorFromColorTheme=qp,y.formatMeasurementAngle=cn,y.formatMeasurementLength=_e,y.formatMeasurementValue=$s,y.formatMemoryBytes=Zu,y.geBox2dToThreeBox2d=Rh,y.geBox2dToThreeBox3d=Gh,y.geBox3dToGeBox2d=Fh,y.geBox3dToThreeBox3d=zh,y.getActiveMeasurementStyle=Aa,y.getDrawingExportBaseName=tc,y.getEffectiveMeasurementUnits=Ws,y.getLastFontLoadStats=Sh,y.getLayerIsoState=hr,y.getMarkupAuthor=ou,y.getMarkupFontSize=qe,y.getMarkupHistory=fe,y.getMarkupLineWeight=Ae,y.getMarkupPresenter=ot,y.getMarkupStore=K,y.getMeasurementGeometry=rr,y.getMeasurementHistory=it,y.getMeasurementStyle=St,y.getMeasurementUnitOverride=op,y.getPolaraddang=zl,y.getPolarang=Fl,y.getPolarmode=Dn,y.getSelectedMeasurementId=Pa,y.getSessionUndo=xt,y.hideObjects=$h,y.hitTestMarkupGeometry=Ks,y.hitTestMeasurementGeometry=Hs,y.isDirectBatchCandidate=em,y.isEffectiveSpatialQueryHit=Sn,y.isInsertableBlockName=Kc,y.isLightColorTheme=Jp,y.isMarkupDoublePointer=bl,y.isMarkupHtmlTextEditing=fl,y.isMarkupShapeCalloutEnabled=pf,y.isMarkupVisible=Ff,y.isMeasurementVisible=ir,y.isModelSpaceDatabase=Qa,y.isOpenFileProgressComplete=Ih,y.isOrthoModeEnabled=Dl,y.isPolarTrackingEnabled=Nl,y.isRevCloudCloseToStart=so,y.isSameLayerIsoState=rl,y.isScriptQuitCommand=kh,y.layoutBackgroundSysVar=dr,y.markupCanvasLineWidth=Ne,y.markupCloudVertices=Ni,y.markupColorToCss=Tt,y.markupDrawStyleFromRecord=cu,y.markupGeometryBounds=Jo,y.markupGeometryCenter=on,y.markupNow=ru,y.markupRectCorners=du,y.markupSidecarFileName=Tu,y.measureAngleDeg=Td,y.measureCentroid=lo,y.measureShoelaceArea=Ld,y.measurementGeometryBounds=ta,y.measurementSidecarFileName=ka,y.migrateStoredSettings=Pl,y.parseMarkupSidecar=Eu,y.parseMeasurementSidecar=wa,y.parseScriptLines=To,y.pickMeasurementAt=Ia,y.placeAngleMeasurement=jd,y.placeArcMeasurement=bo,y.placeAreaMeasurement=zd,y.placeDistanceMeasurement=Wd,y.placeMarkupHtml=xf,y.placeMeasurementRecord=Dd,y.placePointMeasurement=Zd,y.pointInPolygonPx=Xo,y.pointInRectPx=Zo,y.pointerEventToMarkupWorld=kf,y.preferExactAciColor=li,y.promptAttachedCallout=ks,y.promptMarkupCapsuleText=fs,y.promptMarkupText=So,y.promptShapeFirstCorner=vs,y.publishAttachedCallout=hu,y.readLayoutBackgroundColor=bn,y.rectanglePath=no,y.refreshMeasurementValueLabels=wp,y.registerMarkupPublish=lu,y.republishMarkup=zi,y.resetExportDownloadNamesForTests=yy,y.resetMarkupSession=vu,y.resetMeasurementSession=ga,y.resetMeasurementStyleState=La,y.resetMeasurementUnitOverride=sa,y.resetMeasurementVisibility=xa,y.resolveExportDownloadName=jr,y.resolvePointerSelectionAction=Ql,y.resolveSelectedEntities=Un,y.resolveSelectedIds=hc,y.resolveSelectionActionFromEvent=Or,y.resolveUiTheme=kr,y.runMarkupEdit=ke,y.runMeasurementEdit=Ft,y.sampleEntityPath=dd,y.scaleCopyDisplacement=Kn,y.selectMarkupGroup=Ri,y.serializeMeasurementStyle=mt,y.setMarkupDrawColor=tu,y.setMarkupDrawFontSize=nu,y.setMarkupDrawLineWeight=iu,y.setMarkupShapeCalloutEnabled=mf,y.setMarkupVisible=zu,y.setMeasurementUnitOverride=ap,y.setMeasurementVisible=Sa,y.shouldExtendBboxForDirectEntity=nl,y.signedArea=rd,y.simplifySketchPoints=pd,y.stringifyMarkupSidecar=Lu,y.stringifyMeasurementSidecar=va,y.strokeMarkupCloud=uu,y.strokeMeasureArcOnContext=ds,y.subscribeMarkupDrawStyle=ys,y.subscribeMeasurementSelection=Ca,y.sysCmdDescription=sy,y.tessellateMarkupCloud=ws,y.threeBox2dToGeBox2d=Nh,y.threeBox3dToGeBox2d=Vh,y.threeBox3dToGeBox3d=jh,y.toggleBlackWhiteBackgroundColor=tl,y.togglePolarTracking=Hm,y.translateAttachedCallout=rn,y.translateMarkupGeometry=Gs,y.translateMarkupPoint=ae,y.tryBuildDirectEntityMeta=il,y.trySelectReviewOverlay=Fa,y.trySelectReviewOverlaysByBox=za,y.unionSpatialQueryItems=xn,y.uniquifySpatialItemIds=ll,y.unisolateObjects=Yh,y.userCmdDescription=ry,y.viewDiagonalLength=nd,y.withMarkupInput=Je,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));