@mlightcad/cad-simple-viewer 1.6.1 → 1.6.3

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 (281) hide show
  1. package/dist/cad-simple-viewer.js +12123 -8535
  2. package/dist/cad-simple-viewer.umd.cjs +180 -29
  3. package/icons.ts +7 -0
  4. package/lib/app/AcApBusyIndicator.d.ts +6 -0
  5. package/lib/app/AcApBusyIndicator.d.ts.map +1 -1
  6. package/lib/app/AcApBusyIndicator.js +8 -0
  7. package/lib/app/AcApBusyIndicator.js.map +1 -1
  8. package/lib/app/AcApContext.d.ts +24 -0
  9. package/lib/app/AcApContext.d.ts.map +1 -1
  10. package/lib/app/AcApContext.js +103 -18
  11. package/lib/app/AcApContext.js.map +1 -1
  12. package/lib/app/AcApDocManager.d.ts +221 -21
  13. package/lib/app/AcApDocManager.d.ts.map +1 -1
  14. package/lib/app/AcApDocManager.js +820 -134
  15. package/lib/app/AcApDocManager.js.map +1 -1
  16. package/lib/app/AcApDocSession.d.ts +41 -0
  17. package/lib/app/AcApDocSession.d.ts.map +1 -0
  18. package/lib/app/AcApDocSession.js +29 -0
  19. package/lib/app/AcApDocSession.js.map +1 -0
  20. package/lib/app/AcApDocument.d.ts +5 -0
  21. package/lib/app/AcApDocument.d.ts.map +1 -1
  22. package/lib/app/AcApDocument.js +21 -0
  23. package/lib/app/AcApDocument.js.map +1 -1
  24. package/lib/app/AcApOpenFileProgressController.d.ts +14 -0
  25. package/lib/app/AcApOpenFileProgressController.d.ts.map +1 -1
  26. package/lib/app/AcApOpenFileProgressController.js +18 -0
  27. package/lib/app/AcApOpenFileProgressController.js.map +1 -1
  28. package/lib/app/AcApProgress.d.ts +6 -0
  29. package/lib/app/AcApProgress.d.ts.map +1 -1
  30. package/lib/app/AcApProgress.js +17 -0
  31. package/lib/app/AcApProgress.js.map +1 -1
  32. package/lib/app/AcApSettingManager.d.ts.map +1 -1
  33. package/lib/app/AcApSettingManager.js +1 -0
  34. package/lib/app/AcApSettingManager.js.map +1 -1
  35. package/lib/app/index.d.ts +1 -0
  36. package/lib/app/index.d.ts.map +1 -1
  37. package/lib/app/index.js +1 -0
  38. package/lib/app/index.js.map +1 -1
  39. package/lib/command/AcApCloseCmd.d.ts +15 -0
  40. package/lib/command/AcApCloseCmd.d.ts.map +1 -0
  41. package/lib/command/AcApCloseCmd.js +83 -0
  42. package/lib/command/AcApCloseCmd.js.map +1 -0
  43. package/lib/command/draw/AcApArcCmd.d.ts.map +1 -1
  44. package/lib/command/draw/AcApArcCmd.js +28 -312
  45. package/lib/command/draw/AcApArcCmd.js.map +1 -1
  46. package/lib/command/draw/AcApCircleCmd.d.ts.map +1 -1
  47. package/lib/command/draw/AcApCircleCmd.js +10 -42
  48. package/lib/command/draw/AcApCircleCmd.js.map +1 -1
  49. package/lib/command/index.d.ts +1 -0
  50. package/lib/command/index.d.ts.map +1 -1
  51. package/lib/command/index.js +1 -0
  52. package/lib/command/index.js.map +1 -1
  53. package/lib/command/markup/AcApMarkupCalloutCmd.d.ts.map +1 -1
  54. package/lib/command/markup/AcApMarkupCalloutCmd.js +29 -10
  55. package/lib/command/markup/AcApMarkupCalloutCmd.js.map +1 -1
  56. package/lib/command/markup/AcApMarkupGeometry.d.ts +20 -1
  57. package/lib/command/markup/AcApMarkupGeometry.d.ts.map +1 -1
  58. package/lib/command/markup/AcApMarkupGeometry.js +84 -24
  59. package/lib/command/markup/AcApMarkupGeometry.js.map +1 -1
  60. package/lib/command/markup/AcApMarkupHistory.d.ts +1 -1
  61. package/lib/command/markup/AcApMarkupHistory.d.ts.map +1 -1
  62. package/lib/command/markup/AcApMarkupHistory.js +4 -11
  63. package/lib/command/markup/AcApMarkupHistory.js.map +1 -1
  64. package/lib/command/markup/AcApMarkupPresenter.d.ts +8 -2
  65. package/lib/command/markup/AcApMarkupPresenter.d.ts.map +1 -1
  66. package/lib/command/markup/AcApMarkupPresenter.js +35 -5
  67. package/lib/command/markup/AcApMarkupPresenter.js.map +1 -1
  68. package/lib/command/markup/AcApMarkupSession.d.ts +54 -0
  69. package/lib/command/markup/AcApMarkupSession.d.ts.map +1 -0
  70. package/lib/command/markup/AcApMarkupSession.js +85 -0
  71. package/lib/command/markup/AcApMarkupSession.js.map +1 -0
  72. package/lib/command/markup/AcApMarkupSessionBootstrap.d.ts +2 -0
  73. package/lib/command/markup/AcApMarkupSessionBootstrap.d.ts.map +1 -0
  74. package/lib/command/markup/AcApMarkupSessionBootstrap.js +12 -0
  75. package/lib/command/markup/AcApMarkupSessionBootstrap.js.map +1 -0
  76. package/lib/command/markup/AcApMarkupShapeCallout.d.ts +21 -1
  77. package/lib/command/markup/AcApMarkupShapeCallout.d.ts.map +1 -1
  78. package/lib/command/markup/AcApMarkupShapeCallout.js +29 -22
  79. package/lib/command/markup/AcApMarkupShapeCallout.js.map +1 -1
  80. package/lib/command/markup/AcApMarkupStore.d.ts +1 -1
  81. package/lib/command/markup/AcApMarkupStore.d.ts.map +1 -1
  82. package/lib/command/markup/AcApMarkupStore.js +3 -6
  83. package/lib/command/markup/AcApMarkupStore.js.map +1 -1
  84. package/lib/command/markup/AcApMarkupTextCmd.d.ts.map +1 -1
  85. package/lib/command/markup/AcApMarkupTextCmd.js +8 -2
  86. package/lib/command/markup/AcApMarkupTextCmd.js.map +1 -1
  87. package/lib/command/markup/AcApMarkupTextEdit.d.ts.map +1 -1
  88. package/lib/command/markup/AcApMarkupTextEdit.js +3 -1
  89. package/lib/command/markup/AcApMarkupTextEdit.js.map +1 -1
  90. package/lib/command/markup/AcApMarkupUtil.d.ts.map +1 -1
  91. package/lib/command/markup/AcApMarkupUtil.js +3 -2
  92. package/lib/command/markup/AcApMarkupUtil.js.map +1 -1
  93. package/lib/command/markup/index.d.ts +2 -0
  94. package/lib/command/markup/index.d.ts.map +1 -1
  95. package/lib/command/markup/index.js +3 -0
  96. package/lib/command/markup/index.js.map +1 -1
  97. package/lib/command/measure/AcApMeasureArcCmd.d.ts +22 -25
  98. package/lib/command/measure/AcApMeasureArcCmd.d.ts.map +1 -1
  99. package/lib/command/measure/AcApMeasureArcCmd.js +480 -256
  100. package/lib/command/measure/AcApMeasureArcCmd.js.map +1 -1
  101. package/lib/command/measure/AcApMeasureArcLock.d.ts +40 -0
  102. package/lib/command/measure/AcApMeasureArcLock.d.ts.map +1 -0
  103. package/lib/command/measure/AcApMeasureArcLock.js +226 -0
  104. package/lib/command/measure/AcApMeasureArcLock.js.map +1 -0
  105. package/lib/command/measure/AcApMeasurementGeometry.d.ts.map +1 -1
  106. package/lib/command/measure/AcApMeasurementGeometry.js +9 -9
  107. package/lib/command/measure/AcApMeasurementGeometry.js.map +1 -1
  108. package/lib/command/measure/AcApMeasurementSidecar.d.ts.map +1 -1
  109. package/lib/command/measure/AcApMeasurementSidecar.js +12 -7
  110. package/lib/command/measure/AcApMeasurementSidecar.js.map +1 -1
  111. package/lib/command/measure/AcApMeasurementStore.d.ts +2 -0
  112. package/lib/command/measure/AcApMeasurementStore.d.ts.map +1 -1
  113. package/lib/command/measure/AcApMeasurementStore.js +4 -0
  114. package/lib/command/measure/AcApMeasurementStore.js.map +1 -1
  115. package/lib/command/measure/AcApMeasurementTypes.d.ts +6 -0
  116. package/lib/command/measure/AcApMeasurementTypes.d.ts.map +1 -1
  117. package/lib/command/measure/entity/AcApMeasureArcEntity.d.ts +24 -22
  118. package/lib/command/measure/entity/AcApMeasureArcEntity.d.ts.map +1 -1
  119. package/lib/command/measure/entity/AcApMeasureArcEntity.js +104 -41
  120. package/lib/command/measure/entity/AcApMeasureArcEntity.js.map +1 -1
  121. package/lib/command/measure/entity/AcApMeasureDrawUtil.d.ts +35 -38
  122. package/lib/command/measure/entity/AcApMeasureDrawUtil.d.ts.map +1 -1
  123. package/lib/command/measure/entity/AcApMeasureDrawUtil.js +42 -53
  124. package/lib/command/measure/entity/AcApMeasureDrawUtil.js.map +1 -1
  125. package/lib/command/measure/entity/AcApMeasureEntityFactory.d.ts.map +1 -1
  126. package/lib/command/measure/entity/AcApMeasureEntityFactory.js +1 -1
  127. package/lib/command/measure/entity/AcApMeasureEntityFactory.js.map +1 -1
  128. package/lib/command/modify/AcApEraseCmd.d.ts +1 -0
  129. package/lib/command/modify/AcApEraseCmd.d.ts.map +1 -1
  130. package/lib/command/modify/AcApEraseCmd.js +4 -2
  131. package/lib/command/modify/AcApEraseCmd.js.map +1 -1
  132. package/lib/editor/grip/AcEdGripEditSession.d.ts.map +1 -1
  133. package/lib/editor/grip/AcEdGripEditSession.js +2 -0
  134. package/lib/editor/grip/AcEdGripEditSession.js.map +1 -1
  135. package/lib/editor/input/AcEdOsnapCenterMarks.d.ts +23 -0
  136. package/lib/editor/input/AcEdOsnapCenterMarks.d.ts.map +1 -0
  137. package/lib/editor/input/AcEdOsnapCenterMarks.js +240 -0
  138. package/lib/editor/input/AcEdOsnapCenterMarks.js.map +1 -0
  139. package/lib/editor/input/AcEdOsnapResolver.d.ts +18 -0
  140. package/lib/editor/input/AcEdOsnapResolver.d.ts.map +1 -1
  141. package/lib/editor/input/AcEdOsnapResolver.js +159 -10
  142. package/lib/editor/input/AcEdOsnapResolver.js.map +1 -1
  143. package/lib/editor/input/marker/AcEdMarker.d.ts +1 -1
  144. package/lib/editor/input/marker/AcEdMarker.d.ts.map +1 -1
  145. package/lib/editor/input/marker/AcEdMarker.js +11 -1
  146. package/lib/editor/input/marker/AcEdMarker.js.map +1 -1
  147. package/lib/editor/input/marker/AcEdOSnapMarkerManager.d.ts +17 -1
  148. package/lib/editor/input/marker/AcEdOSnapMarkerManager.d.ts.map +1 -1
  149. package/lib/editor/input/marker/AcEdOSnapMarkerManager.js +71 -10
  150. package/lib/editor/input/marker/AcEdOSnapMarkerManager.js.map +1 -1
  151. package/lib/editor/input/ui/AcEdFloatingInput.d.ts.map +1 -1
  152. package/lib/editor/input/ui/AcEdFloatingInput.js +4 -0
  153. package/lib/editor/input/ui/AcEdFloatingInput.js.map +1 -1
  154. package/lib/editor/view/AcEdBaseView.d.ts +12 -0
  155. package/lib/editor/view/AcEdBaseView.d.ts.map +1 -1
  156. package/lib/editor/view/AcEdBaseView.js +29 -1
  157. package/lib/editor/view/AcEdBaseView.js.map +1 -1
  158. package/lib/i18n/AcApI18n.d.ts +1 -1
  159. package/lib/i18n/AcApI18n.d.ts.map +1 -1
  160. package/lib/i18n/AcApI18n.js +2 -1
  161. package/lib/i18n/AcApI18n.js.map +1 -1
  162. package/lib/i18n/ar/command.d.ts +456 -0
  163. package/lib/i18n/ar/command.d.ts.map +1 -0
  164. package/lib/i18n/ar/command.js +14 -0
  165. package/lib/i18n/ar/command.js.map +1 -0
  166. package/lib/i18n/ar/jig.d.ts +1231 -0
  167. package/lib/i18n/ar/jig.d.ts.map +1 -0
  168. package/lib/i18n/ar/jig.js +594 -0
  169. package/lib/i18n/ar/jig.js.map +1 -0
  170. package/lib/i18n/ar/main.d.ts +64 -0
  171. package/lib/i18n/ar/main.d.ts.map +1 -0
  172. package/lib/i18n/ar/main.js +63 -0
  173. package/lib/i18n/ar/main.js.map +1 -0
  174. package/lib/i18n/cs/command.d.ts +3 -0
  175. package/lib/i18n/cs/command.d.ts.map +1 -1
  176. package/lib/i18n/cs/command.js +3 -0
  177. package/lib/i18n/cs/command.js.map +1 -1
  178. package/lib/i18n/cs/jig.d.ts +3 -0
  179. package/lib/i18n/cs/jig.d.ts.map +1 -1
  180. package/lib/i18n/cs/jig.js +7 -4
  181. package/lib/i18n/cs/jig.js.map +1 -1
  182. package/lib/i18n/en/command.d.ts +3 -0
  183. package/lib/i18n/en/command.d.ts.map +1 -1
  184. package/lib/i18n/en/command.js +3 -0
  185. package/lib/i18n/en/command.js.map +1 -1
  186. package/lib/i18n/en/jig.d.ts +3 -0
  187. package/lib/i18n/en/jig.d.ts.map +1 -1
  188. package/lib/i18n/en/jig.js +7 -4
  189. package/lib/i18n/en/jig.js.map +1 -1
  190. package/lib/i18n/index.d.ts.map +1 -1
  191. package/lib/i18n/index.js +8 -0
  192. package/lib/i18n/index.js.map +1 -1
  193. package/lib/i18n/tr/command.d.ts +3 -0
  194. package/lib/i18n/tr/command.d.ts.map +1 -1
  195. package/lib/i18n/tr/command.js +3 -0
  196. package/lib/i18n/tr/command.js.map +1 -1
  197. package/lib/i18n/tr/jig.d.ts +3 -0
  198. package/lib/i18n/tr/jig.d.ts.map +1 -1
  199. package/lib/i18n/tr/jig.js +7 -4
  200. package/lib/i18n/tr/jig.js.map +1 -1
  201. package/lib/i18n/zh/command.d.ts +3 -0
  202. package/lib/i18n/zh/command.d.ts.map +1 -1
  203. package/lib/i18n/zh/command.js +3 -0
  204. package/lib/i18n/zh/command.js.map +1 -1
  205. package/lib/i18n/zh/jig.d.ts +3 -0
  206. package/lib/i18n/zh/jig.d.ts.map +1 -1
  207. package/lib/i18n/zh/jig.js +7 -4
  208. package/lib/i18n/zh/jig.js.map +1 -1
  209. package/lib/plugin/AcApPluginManager.d.ts +10 -0
  210. package/lib/plugin/AcApPluginManager.d.ts.map +1 -1
  211. package/lib/plugin/AcApPluginManager.js +18 -0
  212. package/lib/plugin/AcApPluginManager.js.map +1 -1
  213. package/lib/service/AcApEntityService.d.ts +4 -2
  214. package/lib/service/AcApEntityService.d.ts.map +1 -1
  215. package/lib/service/AcApEntityService.js +14 -10
  216. package/lib/service/AcApEntityService.js.map +1 -1
  217. package/lib/ui/AcApDrawStyle.d.ts +19 -1
  218. package/lib/ui/AcApDrawStyle.d.ts.map +1 -1
  219. package/lib/ui/AcApDrawStyle.js +22 -1
  220. package/lib/ui/AcApDrawStyle.js.map +1 -1
  221. package/lib/ui/AcApDrawStyleToolbar.d.ts +12 -7
  222. package/lib/ui/AcApDrawStyleToolbar.d.ts.map +1 -1
  223. package/lib/ui/AcApDrawStyleToolbar.js +173 -52
  224. package/lib/ui/AcApDrawStyleToolbar.js.map +1 -1
  225. package/lib/ui/icons.d.ts +148 -0
  226. package/lib/ui/icons.d.ts.map +1 -0
  227. package/lib/ui/icons.js +173 -0
  228. package/lib/ui/icons.js.map +1 -0
  229. package/lib/ui/index.d.ts +1 -0
  230. package/lib/ui/index.d.ts.map +1 -1
  231. package/lib/ui/index.js +1 -0
  232. package/lib/ui/index.js.map +1 -1
  233. package/lib/util/AcApCssColor.d.ts +8 -0
  234. package/lib/util/AcApCssColor.d.ts.map +1 -0
  235. package/lib/util/AcApCssColor.js +20 -0
  236. package/lib/util/AcApCssColor.js.map +1 -0
  237. package/lib/util/AcApMeasurementUtil.d.ts.map +1 -1
  238. package/lib/util/AcApMeasurementUtil.js +3 -2
  239. package/lib/util/AcApMeasurementUtil.js.map +1 -1
  240. package/lib/util/AcApScreenHitTest.d.ts +5 -1
  241. package/lib/util/AcApScreenHitTest.d.ts.map +1 -1
  242. package/lib/util/AcApScreenHitTest.js +9 -3
  243. package/lib/util/AcApScreenHitTest.js.map +1 -1
  244. package/lib/util/index.d.ts +1 -0
  245. package/lib/util/index.d.ts.map +1 -1
  246. package/lib/util/index.js +1 -0
  247. package/lib/util/index.js.map +1 -1
  248. package/lib/view/AcApCompareDisplay.d.ts +37 -0
  249. package/lib/view/AcApCompareDisplay.d.ts.map +1 -0
  250. package/lib/view/AcApCompareDisplay.js +8 -0
  251. package/lib/view/AcApCompareDisplay.js.map +1 -0
  252. package/lib/view/AcEdReviewOverlayPick.d.ts +9 -0
  253. package/lib/view/AcEdReviewOverlayPick.d.ts.map +1 -1
  254. package/lib/view/AcEdReviewOverlayPick.js +30 -1
  255. package/lib/view/AcEdReviewOverlayPick.js.map +1 -1
  256. package/lib/view/AcTrLayer.d.ts +6 -0
  257. package/lib/view/AcTrLayer.d.ts.map +1 -1
  258. package/lib/view/AcTrLayer.js +8 -0
  259. package/lib/view/AcTrLayer.js.map +1 -1
  260. package/lib/view/AcTrLayout.d.ts +12 -0
  261. package/lib/view/AcTrLayout.d.ts.map +1 -1
  262. package/lib/view/AcTrLayout.js +12 -0
  263. package/lib/view/AcTrLayout.js.map +1 -1
  264. package/lib/view/AcTrScene.d.ts +7 -0
  265. package/lib/view/AcTrScene.d.ts.map +1 -1
  266. package/lib/view/AcTrScene.js +13 -0
  267. package/lib/view/AcTrScene.js.map +1 -1
  268. package/lib/view/AcTrView2d.d.ts +50 -2
  269. package/lib/view/AcTrView2d.d.ts.map +1 -1
  270. package/lib/view/AcTrView2d.js +210 -37
  271. package/lib/view/AcTrView2d.js.map +1 -1
  272. package/lib/view/AcTrViewSessionState.d.ts +26 -0
  273. package/lib/view/AcTrViewSessionState.d.ts.map +1 -0
  274. package/lib/view/AcTrViewSessionState.js +2 -0
  275. package/lib/view/AcTrViewSessionState.js.map +1 -0
  276. package/lib/view/index.d.ts +2 -0
  277. package/lib/view/index.d.ts.map +1 -1
  278. package/lib/view/index.js +2 -0
  279. package/lib/view/index.js.map +1 -1
  280. package/package.json +12 -5
  281. package/src/ui/icons.ts +293 -0
@@ -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(m,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):(m=typeof globalThis<"u"?globalThis:m||self,d(m["cad-simple-viewer"]={},m.dataModel,m.threeRenderer,m.THREE,m.Stats,m.CSS2DRenderer_js,m.lodashEs,m.mtextRenderer,m.Line2_js,m.LineGeometry_js,m.LineMaterial_js))})(this,(function(m,d,D,xp,Sp,Ap,sa,O,Cp,Pp,_p){"use strict";var xv=Object.defineProperty;var Sv=(m,d,D)=>d in m?xv(m,d,{enumerable:!0,configurable:!0,writable:!0,value:D}):m[d]=D;var E=(m,d,D)=>Sv(m,typeof d!="symbol"?d+"":d,D);function Lp(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=Lp(xp),ra='<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>',hn="mlightcad",oa="https://mlightcad.github.io/cad-viewer/",aa="https://mlightcad.github.io/cad-viewer/docs/",la="https://github.com/mlightcad/cad-viewer";function Xs(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",hn),e.innerHTML=ra;const t=(s==null?void 0:s.size)??"40px";return e.style.width=t,e.style.height=t,e}function ca(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",hn);const t=Xs({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=hn,e.appendChild(t),e.appendChild(i),e}const Ep={unchanged:10265519,deleted:14753096,added:2278750,modified:16096779};function At(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 qs(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,At(s,e,a.x,a.y,l.x,l.y))}return n}function pn(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 qs(s,e,[{x:n,y:o},{x:r,y:o},{x:r,y:a},{x:n,y:a}],!0)}function da(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 ua(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 Qs(s,e,t,i,n,r,o,a){const l=Math.PI*2,c=24;let u=1/0,p=a?r-o:o-r;p<=0&&(p+=l);for(let y=0;y<=c;y++){const g=y/c,f=a?r-g*p:r+g*p,v=t+n*Math.cos(f),w=i+n*Math.sin(f);u=Math.min(u,Math.hypot(s-v,e-w))}return u}const Tp=8;function ce(s,e,t){return{x:s.x+e,y:s.y+t}}function mn(s,e,t){return{tip:ce(s.tip,e,t),anchor:ce(s.anchor,e,t),text:s.text}}function yn(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 er(s,e,t){switch(s.type){case"cloud":return{...s,corner1:ce(s.corner1,e,t),corner2:ce(s.corner2,e,t),callout:s.callout?mn(s.callout,e,t):void 0};case"rect":return{...s,corner1:ce(s.corner1,e,t),corner2:ce(s.corner2,e,t),callout:s.callout?mn(s.callout,e,t):void 0};case"highlight":return{...s,corner1:ce(s.corner1,e,t),corner2:ce(s.corner2,e,t)};case"circle":return{...s,center:ce(s.center,e,t),callout:s.callout?mn(s.callout,e,t):void 0};case"callout":return{...s,tip:ce(s.tip,e,t),anchor:ce(s.anchor,e,t)};case"arrow":case"line":return{...s,start:ce(s.start,e,t),end:ce(s.end,e,t)};case"text":case"stamp":case"symbol":return{...s,position:ce(s.position,e,t)}}}function ha(s,e,t,i){const n=t(s.tip),r=t(s.anchor);return At(e.x,e.y,n.x,n.y,r.x,r.y)<=i}function pa(s,e){e&&(s.expandByPoint(e.tip),s.expandByPoint(e.anchor))}function ma(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),pa(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}),pa(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 ui(s){return(s.type==="cloud"||s.type==="rect"||s.type==="circle")&&s.callout==null}function ya(s){return s.type==="circle"?{kind:"circle",center:s.center,radius:s.radius}:{kind:s.type,corner1:s.corner1,corner2:s.corner2}}function tr(s,e,t,i){switch(s.type){case"rect":{const n=t(s.corner1),r=t(s.corner2),o=Math.min(n.x,r.x),a=Math.max(n.x,r.x),l=Math.min(n.y,r.y),c=Math.max(n.y,r.y);return e.x>=o&&e.x<=a&&e.y>=l&&e.y<=c?Math.min(Math.abs(e.x-o),Math.abs(e.x-a),Math.abs(e.y-l),Math.abs(e.y-c))<=i:pn(e.x,e.y,n,r)<=i}case"cloud":{const n=t(s.corner1),r=t(s.corner2),o=Math.min(n.x,r.x),a=Math.max(n.x,r.x),l=Math.min(n.y,r.y),c=Math.max(n.y,r.y),u=i+Tp;return e.x>=o&&e.x<=a&&e.y>=l&&e.y<=c?Math.min(Math.abs(e.x-o),Math.abs(e.x-a),Math.abs(e.y-l),Math.abs(e.y-c))<=u:pn(e.x,e.y,n,r)<=u}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}default:return!1}}function ir(s,e,t,i){switch(s.type){case"line":case"arrow":{const n=t(s.start),r=t(s.end);return At(e.x,e.y,n.x,n.y,r.x,r.y)<=i}case"rect":case"cloud":case"circle":return tr(s,e,t,i)?!0:s.callout?ha(s.callout,e,t,i):!1;case"highlight":return da(e.x,e.y,t(s.corner1),t(s.corner2))||pn(e.x,e.y,t(s.corner1),t(s.corner2))<=i;case"callout":return ha(s,e,t,i);case"text":case"stamp":case"symbol":return!1}}const hi=new Map;let pi,gn,nr;function ga(s){gn=s}function fa(s){if(!gn)throw new Error("Markup session bag factory is not installed");if(!s)return nr||(nr=gn()),nr;let e=hi.get(s);return e||(e=gn(),hi.set(s,e)),e}function mi(){return fa(pi)}function yi(s){pi=s,fa(s)}function Ip(){return pi}function sr(s){hi.delete(s),pi===s&&(pi=void 0)}function Mp(s){var e;return((e=hi.get(s))==null?void 0:e.store.list())??[]}function Dp(s){var e;return(e=hi.get(s))==null?void 0:e.store}const fn="markup",de="markup-live";class ba{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?Op(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{}}}function H(){return mi().store}function Op(s,e){return(s.type==="cloud"||s.type==="rect"||s.type==="circle")&&s.callout?{...s,callout:{...s.callout,text:e}}:s}const wa=["open","question","answered","closed"];function va(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 rr(s,e,t,i){switch(s.type){case"distance":{const n=t(s.start),r=t(s.end);return At(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(At(e.x,e.y,n.x,n.y,r.x,r.y)<=i||At(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),u=Math.atan2(r.y-n.y,r.x-n.x),p=Math.atan2(o.y-n.y,o.x-n.x),y=d.AcGeMathUtil.normalizeAngle(p-u)>Math.PI;return Qs(e.x,e.y,n.x,n.y,c,u,p,y)<=i}case"area":{const n=s.points.map(t);return n.length<2?!1:ua(e.x,e.y,n)?!0:qs(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);let u=d.AcGeMathUtil.normalizeAngle(c-l)>Math.PI;if(s.through){const p=t(s.through),y=Math.atan2(p.y-n.y,p.x-n.x);u=!d.AcGeMathUtil.isAngleOnCcwSweep(l,y,c)}return Qs(e.x,e.y,n.x,n.y,a,l,c,u)<=i}case"point":return!1}}const ka={showUnits:!0,showApproximate:!0},xa={showUnits:!0,showApproximate:!0,applyAngbaseAngdir:!1};let We={};function Av(s){return s}function or(s){return{lunits:We.lunits??s.lunits,luprec:We.luprec??s.luprec,aunits:We.aunits??s.aunits,auprec:We.auprec??s.auprec}}function Np(){return{...We}}function Bp(s){s.lunits!=null&&(We.lunits=s.lunits),s.luprec!=null&&(We.luprec=s.luprec),s.aunits!=null&&(We.aunits=s.aunits),s.auprec!=null&&(We.auprec=s.auprec)}function Sa(){We={}}function Fp(s){const e=or(s);return e.lunits!==s.lunits||e.luprec!==s.luprec||e.aunits!==s.aunits||e.auprec!==s.auprec}function Aa(s,e){if(!Fp(s))return e();const t=or(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 Ee(s,e,t=ka){return Aa(s,()=>s.formatter.formatLength(e,t))}function bn(s,e,t=xa){return Aa(s,()=>s.formatter.formatAngle(e,t))}function ar(s,e){switch(e.kind){case"length":return Ee(s,e.value);case"area":return`${Ee(s,e.value)}²`;case"angle":return bn(s,e.radians);case"coordinate":{const t=Ee(s,e.x),i=Ee(s,e.y);return`X ${t} Y ${i}`}}}function gi(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 Ft=d.AcGiLineWeight.LineWeight070,jt=13;let wn,lr=Ft,cr=jt;function Be(s){return wn?wn.clone():d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.MEASUREMENTCOLOR,s)}function st(){return lr}function Fe(){return cr}function Ca(s){wn=s.clone()}function Pa(s){s>0&&(lr=s)}function _a(s){!Number.isFinite(s)||s<=0||(cr=s)}function jp(){wn=void 0,lr=Ft,cr=jt}function pt(s){return{color:Be(s),lineWeight:st(),fontSize:Fe()}}function fi(s){return{color:s.color.clone(),lineWeight:s.lineWeight,fontSize:s.fontSize}}function Te(s){const e=Number(s);return!Number.isFinite(e)||e<=0?2:Math.max(1,e/28)}function dr(s,e){return`rgba(${s.red}, ${s.green}, ${s.blue}, ${e})`}function Se(s){return s.cssColor??`rgb(${s.red}, ${s.green}, ${s.blue})`}function ur(s){const e=d.AcCmColor.fromString(s);if(e)return gi(e);try{return gi(new d.AcCmColor().setRGBFromCss(s))}catch{const t=new d.AcCmColor;return t.setRGB(123,135,148),t}}function zp(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 ie=zp();function mt(){ie.emit("undo-stack-changed",{})}function yt(s,e,t){var n;const i=((n=s.isUndoRecording)==null?void 0:n.call(s))??!1;s.runDatabaseEdit(e,t),i||(ie.emit("session-db-edit-committed",{}),mt())}let q;function La(s){q=s}class Ea{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=H(),r=Ia(n.list()),o=n.dirty;this.depth++;try{i()}finally{this.depth--}const a=Ia(n.list()),l=n.dirty;Rp(r,a)&&o===l||(this.undoStack.push({label:t,before:r,after:a,beforeDirty:o,afterDirty:l}),this.redoStack.length=0,Ct().recordMarkup(),mt())}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{H().restore(e,{dirty:t})}finally{this.depth--}}}class Ta{constructor(){this.undoKinds=[],this.redoKinds=[]}recordDb(){this.undoKinds.push("db"),this.redoKinds.length=0,we().clearRedo(),q==null||q.clearRedo()}recordMarkup(){this.undoKinds.push("markup"),this.redoKinds.length=0,q==null||q.clearRedo()}recordOverlay(){this.undoKinds.push("overlay"),this.redoKinds.length=0,we().clearRedo()}canUndo(e){var t;return this.undoKinds.length>0||we().canUndo()||((q==null?void 0:q.canUndo())??!1)||(((t=e.transactionManager)==null?void 0:t.canUndo())??!1)}canRedo(e){var t;return this.redoKinds.length>0||we().canRedo()||((q==null?void 0:q.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(we().undo())return this.redoKinds.push("markup"),"markup";continue}if(i==="overlay"){if(q!=null&&q.undo())return this.redoKinds.push("overlay"),"overlay";continue}if(i==="db"){if(e.transactionManager.undo())return this.redoKinds.push("db"),"db";continue}return we().undo()?(this.redoKinds.push("markup"),"markup"):q!=null&&q.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(we().redo())return this.undoKinds.push("markup"),"markup";continue}if(i==="overlay"){if(q!=null&&q.redo())return this.undoKinds.push("overlay"),"overlay";continue}if(i==="db"){if(e.transactionManager.redo())return this.undoKinds.push("db"),"db";continue}return we().redo()?(this.undoKinds.push("markup"),"markup"):q!=null&&q.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,q==null||q.clear()}}function we(){return mi().history}function Ct(){return mi().sessionUndo}function ve(s,e,t){we().run(s,e,t)}ie.on("session-db-edit-committed",()=>{Ct().recordDb()});function Ia(s){return structuredClone(s)}function Rp(s,e){return s.length!==e.length?!1:JSON.stringify(s)===JSON.stringify(e)}class Ma{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)Oa(e);this.redoStack.length=0}clear(){for(const e of[...this.undoStack,...this.redoStack])Oa(e);this.undoStack.length=0,this.redoStack.length=0}run(e,t,i){if(this.depth>0){i();return}const n=e,r=hr(n),o=Da(r);this.depth++;try{i()}finally{this.depth--}const a=hr(n),l=a.filter(p=>r.indexOf(p)<0),c=r.filter(p=>a.indexOf(p)<0),u=Da(a);l.length===0&&c.length===0&&!Vp(o,u)||(this.undoStack.push({label:t,view:n,added:l,removed:c,stylesBefore:o,stylesAfter:u}),this.clearRedo(),Ct().recordOverlay(),mt())}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 hr(e.view)){const l=o[a.id];l&&fr(e.view,a,l)}e.view.isHtmlDirty=!0}finally{this.depth--}}}function hr(s){return s.htmlTransientManager.groupsOnLayer(Y)}function Da(s){const e={};for(const t of s){const i=Pt(t.id);i&&(e[t.id]=fi(i))}return e}function Vp(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 Oa(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 pr;function rt(){return pr||(pr=new Ma),pr}function zt(s,e,t){rt().run(s,e,t)}function mr(){rt().clear(),$a(),Sa(),Ra()}function Na(){La({canUndo:()=>rt().canUndo(),canRedo:()=>rt().canRedo(),undo:()=>rt().undo(),redo:()=>rt().redo(),clearRedo:()=>rt().clearRedo(),clear:()=>rt().clear()})}Na();const Gp=["distance","angle","area","arc","point"];function bi(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function je(s){return bi(s)&&typeof s.x=="number"&&typeof s.y=="number"&&Number.isFinite(s.x)&&Number.isFinite(s.y)}function Kp(s){return typeof s=="string"&&Gp.includes(s)}function Up(s){if(!bi(s)||typeof s.color!="string")return;const e=typeof s.lineWeight=="number"&&s.lineWeight>0?s.lineWeight:Ft,t=typeof s.fontSize=="number"&&s.fontSize>0?s.fontSize:jt;return{color:s.color,lineWeight:e,fontSize:t}}function Hp(s,e){if(!(!bi(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 Wp(s){if(!bi(s)||typeof s.id!="string"||!Kp(s.type))return;const e=Up(s.style),t=Hp(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 gt(s){return{color:Se(s.color),lineWeight:s.lineWeight,fontSize:s.fontSize}}function Ba(s){return{color:ur(s.color),lineWeight:s.lineWeight>0?s.lineWeight:Ft,fontSize:s.fontSize>0?s.fontSize:jt}}function Fa(s){let e;try{e=JSON.parse(s)}catch{throw new Error("Invalid measurement sidecar: not JSON")}if(!bi(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=Wp(i);n&&t.push(n)}return{version:1,drawingName:typeof e.drawingName=="string"?e.drawingName:void 0,measurements:t}}function ja(s){return`${JSON.stringify(s,null,2)}
2
+ `}function za(s){return s?`${s.replace(/\.(dwg|dxf)$/i,"")}.measurement.json`:"drawing.measurement.json"}const Y="measurement",le="measurement-live";let wi=!0;function yr(){return wi}function Ra(){wi=!0}function Va(s,e){wi=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,le),s.isHtmlDirty=!0}const ft=new Map,Rt=new Map,gr=new Set;let ot;function Pt(s){const e=Rt.get(s);return e?fi(e):void 0}function Ga(){return ot}function Ka(){return ot?Pt(ot):void 0}function Ua(s){return gr.add(s),()=>{gr.delete(s)}}function vn(){for(const s of gr)s()}function Ha(s,e){Rt.set(s,fi(e))}function fr(s,e,t){var a;const i=Rt.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)??Ft,fontSize:t.fontSize??(i==null?void 0:i.fontSize)??jt};Ha(e.id,r);const o=ft.get(e.id);o&&(o.style=fi(r),o.snapshot&&(o.snapshot={...o.snapshot,style:gt(r)})),$p(s,e,r)}function kn(s,e){const t=s.htmlTransientManager.getSelectedGroups().filter(i=>i.layer===Y);t.length!==0&&zt(s,"Measurement Style",()=>{for(const i of t)fr(s,i,e)})}function $p(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=ft.get(e.id);(o=i==null?void 0:i.redraw)==null||o.call(i,t),s.isHtmlDirty=!0}function Yp(s,e){var t;for(const i of s.htmlTransientManager.groupsOnLayer(Y)){const n=ft.get(i.id);if(!(n!=null&&n.value))continue;const r=ar(e,n.value);for(const o of i.children){const a=o;(t=a.setText)==null||t.call(a,r)}}s.isHtmlDirty=!0}function Wa(s){const e=[];for(const t of s.htmlTransientManager.groupsOnLayer(Y)){const i=ft.get(t.id);if(!(i!=null&&i.snapshot))continue;const n=i.style??Rt.get(t.id);e.push({...i.snapshot,id:t.id,layoutId:t.layoutId,style:n?gt(n):i.snapshot.style})}return e}function $a(){ft.clear(),Rt.clear(),ot=void 0,vn()}function Ya(s,e,t){const i=(t==null?void 0:t.entityIds)??[];ft.set(e.id,t??{}),t!=null&&t.style&&Ha(e.id,t.style);const n=e.onSelectedChanged;e.onSelectedChanged=(a,l)=>{n==null||n(a,l),a?(ot=l.id,vn(),i.length>0&&s.highlight(i)):(ot===l.id&&(ot=void 0,vn()),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(),ft.delete(e.id),Rt.delete(e.id),ot===e.id&&(ot=void 0,vn()),i.length>0&&s.unhighlight(i);try{(a=t==null?void 0:t.dispose)==null||a.call(t)}catch{}},zt(s,"Create Measurement",()=>{s.htmlTransientManager.add(e)}),!wi&&(e.layoutId==null||e.layoutId===s.activeLayoutBtrId)&&e.setVisible(!1),s.isHtmlDirty=!0}function br(s){var e,t;return(t=(e=ft.get(s))==null?void 0:e.snapshot)==null?void 0:t.geometry}function Za(s,e,t,i){if(!wi)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=br(l.id);if(c&&rr(c,n,r,i))return l.id}}function Vt(s,e){return s.minX>=e.minX&&s.maxX<=e.maxX&&s.minY>=e.minY&&s.maxY<=e.maxY}function Zp(s){var e;return 80+(((e=s.id)==null?void 0:e.length)??0)*2}function Xa(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+=Zp(s[r]);return Math.round(n/i*t)}const qa=10;function Ja(s){return{minX:s.min.x,minY:s.min.y,maxX:s.max.x,maxY:s.max.y}}function Xp(s,e){return!(s.maxX<e.minX||s.minX>e.maxX||s.maxY<e.minY||s.minY>e.maxY)}function Qa(s,e,t){const i=Ja(s);return t==="window"?Vt(i,e):Xp(i,e)}function qp(s,e,t,i){const n={x:e,y:t},r=l=>s.worldToScreen(l),o=s.activeLayoutBtrId,a=H().list();for(let l=a.length-1;l>=0;l--){const c=a[l];if(c.layoutId!=null&&c.layoutId!==o)continue;const u=s.htmlTransientManager.getGroup(c.id);if(u!=null&&u.visible&&ir(c.geometry,n,r,i))return c.id}}function el(s,e){const t=s.worldToScreen(e),i=Math.max(s.selectionBoxSize*2,4),n=a=>s.worldToScreen(a),r=s.activeLayoutBtrId,o=H().list();for(let a=o.length-1;a>=0;a--){const l=o[a];if(l.layoutId!=null&&l.layoutId!==r)continue;const c=s.htmlTransientManager.getGroup(l.id);if(c!=null&&c.visible&&ui(l.geometry)&&tr(l.geometry,t,n,i))return l}}function tl(s,e,t){const i=Ja(e),n=s.activeLayoutBtrId,r=[];for(const o of H().list()){if(o.layoutId!=null&&o.layoutId!==n)continue;const a=s.htmlTransientManager.getGroup(o.id);if(!(a!=null&&a.visible))continue;const l=ma(o.geometry);l&&Qa(l,i,t)&&r.push(o.id)}if(!yr())return r;for(const o of s.htmlTransientManager.groupsOnLayer(Y)){if(!o.visible||o.layoutId!=null&&o.layoutId!==n)continue;const a=br(o.id);if(!a)continue;const l=va(a);l&&Qa(l,i,t)&&r.push(o.id)}return r}function Jp(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 Qp(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 il(s,e,t,i){const n=Math.max(s.selectionBoxSize*2,qa),r=qp(s,e,t,n),o=Za(s,e,t,n),a=r??o;if(!a)return!1;const l=Jp(s,a,i);return l&&(s.isHtmlDirty=!0),l}function nl(s,e,t,i){const n=tl(s,e,t),r=Qp(s,n,i);return r&&(s.isHtmlDirty=!0),r}const xn="simkai";function em(){return{fontFamily:xn,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:O.MTextParagraphAlignment.DEFAULT}}function sl(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 Ae(s,e,t){return Math.min(t,Math.max(e,s))}function tm(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 im{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=Ae(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=Ae(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=Ae(e,0,this.charBoxes.length),n=Ae(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=Ae(e,0,this.charBoxes.length),n=Ae(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=Ae(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=Ae(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=Ae(this.cursorIndex,0,this.charBoxes.length),this.cursorLineHint=null,this.selection){const o=Ae(this.selection.anchor,0,this.charBoxes.length),a=Ae(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:Ae(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=Ae(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),u=l.x+t<a.x,p=tm(a,l),y=Math.min(a.height,l.height),f=(y>0?p/y:0)<n;(u||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 nm={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"},sm={fillColor:"rgba(0,120,255,0.30)",blendMode:"normal",animate:!1,strategy:"perChar"},rm={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)"},om={showCharBoxes:!0,showLineIndices:!0,showCharIndices:!0,showChars:!0};class am{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={...nm,...e.cursorStyle},this.selectionStyle={...sm,...e.selectionStyle},this.debugStyle={...rm,...e.debugStyle},this.debugVisibility={...om,...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 u=(c=e.chars)==null?void 0:c[r];if(!u)return;this.renderer.drawText({text:u,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 Sn(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 lm{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=Sn(e.color),r=(e.opacity??1)*n.alpha;if(e.dashed&&e.dashed.length>0){const u=[new T.Vector3(t.x,t.y,0),new T.Vector3(i.x,i.y,0)],p=new T.BufferGeometry().setFromPoints(u),y=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,y);g.computeLineDistances(),g.renderOrder=e.renderOrder??1,this.frameGroup.add(g);return}const o=new Pp.LineGeometry;o.setPositions([t.x,t.y,0,i.x,i.y,0]);const a=new _p.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 Cp.Line2(o,a);c.computeLineDistances(),c.renderOrder=e.renderOrder??1,this.frameGroup.add(c)}drawText(e){var U;const t=e.font??"20px monospace",i=Number(((U=t.match(/(\d+(?:\.\d+)?)px/))==null?void 0:U[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 u=e.align??"left",p=e.baseline??"top";o.textAlign=u,o.textBaseline=p;const y=Sn(e.color);o.fillStyle=`rgba(${Math.round(y.color.r*255)}, ${Math.round(y.color.g*255)}, ${Math.round(y.color.b*255)}, ${e.opacity??y.alpha})`;const g=u==="center"?r.width/2:u==="right"?r.width-n:n,f=p==="middle"?r.height/2:p==="bottom"?r.height-n:n;o.fillText(e.text,g,f);const v=this.isYAxisUp(),w=new T.CanvasTexture(r);w.flipY=v,w.needsUpdate=!0;const x=Math.abs(this.currentTransform.scaleX??1),S=Math.abs(this.currentTransform.scaleY??1),A=Math.max(1,r.width*x),C=Math.max(1,r.height*S),L=new T.PlaneGeometry(A,C),_=new T.MeshBasicMaterial({map:w,transparent:!0,depthTest:!1,depthWrite:!1,side:T.DoubleSide}),N=new T.Mesh(L,_),F=this.transformPoint(e.x,e.y),M=u==="center"?0:u==="right"?-A/2:A/2,V=p==="middle"?0:p==="bottom"?v?C/2:-C/2:v?-C/2:C/2;N.position.set(F.x+M,F.y+V,.2),N.renderOrder=10,this.frameGroup.add(N)}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),u=new T.PlaneGeometry(l,i),p=new T.MeshBasicMaterial({color:n,transparent:r<1,opacity:r,side:T.DoubleSide,depthTest:!1}),y=new T.Mesh(u,p);return y.position.set((e.x+t.x)/2,(e.y+t.y)/2,0),y.rotation.z=c,y}createQuadMesh(e,t,i,n,r,o=1){if(!r)return null;const a=new T.PlaneGeometry(i,n),l=Sn(r),c=new T.MeshBasicMaterial({color:l.color,transparent:o*l.alpha<1,opacity:o*l.alpha,side:T.DoubleSide,depthTest:!1}),u=new T.Mesh(a,c);return u.position.set(e+i/2,t,0),u.renderOrder=1,u}createRectBorder(e,t,i,n,r,o,a){const l=Sn(r),c=i/2,u=n/2,p=e+c,y=t,g=[new T.Vector3(p-c,y-u,0),new T.Vector3(p+c,y-u,0),new T.Vector3(p+c,y+u,0),new T.Vector3(p-c,y+u,0)],f=new T.BufferGeometry().setFromPoints(g),v=new T.LineBasicMaterial({color:l.color,transparent:a*l.alpha<1,opacity:a*l.alpha,linewidth:o,depthTest:!1});return new T.LineLoop(f,v)}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 cm(s){return s===O.MTextLineAlignment.TOP?"superscript":s===O.MTextLineAlignment.BOTTOM?"subscript":"normal"}function dm(s){return s==="superscript"?O.MTextLineAlignment.TOP:s==="subscript"?O.MTextLineAlignment.BOTTOM:O.MTextLineAlignment.MIDDLE}function rl(s){return{...s,align:dm(s.script)}}function vi(s){return{underline:s.underline,overline:s.overline,strikeThrough:s.strikeThrough,script:cm(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 ye(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 ki(s){return s.type==="char"||s.type==="stack"||s.type==="paragraphBreak"||s.type==="columnBreak"||s.type==="wrapAtDimLine"}function um(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 ol(s,e){const t=s??vi(new O.MTextContext),i=rl(t),n=rl(e);if(um(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${O.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${wr(n.capHeight)};`),(i.widthFactor.value!==n.widthFactor.value||i.widthFactor.isRelative!==n.widthFactor.isRelative)&&(r+=`\\W${wr(n.widthFactor)};`),(i.charTrackingFactor.value!==n.charTrackingFactor.value||i.charTrackingFactor.isRelative!==n.charTrackingFactor.isRelative)&&(r+=`\\T${wr(n.charTrackingFactor)};`),i.oblique!==n.oblique&&(r+=`\\Q${xi(n.oblique)};`),JSON.stringify(i.paragraph)!==JSON.stringify(n.paragraph)&&(r+=`\\p${hm(n.paragraph)};`),r}function wr(s){return`${xi(s.value)}${s.isRelative?"x":""}`}function xi(s){return Number.isInteger(s),s.toString()}function hm(s){const e=[`i${xi(s.indent)}`,`l${xi(s.left)}`,`r${xi(s.right)}`];return s.align!==O.MTextParagraphAlignment.DEFAULT&&e.push(`q${pm(s.align)}`),s.tabs.length>0&&e.push(`t${s.tabs.map(t=>String(t)).join(",")}`),e.join(",")}function pm(s){switch(s){case O.MTextParagraphAlignment.LEFT:return"l";case O.MTextParagraphAlignment.RIGHT:return"r";case O.MTextParagraphAlignment.CENTER:return"c";case O.MTextParagraphAlignment.JUSTIFIED:return"j";case O.MTextParagraphAlignment.DISTRIBUTED:return"d";default:return"x"}}function al(s,e,t={}){const i=new O.MTextParser(s,e,{...t,yieldPropertyCommands:!1}),n=[];for(const r of i.parse()){const o=vi(r.ctx);switch(r.type){case O.TokenType.WORD:{const a=r.data;for(const l of a)n.push({type:"char",value:l,style:ye(o)});break}case O.TokenType.SPACE:n.push({type:"char",value:" ",style:ye(o)});break;case O.TokenType.NBSP:n.push({type:"char",value:" ",style:ye(o)});break;case O.TokenType.TABULATOR:n.push({type:"char",value:" ",style:ye(o)});break;case O.TokenType.STACK:{const[a,l,c]=r.data,u=ye(o);c==="^"&&(a.length===0&&l.length>0?u.script="subscript":a.length>0&&l.length===0?u.script="superscript":u.script="normal"),n.push({type:"stack",numerator:a,denominator:l,divider:c,style:u});break}case O.TokenType.NEW_PARAGRAPH:n.push({type:"paragraphBreak",style:ye(o)});break;case O.TokenType.NEW_COLUMN:n.push({type:"columnBreak",style:ye(o)});break;case O.TokenType.WRAP_AT_DIMLINE:n.push({type:"wrapAtDimLine",style:ye(o)});break}}return{nodes:n}}function mm(s){const e=vi(new O.MTextContext);let t="",i=0;for(;i<s.nodes.length;){const n=s.nodes[i];if(!n)break;if(!ki(n)){t+=ul(n),i+=1;continue}const r=n.style;let o="",a=i;for(;a<s.nodes.length;){const l=s.nodes[a];if(!l||!ki(l)||!dl(r,l.style))break;o+=ul(l),a+=1}dl(r,e)?t+=o:t+=`{${ol(null,r)}${o}}`,i=a}return t}function An(s,e,t){if(t<=0)return s;const i=Cn(e,0,s.nodes.length),n=Cn(t,0,s.nodes.length-i);return s.nodes.splice(i,n),s}function ym(s,e,t,i,n){const r=Cn(e,0,s.nodes.length),o=Cn(t,0,s.nodes.length-r),a=n??ll(s,r)??vi(new O.MTextContext),l=bm(i,a);return s.nodes.splice(r,o,...l),s}function ll(s,e){for(let t=e-1;t>=0;t--){const i=s.nodes[t];if(i&&ki(i))return ye(i.style)}for(let t=e;t<s.nodes.length;t++){const i=s.nodes[t];if(i&&ki(i))return ye(i.style)}}function gm(s){return s===" "?"\\~":s===" "?"^I":s==="\\"?"\\\\":s==="{"?"\\{":s==="}"?"\\}":s==="^"?"\\U+005E":s==="%"?"\\U+0025":s===`
3
+ `?"\\P":s==="\r"?"":s}function cl(s){return s.replace(/[\\;/#^]/g,"\\$&")}function dl(s,e){return ol(s,e)===""}function ul(s){switch(s.type){case"char":return gm(s.value);case"stack":return fm(s.numerator,s.denominator,s.divider);case"paragraphBreak":return"\\P";case"columnBreak":return"\\N";case"wrapAtDimLine":return"\\X"}}function fm(s,e,t){const i=cl(s),n=cl(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 bm(s,e){const t=[];for(const i of s){if(i===`
4
+ `){t.push({type:"paragraphBreak",style:ye(e)});continue}t.push({type:"char",value:i,style:ye(e)})}return t}function Cn(s,e,t){return Math.max(e,Math.min(t,s))}class ge{constructor(e={nodes:[]}){E(this,"_ast");E(this,"_cursor");E(this,"_selection",null);this._ast=typeof e=="string"?al(e):ge.cloneAst(e),this._cursor=this._ast.nodes.length}static fromMText(e,t){return new ge(al(e,t))}get ast(){return this._ast}get length(){return this._ast.nodes.length}get cursor(){return this._cursor}set cursor(e){this._cursor=ge.clamp(e,0,this.length),this._selection=null}get selection(){return this._selection?{...this._selection}:null}setSelection(e,t){const i=ge.normalizeSelection(e,t,this.length);return this._selection=i.start===i.end?null:i,this._cursor=ge.clamp(t,0,this.length),this}clearSelection(){return this._selection=null,this}moveCursor(e,t=!1){const i=ge.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 ym(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 An(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 An(this._ast,this._cursor-t,t),this._cursor-=t,this}deleteForward(e=1){if(this.hasSelection()){const{start:t,end:i}=this.getActiveRange();return An(this._ast,t,i-t),this._cursor=t,this._selection=null,this}return e<=0||this._cursor>=this.length?this:(An(this._ast,this._cursor,e),this)}replaceSelection(e,t){return this.insertText(e,t)}toMText(){return mm(this._ast)}transaction(e){const t={ast:ge.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 ll(this._ast,e)??vi(new O.MTextContext)}static cloneAst(e){return{nodes:e.nodes.map(t=>t.type==="char"?{...t,style:ye(t.style)}:t.type==="stack"?{...t,style:ye(t.style)}:{...t,style:ye(t.style)})}}static normalizeSelection(e,t,i){const n=ge.clamp(e,0,i),r=ge.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 vr{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 wm={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>'},hl="mlightcad-mtext-toolbar-style",pl=["Arial","Helvetica","Verdana","Tahoma","Trebuchet MS","Times New Roman","Georgia","Courier New","system-ui","sans-serif","serif","monospace"];function vm(){if(document.getElementById(hl))return;const s=document.createElement("style");s.id=hl,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 kr(s){return Math.max(0,Math.min(16777215,Math.round(s)))}function ml(s){return`#${(s===null?16777215:kr(s)).toString(16).padStart(6,"0")}`}function km(s){return/^#[0-9a-fA-F]{6}$/.test(s)?Number.parseInt(s.slice(1),16):16777215}function xm(s){return s.isRgb&&s.rgbValue!==null?ml(s.rgbValue):s.isAci&&s.aci!==null?ml(O.getColorByIndex(s.aci)):"#ffffff"}function yl(s){const e=new O.MTextColor;return e.rgbValue=km(s),e}function gl(s){const e=new O.MTextColor;return s.aci!==null&&Number.isFinite(s.aci)?(e.aci=s.aci,e):s.rgb!==null?(e.rgbValue=kr(s.rgb),e):(e.rgbValue=16777215,e)}function Sm(s){const e=s.trim().toLowerCase();return/^#[0-9a-f]{6}$/.test(e)?e:/^[0-9a-f]{6}$/.test(e)?`#${e}`:null}function bt(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=wm[e],t}function Am(s){const e=s&&s.length>0?s:pl,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:[...pl]}class Cm{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");vm(),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 v of Am(e.fontFamilies)){const w=document.createElement("option");w.value=v,w.textContent=v,i.appendChild(w)}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=bt("Bold","bold"),l=bt("Italic","italic"),c=bt("Underline","underline"),u=bt("Overline","overline"),p=bt("Strike Through","strike"),y=bt("Superscript","superscript"),g=bt("Subscript","subscript"),f=bt("Stack","stack");o.append(a,l,c,u,p,y,g,f),this.root.append(t,r,o),this.controls={fontFamily:i,fontSize:n,boldBtn:a,italicBtn:l,underlineBtn:c,overlineBtn:u,strikeBtn:p,superscriptBtn:y,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))),u=Math.max(o,Math.min(l,Math.round(t-n)));this.root.style.left=`${c}px`,this.root.style.top=`${u}px`}setFormat(e){this.ensureSelectValue(e.fontFamily),this.controls.fontSize.value=String(Math.max(1,Math.round(e.fontSize)));const t=gl(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(yl(a.value))}),{host:a,setValue:l=>{const c=Sm(xm(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?gl(t):yl("#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:kr(e.rgbValue)});return}this.onFormatChange({aci:null,rgb:16777215})}}function fl(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 Pn="__mlightcadMTextInputBoxSceneRoot",K=class K{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",O.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,u,p,y,g;K.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=((u=e.toolbar)==null?void 0:u.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=((y=e.position)==null?void 0:y.clone())??new T.Vector3(0,0,0),e.initialAttachmentPoint!==void 0&&(this.editorAttachmentPoint=e.initialAttachmentPoint),this.enableWordWrap=e.enableWordWrap??!0;const t=e.textStyle??K.DEFAULT_TEXT_STYLE,i=Math.max(1,Number.isFinite(t.fixedTextHeight)?t.fixedTextHeight:K.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||K.DEFAULT_TEXT_STYLE.font,bigFont:t.bigFont??""},this.baseFormat=this.createBaseFormatFromTextStyle(this.defaultTextStyle,this.resolveRenderColorSettings()),this.currentFormat={...this.baseFormat},this.document=new ge,this.uiAdapter=new vr(this.document),this.mtextRenderer=new O.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 im({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 am({renderer:new lm({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 vr(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,K.activeEditor?K.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=y=>{var f;const g=Math.max(0,Math.min(y,o.length-1));return((f=o[g])==null?void 0:f.type)==="paragraphBreak"?Math.min(g+1,o.length):Math.min(y,o.length-1)},l=y=>{var f;const g=a(y);for(let v=g;v>=0;v--)if(((f=o[v])==null?void 0:f.type)==="paragraphBreak")return v+1;return 0},c=y=>{var f;const g=Math.min(Math.max(0,y),o.length-1);for(let v=g;v<o.length;v++)if(((f=o[v])==null?void 0:f.type)==="paragraphBreak")return v;return o.length},u=l(Math.min(n,r)),p=c(Math.max(n,r));if(!(u>=p)){for(let y=u;y<p;y++){const g=o[y];g&&ki(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;K.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(),K.instances.delete(this),K.instances.size===0&&((e=K.sharedToolbar)==null||e.dispose(),K.sharedToolbar=null,K.sharedToolbarContainer=null,K.sharedToolbarFontFamiliesKey="",K.sharedToolbarColorPickerFactory=null,K.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 K.activeEditor===this}activateEditor(){var i;if(this.closed)return;const e=K.activeEditor;e&&e!==this&&e.deactivateEditor(),K.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=K.sharedToolbar)==null||i.setVisible(!1)}deactivateEditor(){var e;this.isDragging=!1,this.detachIme(),this.cursorRenderer.hide(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!1),K.activeEditor===this&&(K.activeEditor=null,(e=K.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=K.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(!K.sharedToolbar||K.sharedToolbarContainer!==t||K.sharedToolbarFontFamiliesKey!==i||K.sharedToolbarColorPickerFactory!==(this.toolbarColorPicker??null)){(a=K.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),K.sharedToolbar=new Cm(l),K.sharedToolbarContainer=t,K.sharedToolbarFontFamiliesKey=i,K.sharedToolbarColorPickerFactory=this.toolbarColorPicker??null}const r=K.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,u=Number.NEGATIVE_INFINITY;for(const p of o){const y=p.clone().project(this.camera),g=e.left+(y.x+1)*.5*e.width,f=e.top+(1-y.y)*.5*e.height;a=Math.min(a,g),l=Math.max(l,g),c=Math.min(c,f),u=Math.max(u,f)}return!Number.isFinite(a)||!Number.isFinite(c)?null:{minX:a,maxX:l,minY:c,maxY:u}}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,u=o.add(l.multiplyScalar(c));return{x:u.x-this.position.x,y:u.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([xn]),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=O.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(xn),[...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,u,p)=>l<p+1e-4&&c>u-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 u of t)l=Math.min(l,u.y-u.height/2),c=Math.max(c,u.y+u.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 u of e){const p=u.y-u.height/2,y=u.y+u.height/2;l=Math.min(l,p),c=Math.max(c,y)}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,u=l.y+l.height/2,p=t.filter(y=>{const g=y.y-y.height/2,f=y.y+y.height/2;return r(g,f,c,u)});if(p.length===0)o=Math.min(o,c),a=Math.max(a,u);else for(const y of p)o=Math.min(o,y.y-y.height/2),a=Math.max(a,y.y+y.height/2)}for(const l of t){const c=l.y-l.height/2,u=l.y+l.height/2;e.some(y=>{const g=y.y-y.height/2,f=y.y+y.height/2;return r(c,u,g,f)})||(o=Math.min(o,c),a=Math.max(a,u))}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 y=p.box?this.toLocalBox(p.box):void 0;!y||!(Number.isFinite(y.x)&&Number.isFinite(y.y)&&Number.isFinite(y.width)&&Number.isFinite(y.height))||i.push(y)}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:fl(this.width,this.editorAttachmentPoint),y:a,width:Math.max(1,this.width),height:Math.max(0,l-a)},u=this.getFallbackLineAdvance();if(c.height<u){const p=u-c.height;c.y-=p,c.height=u}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:fl(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[Pn]=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[Pn]===this&&(this.scene.remove(n),this.disposeMTextRootResources(n),delete n.userData[Pn])}}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[Pn],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=O.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=em();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:O.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??K.DEFAULT_LINE_SPACE_FACTOR}setLineSpacingFactor(e){if(!Number.isFinite(e)||e<=0)return;const t=K.DEFAULT_LINE_SPACE_FACTOR,i=e>=1?Math.max(.01,t+(e-1)/O.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*K.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 O.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 u=Math.max(1,l.height);return{position:{x:e.x,y:l.y},height:u}}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 u=Math.max(0,Math.min(r.startIndex,i.length-1)),p=i[u];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 u,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 y=0;y<=n.length&&(l===o&&a.push({index:y,lineIndex:c}),y!==n.length);y+=1){const g=n[y];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 y=this,f=(typeof y.resolveCandidateByVisualLineHint=="function"?y.resolveCandidateByVisualLineHint:K.prototype.resolveCandidateByVisualLineHint).call(this,a,o,i);if(f!==void 0)return f;const v=((u=a[0])==null?void 0:u.lineIndex)??0,w=((p=a[a.length-1])==null?void 0:p.lineIndex)??0;if(i<v||i>w)return t?a[a.length-1].index:a[0].index;let x=a[0],S=Math.abs(x.lineIndex-i);for(let A=1;A<a.length;A+=1){const C=a[A],L=Math.abs(C.lineIndex-i);L<S&&(x=C,S=L)}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}sl(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 u=n[0],p=this.stackNodeToPlainText(u.numerator,u.denominator,u.divider),y=Array.from(p).map(g=>({type:"char",value:g,style:this.cloneDocumentStyle(u.style)}));if(y.length===0)return;this.document.transaction(g=>{g.ast.nodes.splice(t,1,...y),g.setSelection(t,t+y.length)}),this.syncUiStateFromDocument(),this.relayout();return}if(!n.every(u=>(u==null?void 0:u.type)==="char"))return;const r=n.map(u=>u.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(u=>{u.ast.nodes.splice(t,i-t,l),u.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 y=o[0],g=this.scriptStackToPlainText(y.numerator,y.denominator,y.divider);if(!g)return;const f=this.cloneDocumentStyle(y.style);f.script="normal",f.align=O.MTextLineAlignment.MIDDLE;const v=Array.from(g).map(w=>({type:"char",value:w,style:this.cloneDocumentStyle(f)}));if(v.length===0)return;this.document.transaction(w=>{w.ast.nodes.splice(n,1,...v),w.setSelection(n,n+v.length)}),this.syncUiStateFromDocument(),this.relayout(),i=!0;return}if(!o.every(y=>(y==null?void 0:y.type)==="char"))return;const a=o.map(y=>y.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"?O.MTextLineAlignment.TOP:O.MTextLineAlignment.BOTTOM;const u={type:"stack",numerator:e==="superscript"?a:"",denominator:e==="subscript"?a:"",divider:"^",style:this.cloneDocumentStyle(c)};this.document.transaction(y=>{y.ast.nodes.splice(n,r-n,u),y.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 ge(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 vr(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)||!sl(e.currentFormat,this.currentFormat)?!1:this.document.toMText()===this.buildMTextFromAst(e.ast)}buildMTextFromAst(e){return new ge(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),u=a,p=a+c;c>0&&u<r&&p>n&&o.push(l),a=p}return o}toCharFormat(e){var w,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,u=a==="normal"?i:c?i/.7:i,p=(w=e.widthFactor)==null?void 0:w.value,y=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,v=typeof e.oblique=="number"&&Number.isFinite(e.oblique)?e.oblique:0;return{fontFamily:e.fontFace.family||n,fontSize:Math.max(1,u||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:v,widthFactor:y,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===O.MTextLineAlignment.TOP?"superscript":r&&e.align===O.MTextLineAlignment.BOTTOM?"subscript":"normal"}createDefaultParseContext(){const e=new O.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=O.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=ge.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 ge(i)}computeAttachmentAnchorOnBounds(e,t,i,n,r){const o=(e+t)*.5,a=(i+n)*.5,l=this.position.z;switch(r){case O.MTextAttachmentPoint.TopLeft:return new T.Vector3(e,n,l);case O.MTextAttachmentPoint.TopCenter:return new T.Vector3(o,n,l);case O.MTextAttachmentPoint.TopRight:return new T.Vector3(t,n,l);case O.MTextAttachmentPoint.MiddleLeft:return new T.Vector3(e,a,l);case O.MTextAttachmentPoint.MiddleCenter:return new T.Vector3(o,a,l);case O.MTextAttachmentPoint.MiddleRight:return new T.Vector3(t,a,l);case O.MTextAttachmentPoint.BottomLeft:case O.MTextAttachmentPoint.BaselineLeft:return new T.Vector3(e,i,l);case O.MTextAttachmentPoint.BottomCenter:case O.MTextAttachmentPoint.BaselineCenter:return new T.Vector3(o,i,l);case O.MTextAttachmentPoint.BottomRight:case O.MTextAttachmentPoint.BaselineRight:return new T.Vector3(t,i,l);default:return new T.Vector3(e,n,l)}}mapRibbonParagraphAlignment(e){switch(e){case"default":return O.MTextParagraphAlignment.DEFAULT;case"left":return O.MTextParagraphAlignment.LEFT;case"center":return O.MTextParagraphAlignment.CENTER;case"right":return O.MTextParagraphAlignment.RIGHT;case"justified":return O.MTextParagraphAlignment.JUSTIFIED;case"distributed":return O.MTextParagraphAlignment.DISTRIBUTED;default:return}}mapRibbonAttachmentCode(e){switch(e.trim().toUpperCase()){case"TL":return O.MTextAttachmentPoint.TopLeft;case"TC":return O.MTextAttachmentPoint.TopCenter;case"TR":return O.MTextAttachmentPoint.TopRight;case"ML":return O.MTextAttachmentPoint.MiddleLeft;case"MC":return O.MTextAttachmentPoint.MiddleCenter;case"MR":return O.MTextAttachmentPoint.MiddleRight;case"BL":return O.MTextAttachmentPoint.BottomLeft;case"BC":return O.MTextAttachmentPoint.BottomCenter;case"BR":return O.MTextAttachmentPoint.BottomRight;default:return}}attachmentPointToRibbonCode(e){switch(e){case O.MTextAttachmentPoint.TopLeft:return"TL";case O.MTextAttachmentPoint.TopCenter:return"TC";case O.MTextAttachmentPoint.TopRight:return"TR";case O.MTextAttachmentPoint.MiddleLeft:return"ML";case O.MTextAttachmentPoint.MiddleCenter:return"MC";case O.MTextAttachmentPoint.MiddleRight:return"MR";case O.MTextAttachmentPoint.BottomLeft:case O.MTextAttachmentPoint.BaselineLeft:return"BL";case O.MTextAttachmentPoint.BottomCenter:case O.MTextAttachmentPoint.BaselineCenter:return"BC";case O.MTextAttachmentPoint.BottomRight:case O.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"?O.MTextLineAlignment.TOP:e.script==="subscript"?O.MTextLineAlignment.BOTTOM:O.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(K,"activeEditor",null),E(K,"sharedToolbar",null),E(K,"sharedToolbarContainer",null),E(K,"sharedToolbarFontFamiliesKey",""),E(K,"sharedToolbarColorPickerFactory",null),E(K,"instances",new Set),E(K,"FALLBACK_LINE_ADVANCE_RATIO",1.5),E(K,"DEFAULT_TEXT_STYLE",{name:"MTextInputBoxStyle",standardFlag:0,fixedTextHeight:24,widthFactor:1,obliqueAngle:0,textGenerationFlag:0,lastHeight:24,font:xn,bigFont:""}),E(K,"DEFAULT_LINE_SPACE_FACTOR",.3);let xr=K;function Pm(s){return d.acgiContrastingForegroundColor(s)}function _m(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 bl(s){return s.currentSpaceId===s.tables.blockTable.modelSpace.objectId}function Sr(s){return s?d.AcDbSystemVariables.MODELBKCOLOR:d.AcDbSystemVariables.PAPERBKCOLOR}function wl(s,e){const t=s==null?void 0:s.RGB;return t??(e?d.ACGI_MODEL_SPACE_BACKGROUND:d.ACGI_PAPER_SPACE_BACKGROUND)}function _n(s,e){const t=Sr(e),i=d.AcDbSysVarManager.instance().getVar(t,s);return wl(i,e)}function vl(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 Ln(s){return d.acgiIsLightBackground(s)?"black":"white"}function Lm(s){if(s===void 0)return;const e=s;return e>=1&&e<=12?e:O.MTextAttachmentPoint.TopLeft}function Cv(s){return s}const En="__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[En])return;const i=new Set,n=[],r=()=>{i.forEach(a=>{a()})},o=a=>{const l=t[a];typeof l=="function"&&(t[a]=(...c)=>{const u=l.apply(t,c);return r(),u},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 A,C;const a=t,l=a.getSelectionRange,c=a.toDocumentIndexFromLogicalIndex,u=a.isScriptOnlyStack,p=a.document;if(typeof l!="function"||typeof c!="function")return!1;const y=l.call(t);if(!y||y.isCollapsed)return!1;const g=c.call(t,y.start,!0),f=c.call(t,y.end,!1),v=((C=(A=p==null?void 0:p.ast)==null?void 0:A.nodes)==null?void 0:C.slice(g,f))??[],w=v[0];if(v.length!==1||(w==null?void 0:w.type)!=="stack")return!1;if(typeof u=="function")return!u.call(t,w);if(w.divider!=="^")return!0;const x=(w.numerator??"").trim().length>0,S=(w.denominator??"").trim().length>0;return x===S},t[En]={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[En]}}}static detachFormatBridge(e){var i;(i=e[En])==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:u}=e,p=new T.Vector3(i.x,i.y,i.z??0),g=d.acgiIsLightBackground(t.backgroundColor)?"#000000":"#ffffff",f=k.instance,v=f.curDocument.database,{layerColor:w}=f.resolveColors(),x=()=>{const V=d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.COLORTHEME,v);return V===0||V==="0"||V===!1||V==="dark"?"dark":"light"},S=Array.from(new Set(a.map(V=>V.trim()).filter(V=>V.length>0))),A=()=>{const V=v.tables.textStyleTable.getAt(v.textstyle);return V==null?void 0:V.textStyle},C=Math.max(1,r),L=A(),_=L?{...L,fixedTextHeight:C,lastHeight:C}:void 0,N=c?null:Q.createHiddenToolbarContainer(t.container),F=Lm(u),M=new xr({scene:t.internalScene,camera:t.internalCamera,width:n,position:p.clone(),initialText:o,...F!==void 0?{initialAttachmentPoint:F}:{},textStyle:_,cursorStyle:{color:g,glowColor:g},boundingBoxStyle:{padding:0},imeTarget:t.canvas,colorSettings:{layer:v.clayer,color:new O.MTextColor,byLayerColor:w,byBlockColor:w},toolbar:{enabled:!0,theme:x(),fontFamilies:S,container:N??t.container,offsetY:10,colorPicker:l??Q.defaultColorPicker??void 0}});return Q.attachFormatBridge(M),Q.setActiveInputBox(M),new Promise(V=>{let U=!1;const Z=()=>{U||(M.update(),t.isHtmlDirty=!0)},J=ae=>{ae.name.toLowerCase()===d.AcDbSystemVariables.COLORTHEME.toLowerCase()&&(M.setToolbarTheme(x()),t.isHtmlDirty=!0)},X=()=>{Q.activeInputBox===M&&Q.setActiveInputBox(null),Q.detachFormatBridge(M),M.dispose(),N==null||N.remove(),t.events.renderFrame.removeEventListener(Z),M.off("close",oe),d.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(J),t.isHtmlDirty=!0},te=ae=>{U||(U=!0,X(),V(ae))},oe=()=>{var Bt;const ae=M.getMTextInsertionPoint();te({contents:M.getText(),location:{x:ae.x,y:ae.y,z:ae.z},width:n,height:C,lineSpacingFactor:((Bt=M.getLineSpacingFactor)==null?void 0:Bt.call(M))??Q.defaultLineSpacingFactor,attachmentPoint:M.getMTextAttachmentPoint()})};M.on("close",oe),t.events.renderFrame.addEventListener(Z),d.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(J)})}};Q.defaultLineSpacingFactor=.3,Q.activeInputBox=null,Q.activeInputBoxChangeListeners=new Set,Q.defaultColorPicker=null,Q.defaultToolbarEnabled=!0;let $e=Q;const Hs=class Hs{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)||$e.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&&zt(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(Hs.COMMAND_LINE_INPUT_CLASS)?i.value.trim()===""&&!i.readOnly:!1}return!0}};Hs.COMMAND_LINE_INPUT_CLASS="ml-cli-text";let Tn=Hs;function Em(s){return s.directBatchPrimitive!=null}function kl(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:D.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 xl(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(D.isDirectBatchRejectedMaterial(i))return null;const n=D.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 D.buildLineSegmentsGeometry(s.array,s.itemSize,s.indices,i)}if(s.kind==="point"){const i=e.styleManager.getPointsMaterial(t);return D.isDirectBatchRejectedMaterial(i)?null:D.buildPointGeometry(s.point,i)}if(s.kind==="area"){const i=D.buildAreaGeometry(s.area,t,e.context);return i?D.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 u=l;o.material=u.map(p=>this.shouldRemap(p,t)?this.renderer.getLayerBoundMaterial(this.promoteLayerZeroByLayerColor(p,t),i,n)??p:p),D.syncStyleMaterialIdFromMaterials(D.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,D.syncStyleMaterialIdFromMaterials(D.getSceneDrawableUserData(o),c))})}shouldRemap(e,t){const i=D.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=D.getMaterialMetadata(e),n=D.hasByLayerBinding(i)&&i.isByLayerColor!==!0;return t==="0"&&n&&D.setMaterialMetadata(e,{isByLayerColor:!0}),e}}const Ar=1,Gt=4;function Cr(s){return{isOff:s.isOff,isFrozen:s.isFrozen,isLocked:((s.standardFlags??0)&Gt)!==0}}function Al(s,e){return s.isOff===e.isOff&&s.isFrozen===e.isFrozen&&s.isLocked===e.isLocked}const $="Layer",Cl="Entity";function W(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 yt(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|Ar:i&~Ar}static setLayerLockedState(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|Gt:i&~Gt}static isLayerLocked(e){return((e.standardFlags??0)&Gt)!==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 W(this.db,$,()=>{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?W(this.db,$,()=>{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 W(this.db,$,()=>{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 W(this.db,$,()=>{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 W(this.db,$,()=>{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:W(this.db,$,()=>{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)?W(this.db,$,()=>{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)?W(this.db,$,()=>{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:W(this.db,$,()=>{const i=j.openLayerForWrite(this.db,e);return i?(i.linetype=t,!0):!1})}setLayerTransparency(e,t){return this.db.tables.layerTable.getAt(e)?W(this.db,$,()=>{const i=j.openLayerForWrite(this.db,e);return i?(i.transparency=t,!0):!1}):!1}isolateSingleLayer(e){return this.db.tables.layerTable.getAt(e)?W(this.db,$,()=>{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 W(this.db,$,()=>{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 W(this.db,$,()=>{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 W(this.db,$,()=>{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 W(this.db,$,()=>{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 W(this.db,$,()=>{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);W(this.db,$,()=>{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)?W(this.db,$,()=>{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);W(this.db,$,()=>{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?W(this.db,$,()=>{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 W(this.db,$,()=>{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?W(this.db,$,()=>{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 W(this.db,$,()=>{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?W(this.db,$,()=>{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}:(W(this.db,$,()=>{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)?(W(this.db,$,()=>{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 W(this.db,$,()=>{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,Cr(p));r&&(this.db.clayer=r.name);const l=new Set;for(const p of i.newIterator()){const y=j.openLayerForWrite(this.db,p);if(y){if(n.has(y.name)){y.isOff&&(y.isOff=!1,l.add(y.name)),y.isFrozen&&(j.setLayerFrozenState(y,!1),l.add(y.name)),j.isLayerLocked(y)&&(j.setLayerLockedState(y,!1),l.add(y.name));continue}if(t==="Off"){y.isOff||(y.isOff=!0,l.add(y.name));continue}j.isLayerLocked(y)||(j.setLayerLockedState(y,!0),l.add(y.name))}}const c=[];for(const p of i.newIterator()){const y=a.get(p.name);if(!y)continue;const g=Cr(p);Al(y,g)||c.push({name:p.name,before:y,isolated:g})}const u={currentLayerBefore:o,currentLayerAfter:this.db.clayer,layers:c};return{layerNames:e,affectedLayerCount:l.size,isoSnapshot:u}})}unisolateFromSnapshot(e){return W(this.db,$,()=>{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}:W(this.db,$,()=>{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){W(this.db,$,()=>{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 ne=j;class Pr{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 ne.resolveLayerTraits(t,e)}}const Kt=1e-5;function Si(s){return Number.isFinite(s.minX)&&Number.isFinite(s.minY)&&Number.isFinite(s.maxX)&&Number.isFinite(s.maxY)}function _r(s){const e=new T.Box3;for(const t of s.wcsChildBoxes)Si(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 Im(s){if(s.wcsChildBoxes.length===0)return;const e=_r(s),t=s.wcsBbox;if(!(Math.abs(t.min.x-e.min.x)<=Kt&&Math.abs(t.min.y-e.min.y)<=Kt&&Math.abs(t.min.z-e.min.z)<=Kt&&Math.abs(t.max.x-e.max.x)<=Kt&&Math.abs(t.max.y-e.max.y)<=Kt&&Math.abs(t.max.z-e.max.z)<=Kt))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 Mm(s){Im(s)}function In(s,e){var o;let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const a of s)Si(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 Mn(s){return!(s.children!==void 0&&s.children.length===0)}function Pl(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 Dm=40;class Om{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())_l(n,e)&&((t==null?void 0:t.selectionMode)==="window"&&!Vt(n,e)||i.push(n));return i}collides(e){for(const t of this.items.values())if(_l(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:Xa(e)+t*Dm}}}function _l(s,e){return!(s.maxX<e.minX||s.minX>e.maxX||s.maxY<e.minY||s.minY>e.maxY)}function Ll(s,e,t=0,i=s.length-1,n=Nm){for(;i>t;){if(i-t>600){const l=i-t+1,c=e-t+1,u=Math.log(l),p=.5*Math.exp(2*u/3),y=.5*Math.sqrt(u*p*(l-p)/l)*(c-l/2<0?-1:1),g=Math.max(t,Math.floor(e-c*p/l+y)),f=Math.min(i,Math.floor(e+(l-c)*p/l+y));Ll(s,e,g,f,n)}const r=s[e];let o=t,a=i;for(Ai(s,t,e),n(s[i],r)>0&&Ai(s,t,i);o<a;){for(Ai(s,o,a),o++,a--;n(s[o],r)<0;)o++;for(;n(s[a],r)>0;)a--}n(s[t],r)===0?Ai(s,t,a):(a++,Ai(s,a,i)),a<=e&&(t=a+1),e<=a&&(i=a-1)}}function Ai(s,e,t){const i=s[e];s[e]=s[t],s[t]=i}function Nm(s,e){return s<e?-1:s>e?1:0}class Bm{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(!On(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;On(e,l)&&(t.leaf?i.push(a):Er(e,l)?this._all(a,i):r.push(a))}t=r.pop()}return i}collides(e){let t=this.data;if(!On(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(On(e,o)){if(t.leaf||Er(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=Ht([]),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 u=Fm(e,i.children,t);if(u!==-1)return i.children.splice(u,1),r.push(i),this._condense(r),this}!c&&!i.leaf&&Er(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=Ht(e.slice(t,i+1)),Ut(a,this.toBBox),a;n||(n=Math.ceil(Math.log(r)/Math.log(o)),o=Math.ceil(r/Math.pow(o,n-1))),a=Ht([]),a.leaf=!1,a.height=n;const l=Math.ceil(r/o),c=l*Math.ceil(Math.sqrt(o));El(e,t,i,c,this.compareMinX);for(let u=t;u<=i;u+=c){const p=Math.min(u+c-1,i);El(e,u,p,l,this.compareMinY);for(let y=u;y<=p;y+=l){const g=Math.min(y+l-1,p);a.children.push(this._build(e,y,g,n-1))}}return Ut(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],u=Lr(c),p=Rm(e,c)-u;p<o?(o=p,r=u<r?u:r,a=c):p===o&&u<r&&(r=u,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),Pi(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=Ht(i.children.splice(o,i.children.length-o));a.height=i.height,a.leaf=i.leaf,Ut(i,this.toBBox),Ut(a,this.toBBox),t?e[t-1].children.push(a):this._splitRoot(i,a)}_splitRoot(e,t){this.data=Ht([e,t]),this.data.height=e.height+1,this.data.leaf=!1,Ut(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=Ci(e,0,a,this.toBBox),c=Ci(e,a,i,this.toBBox),u=Vm(l,c),p=Lr(l)+Lr(c);u<r?(r=u,n=a,o=p<o?p:o):u===r&&p<o&&(o=p,n=a)}return n||i-t}_chooseSplitAxis(e,t,i){const n=e.leaf?this.compareMinX:jm,r=e.leaf?this.compareMinY:zm,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=Ci(e,0,t,r),a=Ci(e,i-t,i,r);let l=Dn(o)+Dn(a);for(let c=t;c<i-t;c++){const u=e.children[c];Pi(o,e.leaf?r(u):u),l+=Dn(o)}for(let c=i-t-1;c>=t;c--){const u=e.children[c];Pi(a,e.leaf?r(u):u),l+=Dn(a)}return l}_adjustParentBBoxes(e,t,i){for(let n=i;n>=0;n--)Pi(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():Ut(e[t],this.toBBox)}}function Fm(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 Ut(s,e){Ci(s,0,s.children.length,e,s)}function Ci(s,e,t,i,n){n||(n=Ht(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];Pi(n,s.leaf?i(o):o)}return n}function Pi(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 jm(s,e){return s.minX-e.minX}function zm(s,e){return s.minY-e.minY}function Lr(s){return(s.maxX-s.minX)*(s.maxY-s.minY)}function Dn(s){return s.maxX-s.minX+(s.maxY-s.minY)}function Rm(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 Vm(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 Er(s,e){return s.minX<=e.minX&&s.minY<=e.minY&&e.maxX<=s.maxX&&e.maxY<=s.maxY}function On(s,e){return e.minX<=s.maxX&&e.minY<=s.maxY&&e.maxX>=s.minX&&e.maxY>=s.minY}function Ht(s){return{children:s,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function El(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;Ll(s,o,e,t,n),r.push(e,o,o,t)}}const Gm=40,Km=1.4;class Tl{constructor(e){this.tree=new Bm(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=>Vt(n,e))}collides(e){return this.tree.collides(e)}all(){return this.tree.all()}getStats(){const e=this.tree.all(),t=e.length,i=Xa(e),n=this.idMap.size*Gm;return{kind:"rbush",itemCount:t,estimatedBytes:Math.round(i*Km+n)}}}const Ws=class Ws{constructor(e){this.childIndexes=new Map,this.rootIndex=e??new Tl}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"||Vt(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 Vt(e,t);const n=i.all().filter(Si);return n.length===0?!1:n.every(r=>Vt(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=Pl(t.filter(Si));if(i.length===0)return;const n=In(i,e);Si(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>Ws.THRESHOLD)return new Tl;if(e>0)return new Om}};Ws.THRESHOLD=100;let Tr=Ws;class Wt{static isLayerVisible(e){return!(e.isFrozen||e.isOff)}constructor(e){this._group=new D.AcTrBatchedGroup,this._name=e.name,this._cachedBox=new T.Box3,this._boxDirty=!0,this._group.visible=Wt.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=Wt.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)}}setCompareDisplay(e){this._group.setCompareDisplay(e)}}class Il{constructor(){this.isReference=!1,this._group=new T.Group,this._spatialIndex=new Tr,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(u=>{const p=u.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 D.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 u=r.get(c);u||(u=new Set,r.set(c,u)),u.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],u=a.createPreviewSubset(c,{maxSlots:Math.max(1e4,c.length*8),missingEntity:i});if(!u||u.children.length===0){if(i==="fail")return D.disposePreviewSubset(o),null;continue}o.add(u)}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 Wt(e),this._layers.set(t,i),this._group.add(i.internalObject),this._compareDisplayOptions&&i.setCompareDisplay(this._compareDisplayOptions)),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))}setCompareDisplay(e){this._compareDisplayOptions=e,this._layers.forEach(t=>t.setCompareDisplay(e))}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=In(t);i={minX:n.minX,minY:n.minY,maxX:n.maxX,maxY:n.maxY,id:e.objectId}}else if(e instanceof D.AcTrGroup&&e.wcsChildBoxes.length>0){const n=In(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 D.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 T.Scene,this._transientManager=new D.AcTrTransientManager(this._scene),this._htmlTransientManager=new D.AcTrHtmlTransientManager(this._scene),this._previewOverlayManager=new D.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 u={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,u.line+=p.summary.totalSize.unbatchedByType.line,u.mesh+=p.summary.totalSize.unbatchedByType.mesh,u.point+=p.summary.totalSize.unbatchedByType.point,u.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:u}}}}addEmptyLayout(e){const t=this._layouts.get(e);if(t)return t;const i=new Il;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 D.AcTrTransientManager(this._scene),this._htmlTransientManager=new D.AcTrHtmlTransientManager(this._scene),this._previewOverlayManager=new D.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)}setCompareDisplay(e){this._layouts.forEach(t=>{t.isReference||t.setCompareDisplay(e)})}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 D.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 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 Nn="ml-html-text-editing",Dl="ml-markup-inline-text-edit-styles",Um=400,Ol=6,_i=new WeakSet;let Bn=0;function Nl(){return Bn>0}function Hm(){if(typeof document>"u"||document.getElementById(Dl))return;const s=document.createElement("style");s.id=Dl,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 Wm(s){const e=window.getSelection();if(!e)return;const t=document.createRange();t.selectNodeContents(s),e.removeAllRanges(),e.addRange(t)}function $m(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>Um)return!1;const i=e.x-s.x,n=e.y-s.y;return i*i+n*n<=Ol*Ol}function Ir(s){var r;Hm();const{el:e,multiline:t=!1}=s,i=s.listenOn??e;if(_i.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 v;_i.add(e),Bn+=1,i.style.pointerEvents="auto",e.style.pointerEvents="auto",e.textContent=n,e.classList.add(Nn),i.classList.add(Nn),e.tabIndex=0,$m(e);let a=!1,l=performance.now()+300;const c=()=>{var w;(w=s.signal)==null||w.removeEventListener("abort",f),e.classList.remove(Nn),i.classList.remove(Nn),e.removeAttribute("contenteditable"),e.removeAttribute("tabindex"),i.removeEventListener("pointerdown",p,!0),e.removeEventListener("keydown",y),e.removeEventListener("blur",g),_i.delete(e),Bn=Math.max(0,Bn-1)},u=w=>{if(a)return;a=!0;const x=(e.textContent??"").trim();if(!w){e.textContent=n,c(),o(void 0);return}e.textContent=x,c(),o(x)},p=w=>{w.stopPropagation()},y=w=>{if(!(w.isComposing||w.keyCode===229)){if(w.stopPropagation(),w.key==="Escape"){w.preventDefault(),u(!1);return}w.key==="Enter"&&(!t||!w.shiftKey)&&(w.preventDefault(),u(!0))}},g=()=>{if(performance.now()<l){e.focus();return}u(!0)},f=()=>u(!1);i.addEventListener("pointerdown",p,!0),e.addEventListener("keydown",y),e.addEventListener("blur",g),(v=s.signal)==null||v.addEventListener("abort",f),requestAnimationFrame(()=>{a||(l=performance.now()+300,e.focus(),Wm(e))})})}function Fn(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||_i.has(t))return;const y=H().get(i),g=((y==null?void 0:y.text)??t.textContent??"").trim();H().setSelectedId(i),e.htmlTransientManager.selectGroup(i),l=new AbortController,Ir({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",()=>{H().updateMeta(i,{text:f})})})},u=y=>{if(y.button!==0||_i.has(t))return;const g={t:performance.now(),x:y.clientX,y:y.clientY},f=y.detail>=2||Bl(o,g);o=g,f&&(y.stopPropagation(),c())},p=y=>{y.preventDefault(),y.stopPropagation(),c()};return r.addEventListener("pointerdown",u,!0),r.addEventListener("dblclick",p),()=>{a=!0,l==null||l.abort(),r.removeEventListener("pointerdown",u,!0),r.removeEventListener("dblclick",p)}}let Mr=null;function Fl(s){Mr=s}function Li(){if(!Mr)throw new Error("[AcApCommandServices] Not bound. Create AcApDocManager before running commands.");return Mr}var z=(s=>(s[s.Read=0]="Read",s[s.Review=4]="Review",s[s.Write=8]="Write",s))(z||{});class R{constructor(){this._mode=z.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,ie.emit("session-db-edit-committed",{}),mt()),e.view.editor.events.commandEnded.dispatch({command:this}),this.onCommandEnded(e)}}shouldRecordUndoStack(e){return this.recordsUndoStack?e.doc.openMode>=z.Review&&this.mode>=z.Review:!1}async execute(e){}showMessage(e,t="info",i){Li().showMessage(e,t,i)}notify(e,t="info"){ie.emit("message",{message:e,type:t})}showBusyIndicator(e){Li().showBusyIndicator(e)}hideBusyIndicator(){Li().hideBusyIndicator()}async withBusyIndicator(e,t){return Li().withBusyIndicator(e,t)}}class Ym{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 li=class li{constructor(){this._activeCommand=null,this._activeView=null,this._activePromise=null,this._commandsByGroup=[],this._systemCommandGroup={groupName:li.SYSTEMT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._defaultCommandGroup={groupName:li.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 Ym(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}};li.SYSTEMT_COMMAND_GROUP_NAME="ACAD",li.DEFAUT_COMMAND_GROUP_NAME="USER";let he=li;function Zm(s){ie.emit("message",{message:s,type:"warning"})}class Dr{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 Xm={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 Or(s,e=document.documentElement){const t=Xm[s];Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])}),e.setAttribute("data-ml-ui-theme",s)}function Nr(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 jl=600,zl=`(max-width: ${jl}px)`;function qm(){var s;return((s=window.matchMedia)==null?void 0:s.call(window,zl).matches)??!1}const Rl=960,Vl=`(max-width: ${Rl}px)`;function Jm(){var s;return((s=window.matchMedia)==null?void 0:s.call(window,Vl).matches)??!1}const Qm={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])},Br="settings";function Gl(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 pe{constructor(){this.events={modified:new d.AcCmEventManager}}static get instance(){return this._instance||(this._instance=new pe),this._instance}set(e,t){const i=this.settings;i[e]=t,localStorage.setItem(Br,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(Br),t=e==null?{}:JSON.parse(e),{settings:i,migrated:n}=Gl(t),r=sa.defaults(i,Qm);return n&&localStorage.setItem(Br,JSON.stringify(r)),r}}const ey=1e-10;function jn(s,e,t,i){return Math.hypot(s-t,e-i)}function ty(s,e,t,i,n,r){const o=n-t,a=r-i,l=o*o+a*a;if(l<1e-18)return jn(s,e,t,i);let c=((s-t)*o+(e-i)*a)/l;return c=Math.max(0,Math.min(1,c)),jn(s,e,t+c*o,i+c*a)}function iy(s,e,t){if(Math.abs(t)>ey)try{const i=new d.AcGeCircArc2d(s,e,t);return!(i.radius>0)||!Number.isFinite(i.radius)?void 0:i}catch{return}}function $t(s){return{x:s.x,y:s.y,z:s.z??0}}function ny(s,e){const t=new d.AcGePoint3d(s.x,s.y,s.z).applyMatrix4(e);return $t(t)}function zn(s){return typeof s!="string"?s:s.replace(/#\d+$/,"")}function sy(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 ry(s,e){const t=sy(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=iy(a,l,a.bulge),u=c?jn(e.x,e.y,c.nearestPoint(e).x,c.nearestPoint(e).y):ty(e.x,e.y,a.x,a.y,l.x,l.y);u<n&&(n=u,r=c)}if(r)return $t({x:r.center.x,y:r.center.y,z:s.elevation})}function Fr(s,e,t){const i=[];return s.subGetOsnapPoints(d.AcDbOsnapMode.Center,e,e,i,t),i.map(n=>$t(n))}function Kl(s,e,t){const i=s.blockTableRecord;if(!i)return;const n=new d.AcGeMatrix3d().multiplyMatrices(t,s.blockTransform),r=zn(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=Kl(o,e,n);if(a)return a}}}function oy(s,e,t){if(!t)return Fr(s,e);const i=Kl(s,t,new d.AcGeMatrix3d);if(!i)return Fr(s,e,zn(t));const n=i.transform.clone().invert(),r=new d.AcGePoint3d(e).applyMatrix4(n);return jr(i.entity,r).map(o=>ny(o,i.transform))}function jr(s,e,t){if(s instanceof d.AcDbBlockReference)return oy(s,e,t);if(s instanceof d.AcDbCircle)return[$t(s.center)];if(s instanceof d.AcDbArc)return[$t(s.center)];if(s instanceof d.AcDbEllipse)return[$t(s.center)];if(s instanceof d.AcDbPolyline||s instanceof d.AcDb2dPolyline){const i=ry(s,e);return i?[i]:[]}return Fr(s,e,t)}function ay(s,e){const t=[...s];for(const i of e)t.some(n=>Ul(n,i))||t.push(i);return t}function Ul(s,e,t=1e-8){return jn(s.x,s.y,e.x,e.y)<=t}const ly=20,cy=48;class wt{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=>!Ul(i,t))}resolve(e){const t=e.hitRadiusPx??ly,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,u=-1;for(let p=0;p<a.length;p++){const y=a[p],g=e.cursorWcs.x-y.x,f=e.cursorWcs.y-y.y,v=Math.hypot(g,f);if(v>=o)continue;const w=wt.osnapModePriority(y.type);(w<l||w===l&&v<c)&&(l=w,c=v,u=p)}return u!==-1?a[u]: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(pe.instance.osnapModes).forEach(a=>{a!==d.AcDbOsnapMode.Intersection&&this.collectOsnapPointsByMode(e,a,t,i,n,r)})}collectIntersectionOsnapPoints(e,t){const i=e.slice(0,cy);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),u=[],p=new Set;return n.forEach(y=>{const g=o.getIdAt(y.id);g&&(p.has(y.id)||(p.add(y.id),u.push(g)),y.children&&y.children.length>0?y.children.forEach(f=>this.collectOsnapPointsInAvailableModes(g,a,l,c,zn(f.id))):this.collectOsnapPointsInAvailableModes(g,a,l,c))}),d.acdbHasOsnapMode(pe.instance.osnapModes,d.AcDbOsnapMode.Intersection)&&this.collectIntersectionOsnapPoints(u,a),this.updateAcquiredCenters(n,o,l),a}updateAcquiredCenters(e,t,i){if(!d.acdbHasOsnapMode(pe.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(...jr(o,i,zn(a.id)))}):n.push(...jr(o,i)))}),this._acquiredCenters=ay(this._acquiredCenters,n)}}class Rn{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,Rn.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 zr{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 Rn(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 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 Hl 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 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 Wl{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 zr(e),this._jig=new Hl(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;yt(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(wt.displayCenterMarks(this._view.osnapResolver.acquiredCenterMarks,r)),r?(this._osnapMarkerManager.showMarker(r,wt.osnapModeToMarkerType(r.type)),{x:r.x,y:r.y,z:r.z??0}):n}}class Vn{constructor(e,t){this._host=e,this._state="normal",Vn.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 $l(s){const e=new d.AcCmColor(d.AcCmColorMethod.ByACI,s);return e.cssColor??`rgb(${e.red}, ${e.green}, ${e.blue})`}function Yl(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:$l(i),hotColorCss:$l(n)}}const dy=new Set([d.AcDbSystemVariables.GRIPSIZE.toLowerCase(),d.AcDbSystemVariables.GRIPCOLOR.toLowerCase(),d.AcDbSystemVariables.GRIPHOT.toLowerCase()]);function uy(s){return dy.has(s.toLowerCase())}function hy(s,e){return e<=0?!1:s>e}function py(s,e,t,i,n){return s!==z.Write||e||t?!1:!hy(i,n)}class Zl{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=Yl(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 Vn(this._view.container,i),u={entityId:n,gripIndex:a,wcsPoint:l,handle:c};this.wireHandleEvents(u),this._entries.push(u),this.positionEntry(u)}}}canShowGrips(){const e=k.instance.curDocument,t=d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.GRIPOBJLIMIT,e.database);return py(e.openMode,this._view.editor.isActive,!!$e.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}uy(t)&&this.applyAppearance()}applyAppearance(){if(this._entries.length===0)return;const e=Yl(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 Wl(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 Ie=(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))(Ie||{});class Xl{constructor(e){this._backgroundColor=d.ACGI_MODEL_SPACE_BACKGROUND,this._totalLength=20,this._view=e,this._cursorMap=new Map,this.setCursorColor(Ln(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,Ln(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(Ln(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 ql(s){const e=s??d.acdbHostApplicationServices().workingDatabase,t=d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.ORTHOMODE,e);return Number(t)!==0}function Jl(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 Yt=2,Ql=4;function Ei(s){return s??d.acdbHostApplicationServices().workingDatabase}function ec(s,e,t){const i=d.AcDbSysVarManager.instance().getVar(s,e),n=Number(i);return Number.isFinite(n)?n:t}function my(s,e){const t=d.AcDbSysVarManager.instance().getVar(s,e);return t==null?"":String(t)}function Gn(s){const e=Ei(s);return ec(d.AcDbSystemVariables.POLARMODE,e,0)}function tc(s){const e=Ei(s);return ec(d.AcDbSystemVariables.POLARANG,e,90)}function ic(s){const e=Ei(s);return my(d.AcDbSystemVariables.POLARADDANG,e)}function nc(s){return(Gn(s)&Yt)!==0}function yy(s,e,t){let i=s-e;return t===1&&(i=-i),d.AcGeMathUtil.normalizeAngle(i)}function gy(s,e,t){let i=s;return t===1&&(i=-i),d.AcGeMathUtil.normalizeAngle(i+e)}function fy(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 by(s,e){const t=Gn(s),i=(t&Yt)!==0,n=(t&Ql)!==0,r=new Set;if(e.includeOrtho)for(const o of[0,90,180,270])r.add(o);if(i){const o=tc(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 fy(ic(s)))r.add(a)}return[...r].map(d.AcGeMathUtil.degToRad)}function sc(s,e){const t=Math.abs(d.AcGeMathUtil.normalizeAngle(s-e));return Math.min(t,Math.PI*2-t)}function wy(s,e){let t=e[0],i=sc(s,t);for(let n=1;n<e.length;n++){const r=e[n],o=sc(s,r);o<i&&(i=o,t=r)}return t}function rc(s,e,t){const i=Ei(t),n=ql(i),r=nc(i);if(!n&&!r)return s;if(n&&!r)return Jl(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),u=yy(c,i.angbase,i.angdir),p=by(i,{includeOrtho:n});if(p.length===0)return s;const y=wy(u,p),g=gy(y,i.angbase,i.angdir);return{x:e.x+l*Math.cos(g),y:e.y+l*Math.sin(g)}}function vy(s){const e=Ei(s),t=Gn(e),i=(t&Yt)!==0?t&~Yt:t|Yt;return d.AcDbSysVarManager.instance().setVar(d.AcDbSystemVariables.POLARMODE,i,e),i}class Kn{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 Rr{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 oc{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],u=S=>{if(!S)return;const A=S.indexOf(",");return A>=0?S.substring(0,A):S},p=u(c),y=u(l),g=p!==void 0,f=y!==void 0,v=g?p:"",w=f?y:void 0,x=new Rr(v||w||"",v,w,!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 Rr(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 Ye{constructor(e,t){this._message="",this._appendKeywordsToMessage=!0,this._isReadOnly=!1,this._keywords=new oc,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(u=>u.toLowerCase()===a.toLowerCase());c||(c=a),this._keywords.add(a,c)}}}return this}}class Ce extends Ye{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 Un extends Ye{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 ze{constructor(e,t){this.status=e,this.stringResult=t}}class Hn extends ze{constructor(e,t,i){super(e,i),this.value=t}}class Wn extends Ye{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 ke extends Wn{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 se extends Wn{}class Vr extends ze{constructor(e,t){super(e,void 0),this.value=t}}class Pe extends Vr{constructor(e,t){super(e,t)}}class Ze extends Ye{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 $n extends ze{constructor(e,t,i){super(e),this.objectId=t,this.pickedPoint=i}}class Gr extends Wn{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 Yn extends Vr{constructor(e,t){super(e,t)}}class re extends Ye{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 Ye{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 Zn extends ze{constructor(e,t){super(e,void 0),this.value=t}}class _t extends Ye{constructor(e,t){super(e,t),this._singleOnly=!1}get singleOnly(){return this._singleOnly}set singleOnly(e){this._singleOnly=e}}class Ti extends ze{constructor(e,t,i){super(e,i),this.value=t}}class ue extends Ye{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 ct=class ct{static get messages(){return this._messages}static getLocaleMessage(e){return this._messages[e]}static mergeLocaleMessage(e,t){ac(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(he.SYSTEMT_COMMAND_GROUP_NAME,e,t)}static sysCmdKey(e,t){return this.cmdKey(he.SYSTEMT_COMMAND_GROUP_NAME,e,t)}static userCmd(e,t){return this.cmd(he.DEFAUT_COMMAND_GROUP_NAME,e,t)}static userCmdKey(e,t){return this.cmdKey(he.DEFAUT_COMMAND_GROUP_NAME,e,t)}static sysCmdDescription(e){return this.cmdDescription(he.SYSTEMT_COMMAND_GROUP_NAME,e)}static sysCmdPrompt(e){return this.cmdPrompt(he.SYSTEMT_COMMAND_GROUP_NAME,e)}};ct._messages={en:{},zh:{},tr:{},cs:{},ar:{}},ct._currentLocale="en",ct.events={localeChanged:new d.AcCmEventManager},ct.userCmdDescription=e=>ct.cmdDescription(he.DEFAUT_COMMAND_GROUP_NAME,e),ct.userCmdPrompt=e=>ct.cmdPrompt(he.DEFAUT_COMMAND_GROUP_NAME,e);let h=ct;function ac(s,e){for(const t of Object.keys(e)){const i=e[t],n=s[t];lc(n)&&lc(i)?ac(n,i):s[t]=i}}function lc(s){return typeof s=="object"&&s!==null}const P={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"},close:{description:"Closes the current 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:{}},ky={...P,ACAD:{...P.ACAD,"-hatch":{...P.ACAD["-hatch"],description:"إنشاء تعبئة تهشير باستخدام خيارات سطر الأوامر دون واجهة الشريط"},"-layer":{...P.ACAD["-layer"],description:"إدارة الطبقات باستخدام خيارات سطر الأوامر"},about:{...P.ACAD.about,description:"عرض معلومات حول mlightcad"},acadver:{...P.ACAD.acadver,description:"عرض معرّف إصدار قاعدة بيانات الرسم (للقراءة فقط)"},angbase:{...P.ACAD.angbase,description:"تحديد اتجاه زاوية الأساس 0 بالنسبة إلى نظام الإحداثيات UCS الحالي"},angdir:{...P.ACAD.angdir,description:"تحديد ما إذا كانت الزوايا الموجبة تُقاس مع أو عكس اتجاه عقارب الساعة"},arc:{...P.ACAD.arc,description:"إنشاء قوس"},aunits:{...P.ACAD.aunits,description:"تحديد تنسيق عرض الزوايا"},auprec:{...P.ACAD.auprec,description:"تحديد دقة عرض الزوايا بالتكامل مع AUNITS"},cdxf:{...P.ACAD.cdxf,description:"تصدير الرسم الحالي إلى DXF"},cpdf:{...P.ACAD.cpdf,description:"تصدير الرسم الحالي إلى PDF"},cecolor:{...P.ACAD.cecolor,description:"تحديد اللون الافتراضي الحالي للعناصر الجديدة"},celtscale:{...P.ACAD.celtscale,description:"التحكم في معامل مقياس نوع الخط للعناصر الجديدة"},celtype:{...P.ACAD.celtype,description:"تحديد نوع الخط للعناصر الجديدة"},celweight:{...P.ACAD.celweight,description:"تحديد سُمك الخط الافتراضي للعناصر الجديدة"},cetransparency:{...P.ACAD.cetransparency,description:"تحديد الشفافية للعناصر الجديدة"},cachefont:{...P.ACAD.cachefont,description:"تخزين ملف خط محلي مؤقتًا في IndexedDB لاستخدامه في عرض النص"},circle:{...P.ACAD.circle,description:"إنشاء دائرة باستخدام المركز ونصف القطر"},clayer:{...P.ACAD.clayer,description:"تحديد الطبقة الحالية للعناصر الجديدة وعمليات التحرير"},cmleaderstyle:{...P.ACAD.cmleaderstyle,description:"تحديد اسم نمط Multileader الحالي"},cmlscale:{...P.ACAD.cmlscale,description:"التحكم في العرض الكلي للخط متعدد المسارات"},cmlstyle:{...P.ACAD.cmlstyle,description:"تحديد اسم نمط الخط متعدد المسارات الحالي"},colortheme:{...P.ACAD.colortheme,description:"التحكم في سمة ألوان واجهة المستخدم بين الوضع الداكن والفاتح"},copy:{...P.ACAD.copy,description:"نسخ العناصر المحددة إلى مواضع جديدة",prompt:"حدد العناصر"},csvg:{...P.ACAD.csvg,description:"تحويل الرسم الحالي إلى SVG"},chtml:{...P.ACAD.chtml,description:"تصدير الرسم الحالي إلى ملف HTML مستقل يعمل دون اتصال"},"-chtml":{...P.ACAD["-chtml"],description:"تصدير الرسم الحالي إلى HTML باستخدام خيارات سطر الأوامر"},dimlinear:{...P.ACAD.dimlinear,description:"إنشاء أبعاد خطية"},dimstyle:{...P.ACAD.dimstyle,description:"تحديد اسم نمط الأبعاد الحالي"},dwgname:{...P.ACAD.dwgname,description:"عرض اسم ملف الرسم الحالي (للقراءة فقط)"},loginname:{...P.ACAD.loginname,description:"عرض اسم تسجيل دخول المستخدم (للقراءة فقط)"},dynmode:{...P.ACAD.dynmode,description:"التحكم في إعدادات الإدخال الديناميكي عند المؤشر"},dynprompt:{...P.ACAD.dynprompt,description:"التحكم في عرض رسائل الأوامر داخل تلميحات الإدخال الديناميكي"},ellipse:{...P.ACAD.ellipse,description:"إنشاء قطع ناقص أو قوس بيضاوي باستخدام نهايات المحور أو المركز"},erase:{...P.ACAD.erase,description:"حذف العناصر المحددة من الرسم",prompt:"حدد العناصر"},extmax:{...P.ACAD.extmax,description:"عرض الركن العلوي الأيمن لحدود الرسم في مساحة النموذج (للقراءة فقط)"},extmin:{...P.ACAD.extmin,description:"عرض الركن السفلي الأيسر لحدود الرسم في مساحة النموذج (للقراءة فقط)"},entout:{...P.ACAD.entout,description:"تصدير صورة معاينة مدمجة للعناصر المحددة",prompt:"حدد العناصر"},hideobjects:{...P.ACAD.hideobjects,description:"إخفاء العناصر المحددة مؤقتًا من العرض",prompt:"حدد العناصر"},imageattach:{...P.ACAD.imageattach,description:"إرفاق صورة نقطية كمرجع خارجي إلى الرسم الحالي"},"-insert":{...P.ACAD["-insert"],description:"إدراج تعريف كتلة داخل الرسم الحالي باستخدام سطر الأوامر"},xattach:{...P.ACAD.xattach,description:"إرفاق رسم DWG أو DXF كمرجع خارجي إلى الرسم الحالي"},gripcolor:{...P.ACAD.gripcolor,description:"تحديد لون مقابض التحكم غير المحددة للعناصر المحددة"},griphot:{...P.ACAD.griphot,description:"تحديد لون مقابض التحكم المحددة"},gripobjlimit:{...P.ACAD.gripobjlimit,description:"إيقاف عرض مقابض التحكم عندما يتجاوز عدد العناصر المحددة الحد المعين، والقيمة 0 تعني عدم وجود حد"},grips:{...P.ACAD.grips,description:"التحكم في عرض مقابض التحكم على العناصر المحددة"},gripsize:{...P.ACAD.gripsize,description:"تحديد حجم مربعات مقابض التحكم بالبكسل"},hatch:{...P.ACAD.hatch,description:"ملء منطقة مغلقة أو عناصر محددة بنمط تهشير"},ipdf:{...P.ACAD.ipdf,description:"استيراد الهندسة المتجهية من ملف PDF"},hpang:{...P.ACAD.hpang,description:"تحديد الزاوية الافتراضية بالراديان لأنماط التهشير الجديدة"},hpassoc:{...P.ACAD.hpassoc,description:"التحكم في كون التهشير الجديد ترابطيًا"},hpbackgroundcolor:{...P.ACAD.hpbackgroundcolor,description:"تحديد لون الخلفية الافتراضي لأنماط التهشير الجديدة"},hpcolor:{...P.ACAD.hpcolor,description:"تحديد اللون الافتراضي للتهشير الجديد"},hpdouble:{...P.ACAD.hpdouble,description:"التحكم في مضاعفة أنماط التهشير المعرفة بواسطة المستخدم"},hpislanddetection:{...P.ACAD.hpislanddetection,description:"التحكم في كيفية التعامل مع الجزر داخل حدود التهشير الجديدة"},hplayer:{...P.ACAD.hplayer,description:"تحديد الطبقة الافتراضية للتهشير والتعبئة الجديدة"},hpname:{...P.ACAD.hpname,description:"تحديد اسم نمط التهشير الافتراضي للعناصر الجديدة في الجلسة الحالية"},hpscale:{...P.ACAD.hpscale,description:"تحديد معامل المقياس الافتراضي لأنماط التهشير الجديدة"},hpseparate:{...P.ACAD.hpseparate,description:"التحكم في إنشاء عنصر تهشير واحد أو عناصر منفصلة عند وجود عدة حدود"},hptransparency:{...P.ACAD.hptransparency,description:"تحديد الشفافية الافتراضية للتهشير والتعبئة الجديدة"},insunits:{...P.ACAD.insunits,description:"تحديد وحدات الرسم المستخدمة في التحجيم التلقائي للكتل والصور والمراجع الخارجية عند الإدراج"},laycur:{...P.ACAD.laycur,description:"تغيير طبقة العناصر المحددة إلى الطبقة الحالية",prompt:"حدد العناصر المطلوب نقلها إلى الطبقة الحالية"},laydel:{...P.ACAD.laydel,description:"حذف طبقة وجميع العناصر الموجودة عليها"},layerclose:{...P.ACAD.layerclose,description:"إغلاق مدير خصائص الطبقات"},layerp:{...P.ACAD.layerp,description:"التراجع عن آخر تغيير أو مجموعة تغييرات في إعدادات الطبقات"},layfrz:{...P.ACAD.layfrz,description:"تجميد طبقة العناصر المحددة",prompt:"حدد عنصرًا على الطبقة المراد تجميدها"},layiso:{...P.ACAD.layiso,description:"عزل طبقات العناصر المحددة",prompt:"حدد عناصر على الطبقات المراد عزلها"},laylck:{...P.ACAD.laylck,description:"قفل طبقة العناصر المحددة",prompt:"حدد عنصرًا على الطبقة المراد قفلها"},layoff:{...P.ACAD.layoff,description:"إيقاف طبقة العناصر المحددة",prompt:"حدد عنصرًا على الطبقة المراد إيقافها"},layon:{...P.ACAD.layon,description:"تشغيل جميع الطبقات في الرسم"},laythw:{...P.ACAD.laythw,description:"إلغاء تجميد جميع الطبقات المجمدة في الرسم"},layulk:{...P.ACAD.layulk,description:"إلغاء قفل طبقة العناصر المحددة",prompt:"حدد عنصرًا على الطبقة المراد إلغاء قفلها"},layuniso:{...P.ACAD.layuniso,description:"استعادة الطبقات التي تم إخفاؤها أو قفلها بواسطة LAYISO"},line:{...P.ACAD.line,description:"رسم مقاطع خطوط مستقيمة بين النقاط"},log:{...P.ACAD.log,description:"تسجيل معلومات تصحيح الأخطاء في وحدة التحكم"},ltscale:{...P.ACAD.ltscale,description:"تحديد معامل مقياس نوع الخط العام للرسم"},lunits:{...P.ACAD.lunits,description:"تحديد تنسيق عرض الإحداثيات والمسافات"},luprec:{...P.ACAD.luprec,description:"تحديد دقة عرض الوحدات الخطية بالتكامل مع LUNITS"},lwdisplay:{...P.ACAD.lwdisplay,description:"التحكم في عرض سُمك الخطوط داخل الرسم"},clearmeasurements:{...P.ACAD.clearmeasurements,description:"إزالة جميع القياسات من المخطط الحالي"},measurementvis:{...P.ACAD.measurementvis,description:"إظهار أو إخفاء القياسات في المخطط الحالي"},measurementexport:{...P.ACAD.measurementexport,description:"تصدير القياسات إلى ملف JSON جانبي"},measurementimport:{...P.ACAD.measurementimport,description:"استيراد القياسات من ملف JSON جانبي"},measurearea:{...P.ACAD.measurearea,description:"حساب المساحة والمحيط للعناصر أو النقاط المحددة"},measureangle:{...P.ACAD.measureangle,description:"قياس الزاوية بين خطين أو باستخدام ثلاث نقاط"},measurearc:{...P.ACAD.measurearc,description:"قياس طول مقطع قوس"},measuredistance:{...P.ACAD.measuredistance,description:"قياس المسافة وفروق الإحداثيات بين نقطتين"},measurepoint:{...P.ACAD.measurepoint,description:"قياس إحداثيات X وY لنقطة محددة"},measurement:{...P.ACAD.measurement,description:"تحديد ما إذا كان الرسم يستخدم الوحدات الإمبراطورية أو المترية"},measurementcolor:{...P.ACAD.measurementcolor,description:"تحديد اللون المستخدم لتراكبات القياس"},modelbkcolor:{...P.ACAD.modelbkcolor,description:"تحديد لون خلفية مساحة النموذج"},mline:{...P.ACAD.mline,description:"إنشاء عدة خطوط متوازية كعنصر متعدد الخطوط واحد"},move:{...P.ACAD.move,description:"نقل العناصر المحددة باستخدام متجه إزاحة",prompt:"حدد العناصر"},offset:{...P.ACAD.offset,description:"إنشاء منحنيات أو خطوط متعددة أو دوائر موازية على مسافة محددة"},mtext:{...P.ACAD.mtext,description:"إنشاء عنصر نص متعدد الأسطر"},open:{...P.ACAD.open,description:"فتح ملف رسم موجود"},openprof:{...P.ACAD.openprof,description:"التحكم في تسجيل أزمنة مراحل فتح الملفات داخل وحدة التحكم"},openperf:{...P.ACAD.openperf,description:"فتح لوحة أداء الفتح وعرض أزمنة آخر عملية فتح للرسم"},orthomode:{...P.ACAD.orthomode,description:"تقييد حركة المؤشر على المحور الأفقي أو الرأسي"},osmode:{...P.ACAD.osmode,description:"تحديد أوضاع Object Snap المستمرة باستخدام قيمة bitcode"},pan:{...P.ACAD.pan,description:"تحريك العرض دون تغيير اتجاه الرؤية أو مستوى التكبير"},paperbkcolor:{...P.ACAD.paperbkcolor,description:"تحديد لون خلفية مساحة الورق أو المخطط"},pdmode:{...P.ACAD.pdmode,description:"التحكم في طريقة عرض عناصر POINT"},pdsize:{...P.ACAD.pdsize,description:"تحديد حجم عرض عناصر POINT"},pickbox:{...P.ACAD.pickbox,description:"تحديد حجم مربع التحديد المستخدم لاختيار العناصر بالبكسل"},pline:{...P.ACAD.pline,description:"إنشاء متعدد خطوط باستخدام عدة نقاط"},pngout:{...P.ACAD.pngout,description:"تصدير الرسم إلى PNG"},point:{...P.ACAD.point,description:"إنشاء نقاط"},polaraddang:{...P.ACAD.polaraddang,description:"تخزين زوايا إضافية للتتبع القطبي كقائمة مفصولة بفواصل منقوطة"},polarang:{...P.ACAD.polarang,description:"تحديد مقدار زيادة الزاوية للتتبع القطبي"},polarmode:{...P.ACAD.polarmode,description:"التحكم في إعدادات التتبع القطبي وتتبع Object Snap"},polygon:{...P.ACAD.polygon,description:"إنشاء مضلع منتظم باستخدام المركز ونصف القطر أو باستخدام أحد أضلاع المضلع"},qnew:{...P.ACAD.qnew,description:"بدء رسم جديد"},close:{...P.ACAD.close,description:"إغلاق الرسم الحالي"},ray:{...P.ACAD.ray,description:"إنشاء شعاع يبدأ من نقطة ويمتد إلى ما لا نهاية"},rectang:{...P.ACAD.rectang,description:"إنشاء مستطيل بتحديد ركنين متقابلين"},regen:{...P.ACAD.regen,description:"إعادة رسم العرض الحالي"},revcloud:{...P.ACAD.revcloud,description:"إنشاء أو تعديل سحابة مراجعة"},markuptext:{...P.ACAD.markuptext,description:"وضع علامة مراجعة نصية"},markupline:{...P.ACAD.markupline,description:"إنشاء علامة مراجعة خطية"},markuparrow:{...P.ACAD.markuparrow,description:"إنشاء سهم مراجعة"},markupcloud:{...P.ACAD.markupcloud,description:"إنشاء سحابة مراجعة"},markuprect:{...P.ACAD.markuprect,description:"إنشاء مستطيل مراجعة"},markupcircle:{...P.ACAD.markupcircle,description:"إنشاء دائرة مراجعة"},markuphighlight:{...P.ACAD.markuphighlight,description:"إنشاء مستطيل تمييز"},markupcallout:{...P.ACAD.markupcallout,description:"إنشاء وسيلة شرح: حدد رأس خط التوجيه ثم موضع مربع النص ثم أدخل النص"},markupstamp:{...P.ACAD.markupstamp,description:"وضع ختم أو رمز مخصص"},markupvis:{...P.ACAD.markupvis,description:"إظهار أو إخفاء علامات المراجعة"},clearmarkups:{...P.ACAD.clearmarkups,description:"مسح جميع علامات المراجعة من المخطط الحالي"},markupexport:{...P.ACAD.markupexport,description:"تصدير علامات المراجعة إلى ملف JSON جانبي"},markupimport:{...P.ACAD.markupimport,description:"استيراد علامات المراجعة من ملف JSON جانبي"},markuppanel:{...P.ACAD.markuppanel,description:"فتح لوحة علامات المراجعة"},rotate:{...P.ACAD.rotate,description:"تدوير العناصر المحددة حول نقطة أساس",prompt:"حدد العناصر"},select:{...P.ACAD.select,description:"تحديد العناصر"},shortcutmenu:{...P.ACAD.shortcutmenu,description:"التحكم في إتاحة القوائم المختصرة داخل منطقة الرسم"},sketch:{...P.ACAD.sketch,description:"إنشاء سلسلة من مقاطع الخطوط بالرسم الحر"},spline:{...P.ACAD.spline,description:"إنشاء منحنى Spline ناعم باستخدام نقاط التحكم"},textstyle:{...P.ACAD.textstyle,description:"تحديد اسم نمط النص الحالي"},unitmode:{...P.ACAD.unitmode,description:"التحكم في عرض الكسور للإحداثيات عندما يكون LUNITS من النوع Architectural أو Fractional"},switchbg:{...P.ACAD.switchbg,description:"التبديل بين الخلفية البيضاء والسوداء لمنطقة الرسم"},unisolateobjects:{...P.ACAD.unisolateobjects,description:"إعادة عرض جميع العناصر التي تم إخفاؤها بواسطة HIDEOBJECTS"},undo:{...P.ACAD.undo,description:"التراجع عن آخر عملية تحرير في قاعدة بيانات الرسم",nothingToUndo:"لا توجد عملية يمكن التراجع عنها."},redo:{...P.ACAD.redo,description:"إعادة آخر عملية تم التراجع عنها",nothingToRedo:"لا توجد عملية يمكن إعادتها."},xline:{...P.ACAD.xline,description:"إنشاء خط إنشائي يمتد إلى ما لا نهاية في الاتجاهين"},zoom:{...P.ACAD.zoom,description:"التكبير أو التصغير لعرض أقصى امتداد لجميع العناصر"}},USER:{...P.USER}},B={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, or a cloud / rectangle / circle outline without a callout",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"}}}},xy={...B,arc:{...B.arc,startPointOrCenter:"حدد نقطة بداية القوس أو",secondPointOrOptions:"حدد النقطة الثانية للقوس أو",secondPoint:"حدد النقطة الثانية للقوس",startPoint:"حدد نقطة بداية القوس",centerPoint:"حدد نقطة مركز القوس",endPoint:"حدد نقطة نهاية القوس",endPointOrOptions:"حدد نقطة نهاية القوس أو",centerPointOrOptions:"حدد نقطة مركز القوس",includedAngle:"حدد الزاوية المحصورة",chordLength:"حدد طول الوتر",tangentDirection:"حدد اتجاه المماس عند نقطة بداية القوس",radius:"حدد نصف قطر القوس",invalid:{...B.arc.invalid,threePoint:"قوس الثلاث نقاط غير صالح: النقاط على استقامة واحدة أو لا يمكنها تعريف قوس.",center:"إدخال المركز غير صالح: يجب أن تقع نقطتا البداية والنهاية على الدائرة نفسها.",angle:"الزاوية غير صالحة: يجب أن تكون الزاوية المحصورة أكبر من 0 وأقل من 360 درجة.",chordLength:"طول الوتر غير صالح: القيمة خارج النطاق المسموح به لنصف القطر الحالي.",direction:"الاتجاه غير صالح: لا يمكن إنشاء القوس باستخدام اتجاه المماس المحدد.",radius:"نصف القطر غير صالح: لا يمكن لنصف القطر المحدد توصيل نقطتي البداية والنهاية."},keywords:{...B.arc.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"}}},circle:{...B.circle,center:"حدد مركز الدائرة",centerOrOptions:"حدد نقطة مركز الدائرة أو",radius:"حدد نصف قطر الدائرة",radiusOrDiameter:"حدد نصف قطر الدائرة أو",diameter:"حدد قطر الدائرة",twoPointFirst:"حدد نقطة النهاية الأولى لقطر الدائرة",twoPointSecond:"حدد نقطة النهاية الثانية لقطر الدائرة",threePointFirst:"حدد النقطة الأولى على الدائرة",threePointSecond:"حدد النقطة الثانية على الدائرة",threePointThird:"حدد النقطة الثالثة على الدائرة",keywords:{...B.circle.keywords,threeP:{display:"3 نقاط(3P)",local:"3 نقاط",global:"3P"},twoP:{display:"نقطتان(2P)",local:"نقطتان",global:"2P"},diameter:{display:"القطر(D)",local:"القطر",global:"Diameter"}}},copy:{...B.copy,basePointOrOptions:"حدد نقطة الأساس أو",displacementOrArray:"حدد الإزاحة أو",secondPointOrArray:"حدد النقطة الثانية أو",modePrompt:"أدخل خيار وضع النسخ",arrayItemCount:"أدخل عدد العناصر في المصفوفة بما في ذلك العنصر الأصلي",arraySecondPointOrFit:"حدد النقطة الثانية أو",arrayFitSecondPoint:"حدد النقطة الثانية",keywords:{...B.copy.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:{...B.dimlinear,xLine1Point:"حدد نقطة أصل خط الامتداد الأول",xLine2Point:"حدد نقطة أصل خط الامتداد الثاني",dimLinePoint:"حدد موقع خط البُعد"},ellipse:{...B.ellipse,axisEndpointOrOptions:"حدد نقطة نهاية محور القطع الناقص أو",arcAxisEndpointOrCenter:"حدد نقطة نهاية محور القوس البيضاوي أو",center:"حدد مركز القطع الناقص",firstAxisEndpoint:"حدد نقطة نهاية المحور الأولى",secondAxisEndpoint:"حدد نقطة النهاية الأخرى للمحور",otherAxisOrRotation:"حدد المسافة إلى المحور الآخر أو",rotationAngle:"حدد زاوية الدوران حول المحور الأكبر",arcStartAngle:"حدد زاوية بداية القوس البيضاوي",arcEndAngle:"حدد زاوية نهاية القوس البيضاوي",invalid:{...B.ellipse.invalid,axis:"المحور غير صالح: يجب أن يكون طول المحور أكبر من 0.",otherAxis:"المحور الآخر غير صالح: يجب أن تكون المسافة أكبر من 0.",rotation:"الدوران غير صالح: يجب أن يكون المحور الأصغر الناتج أكبر من 0."},keywords:{...B.ellipse.keywords,arc:{display:"قوس(A)",local:"قوس",global:"Arc"},center:{display:"المركز(C)",local:"المركز",global:"Center"},rotation:{display:"دوران(R)",local:"دوران",global:"Rotation"}}},hatch:{...B.hatch,prompt:"حدد عنصر حدود أو",pickPoint:"حدد نقطة داخلية (أو اضغط Enter للإنهاء)",select:"حدد العناصر المطلوب تهشيرها",patternName:"أدخل اسم نمط التهشير",scale:"حدد مقياس نمط التهشير",angle:"حدد زاوية نمط التهشير",style:"أدخل نمط التهشير",associative:"حدد حالة الترابط",invalidBoundary:"العناصر المحددة لا تكوّن حدودًا مغلقة.",keywords:{...B.hatch.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"}}},line:{...B.line,firstPoint:"حدد النقطة الأولى",firstPointOrContinue:"حدد النقطة الأولى أو",nextPoint:"حدد النقطة التالية",nextPointWithOptions:"حدد النقطة التالية أو",keywords:{...B.line.keywords,continue:{display:"متابعة(C)",local:"متابعة",global:"Continue"},undo:{display:"تراجع(U)",local:"تراجع",global:"Undo"},close:{display:"إغلاق(C)",local:"إغلاق",global:"Close"}}},xline:{...B.xline,firstPointOrOptions:"حدد نقطة أو",secondPoint:"حدد النقطة الثانية",throughPoint:"حدد نقطة يمر بها الخط",angle:"أدخل زاوية الخط الإنشائي",invalidDirection:"اتجاه XLINE غير صالح.",keywords:{...B.xline.keywords,hor:{display:"أفقي(H)",local:"أفقي",global:"Hor"},ver:{display:"رأسي(V)",local:"رأسي",global:"Ver"},ang:{display:"زاوية(A)",local:"زاوية",global:"Ang"}}},ray:{...B.ray,startPoint:"حدد نقطة البداية",throughPoint:"حدد نقطة يمر بها الشعاع"},move:{...B.move,basePointOrDisplacement:"حدد نقطة الأساس أو",secondPointOrDisplacement:"حدد النقطة الثانية أو",displacement:"حدد الإزاحة",keywords:{...B.move.keywords,displacement:{display:"إزاحة(D)",local:"إزاحة",global:"Displacement"}}},offset:{...B.offset,distance:"حدد مسافة الإزاحة",selectObject:"حدد العنصر المطلوب إزاحته أو اضغط Enter للإنهاء",sidePoint:"حدد نقطة في جهة الإزاحة",invalidDistance:"يجب أن تكون مسافة الإزاحة أكبر من 0.",invalidSelection:"لا يمكن إنشاء إزاحة للعنصر المحدد.",offsetFailed:"تعذر إنشاء منحنى إزاحة في الجهة المحددة."},mtext:{...B.mtext,point:"حدد نقطة إدراج النص متعدد الأسطر"},point:{...B.point,point:"حدد نقطة"},polygon:{...B.polygon,numberOfSides:"أدخل عدد الأضلاع",centerOrEdge:"حدد مركز المضلع أو",radiusOrType:"أدخل الخيارات",edgeStart:"حدد نقطة النهاية الأولى للضلع",edgeEnd:"حدد نقطة النهاية الثانية للضلع",invalid:{...B.polygon.invalid,sides:"عدد الأضلاع غير صالح. أدخل عددًا صحيحًا بين 3 و1024.",radius:"نصف القطر غير صالح. يجب أن يكون أكبر من 0.",edge:"الضلع غير صالح. يجب أن يكون طول الضلع أكبر من 0."},keywords:{...B.polygon.keywords,edge:{display:"حافة(E)",local:"حافة",global:"Edge"},inscribed:{display:"داخل الدائرة(I)",local:"داخل الدائرة",global:"Inscribed"},circumscribed:{display:"محيط بالدائرة(C)",local:"محيط بالدائرة",global:"Circumscribed"}}},polyline:{...B.polyline,firstPoint:"حدد النقطة الأولى",nextPoint:"حدد النقطة التالية (أو اضغط Enter للإنهاء)",nextPointWithOptions:"حدد النقطة التالية أو",nextPointWithArcOptions:"حدد النقطة التالية أو",arcAngle:"حدد زاوية القوس",arcCenter:"حدد نقطة مركز القوس",arcSecondPoint:"حدد النقطة الثانية على القوس",arcEndPoint:"حدد نقطة نهاية القوس",arcRadius:"حدد نصف قطر القوس",keywords:{...B.polyline.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"}}},rect:{...B.rect,firstPoint:"حدد نقطة الركن الأول",nextPoint:"حدد نقطة الركن المقابل",firstPointWithOptions:"حدد نقطة الركن الأول أو",otherCornerWithOptions:"حدد نقطة الركن الآخر أو",chamferFirst:"حدد مسافة الشطف الأولى",chamferSecond:"حدد مسافة الشطف الثانية",filletRadius:"حدد نصف قطر التدوير",segmentWidth:"حدد عرض خط المستطيل",elevationValue:"حدد المنسوب",thicknessValue:"حدد السماكة",rotationAngle:"حدد زاوية دوران المستطيل",dimensionLength:"حدد طول المستطيل",dimensionWidth:"حدد عرض المستطيل",areaValue:"حدد مساحة المستطيل",areaLengthOrWidth:"حدد طول المستطيل",areaSpecifyWidth:"حدد عرض المستطيل",invalidPositive:"إدخال غير صالح. أدخل قيمة أكبر من 0.",invalidRect:"تعذر إنشاء المستطيل. حدد أركانًا أو أبعادًا صالحة.",thicknessNotSupported:"سماكة المستطيل لا تُكتب حاليًا إلى بيانات العنصر، لذلك سيتم تجاهل إعداد السماكة.",keywords:{...B.rect.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"}}},rotate:{...B.rotate,basePoint:"حدد نقطة الأساس",rotationAngleOrOptions:"حدد زاوية الدوران أو",referenceAngleOrPoints:"حدد الزاوية المرجعية أو",firstReferencePoint:"حدد النقطة الأولى للزاوية المرجعية",secondReferencePoint:"حدد النقطة الثانية",newAngle:"حدد الزاوية الجديدة",invalid:{...B.rotate.invalid,referencePoints:"النقاط المرجعية غير صالحة: يجب أن تكون النقطتان مختلفتين."},keywords:{...B.rotate.keywords,copy:{display:"نسخ(C)",local:"نسخ",global:"Copy"},reference:{display:"مرجع(R)",local:"مرجع",global:"Reference"},points:{display:"نقاط(P)",local:"نقاط",global:"Points"}}},spline:{...B.spline,firstPoint:"حدد النقطة الأولى",nextPoint:"حدد النقطة التالية (أو اضغط Enter للإنهاء)",firstPointWithOptions:"حدد النقطة الأولى أو",nextPointWithFitOptions:"حدد النقطة التالية أو",nextPointWithCvOptions:"حدد نقطة التحكم التالية أو",methodPrompt:"أدخل طريقة إنشاء Spline",knotsPrompt:"أدخل طريقة توزيع العقد",degreePrompt:"حدد درجة منحنى Spline",keywords:{...B.spline.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"}}},zoom:{...B.zoom,mainPrompt:"حدد ركن نافذة التكبير أو",firstCorner:"حدد الركن الأول",secondCorner:"حدد الركن المقابل",centerPoint:"حدد نقطة المركز",heightOrScale:"أدخل الارتفاع أو معامل المقياس (nX أو nXP)",scaleFactor:"أدخل معامل المقياس (nX أو nXP)",keywords:{...B.zoom.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"}}},hideobjects:{...B.hideobjects,hidden:"تم إخفاء العناصر",restored:"تمت استعادة العناصر",nothingToRestore:"لا توجد عناصر مخفية لاستعادتها"},entout:{...B.entout,longSidePrompt:"أدخل حجم الضلع الأطول للمعاينة بالبكسل",exported:"تم تصدير معاينات العناصر",skipped:"تم تخطي بعض العناصر",failed:{...B.entout.failed,"no-preview-root":"تعذر إنشاء هندسة المعاينة للعناصر المحددة","no-bounds":"تعذر حساب حدود المعاينة للعناصر المحددة","capture-failed":"تعذر عرض صورة معاينة العناصر","download-failed":"تم إنشاء المعاينة ولكن فشل تنزيل ملف PNG"}},layer:{...B.layer,main:"أدخل خيارًا",listSummary:"تمت طباعة قائمة الطبقات في وحدة تحكم المتصفح",emptyInput:"لم يتم إدخال اسم طبقة.",newPrompt:"أدخل اسم الطبقة أو الطبقات الجديدة",makePrompt:"أدخل اسم الطبقة المطلوب إنشاؤها وجعلها حالية",setPrompt:"أدخل اسم الطبقة المطلوب جعلها حالية",onPrompt:"أدخل أسماء الطبقات المطلوب تشغيلها",offPrompt:"أدخل أسماء الطبقات المطلوب إيقافها",freezePrompt:"أدخل أسماء الطبقات المطلوب تجميدها",thawPrompt:"أدخل أسماء الطبقات المطلوب إلغاء تجميدها",lockPrompt:"أدخل أسماء الطبقات المطلوب قفلها",unlockPrompt:"أدخل أسماء الطبقات المطلوب إلغاء قفلها",colorLayerPrompt:"أدخل أسماء الطبقات المطلوب تغيير لونها",colorValuePrompt:"أدخل اللون (ACI من 1 إلى 255، أو RGB مثل 255,0,0، أو اسم لون CSS)",invalidColor:"قيمة اللون غير صالحة.",descriptionLayerPrompt:"أدخل اسم الطبقة المطلوب تعديل وصفها",descriptionValuePrompt:"أدخل وصف الطبقة الجديد",created:"عدد الطبقات التي تم إنشاؤها",alreadyExists:"الطبقة موجودة بالفعل",notFound:"الطبقة غير موجودة",cannotChangeCurrent:"لا يمكن إيقاف الطبقة الحالية أو تجميدها.",keywords:{...B.layer.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:{...B.layon,alreadyOn:"جميع الطبقات قيد التشغيل بالفعل.",turnedOn:"تم تشغيل الطبقات"},laycur:{...B.laycur,prompt:"حدد العناصر المطلوب نقلها إلى الطبقة الحالية",currentLayerNotFound:"الطبقة الحالية غير موجودة.",noObjects:"لم يتم تحديد عناصر صالحة.",alreadyCurrent:"العناصر المحددة موجودة بالفعل على الطبقة الحالية.",changed:"تم نقل العناصر إلى الطبقة الحالية"},layfrz:{...B.layfrz,prompt:"حدد عنصرًا على الطبقة المطلوب تجميدها أو",invalidSelection:"العنصر المحدد غير صالح.",settingsPrompt:"أدخل إعداد LAYFRZ المطلوب تغييره",viewportPrompt:"حدد سلوك التجميد داخل منفذ العرض",blockSelectionPrompt:"حدد سلوك اختيار الكتل المتداخلة",vpfreezeFallback:"العارض الحالي لا يدعم تجميد الطبقات بشكل مستقل لكل منفذ عرض؛ سيتم استخدام التجميد العادي بدلًا من ذلك.",nestedSelectionLimited:"تم حفظ إعدادات اختيار الكتل المتداخلة، لكن الاختيار الحالي ما زال يعتمد طبقة العنصر ذي المستوى الأعلى.",layerNotFound:"الطبقة غير موجودة",cannotFreezeCurrent:"لا يمكن تجميد الطبقة الحالية.",alreadyFrozen:"الطبقة مجمدة بالفعل",frozen:"تم تجميد الطبقة",restored:"تمت استعادة الطبقة",nothingToUndo:"لا توجد عملية LAYFRZ يمكن التراجع عنها.",keywords:{...B.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:{...B.layiso,prompt:"حدد عناصر على الطبقة أو الطبقات المطلوب عزلها أو",settingsPrompt:"أدخل إعداد الطبقات غير المعزولة",offModePrompt:"حدد سلوك إيقاف الطبقات غير المعزولة",noLayers:"لم يتم تحديد طبقات صالحة.",layerNotFound:"الطبقة غير موجودة",isolated:"تم عزل الطبقات",affectedLayers:"الطبقات المتأثرة",vpfreezeFallback:"العارض الحالي لا يدعم التجميد المستقل لكل منفذ عرض؛ سيتم استخدام الإيقاف بدلًا من ذلك.",lockFadeFallback:"العارض الحالي لا يدعم إظهار الطبقات بتأثير التلاشي؛ سيتم قفل الطبقات غير المعزولة دون تلاشي.",keywords:{...B.layiso.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"}}},layuniso:{...B.layuniso,noPrevious:"لا توجد حالة LAYISO سابقة لاستعادتها.",layerNotFound:"الطبقة غير موجودة",nothingRestored:"لم تتم استعادة أي تغييرات طبقات من LAYISO.",restored:"تمت استعادة الطبقات"},laythw:{...B.laythw,alreadyThawed:"جميع الطبقات غير مجمدة بالفعل.",thawed:"تم إلغاء تجميد الطبقات"},laylck:{...B.laylck,prompt:"حدد عنصرًا على الطبقة المطلوب قفلها",invalidSelection:"العنصر المحدد غير صالح.",layerNotFound:"الطبقة غير موجودة",alreadyLocked:"الطبقة مقفلة بالفعل",locked:"تم قفل الطبقة"},layulk:{...B.layulk,prompt:"حدد عنصرًا على الطبقة المطلوب إلغاء قفلها",invalidSelection:"العنصر المحدد غير صالح.",layerNotFound:"الطبقة غير موجودة",alreadyUnlocked:"الطبقة غير مقفلة بالفعل",unlocked:"تم إلغاء قفل الطبقة"},layoff:{...B.layoff,prompt:"حدد عنصرًا على الطبقة المطلوب إيقافها أو",invalidSelection:"العنصر المحدد غير صالح.",settingsPrompt:"أدخل إعداد LAYOFF المطلوب تغييره",viewportPrompt:"حدد سلوك منفذ العرض",blockSelectionPrompt:"حدد سلوك اختيار الكتل المتداخلة",vpfreezeFallback:"العارض الحالي لا يدعم إيقاف الطبقات بشكل مستقل لكل منفذ عرض؛ سيتم استخدام الإيقاف العادي بدلًا من ذلك.",nestedSelectionLimited:"تم حفظ إعدادات اختيار الكتل المتداخلة، لكن الاختيار الحالي ما زال يعتمد طبقة العنصر ذي المستوى الأعلى.",layerNotFound:"الطبقة غير موجودة",cannotTurnOffCurrent:"لا يمكن إيقاف الطبقة الحالية.",alreadyOff:"الطبقة متوقفة بالفعل",turnedOff:"تم إيقاف الطبقة",restored:"تمت استعادة الطبقة",nothingToUndo:"لا توجد عملية LAYOFF يمكن التراجع عنها.",keywords:{...B.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:{...B.layerp,restored:"تمت استعادة حالة الطبقات السابقة.",noPreviousState:"لا توجد حالة طبقات سابقة لاستعادتها."},mline:{...B.mline,startPointWithOptions:"حدد نقطة البداية أو",nextPointWithOptions:"حدد النقطة التالية أو",justificationPrompt:"أدخل نوع المحاذاة",scalePrompt:"حدد مقياس الخط المتعدد",stylePrompt:"أدخل اسم نمط الخط المتعدد أو [?] لعرض القائمة",styleNotFound:"نمط الخط المتعدد غير موجود",styleListHeader:"أنماط الخطوط المتعددة المحملة",styleListEmpty:"لا توجد أنماط خطوط متعددة محملة في الرسم الحالي.",keywords:{...B.mline.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"}}},measureAngle:{...B.measureAngle,vertex:"حدد نقطة رأس الزاوية",arm1:"حدد نقطة على الضلع الأول",arm2:"حدد نقطة على الضلع الثاني"},measureArc:{...B.measureArc,startPoint:"حدد نقطة بداية القوس",throughPoint:"حدد نقطة على القوس",endPoint:"حدد نقطة نهاية القوس",lockedEndPoint:"حدد نقطة نهاية القوس (استخدم Ctrl للتبديل بين القوس الأكبر والأصغر)",invalidPoints:"النقاط الثلاث على استقامة واحدة ولا يمكنها تعريف قوس."},measureArea:{...B.measureArea,firstPoint:"حدد النقطة الأولى",nextPoint:"حدد النقطة التالية (أو اضغط Enter للإنهاء)"},measureDistance:{...B.measureDistance,firstPoint:"حدد النقطة الأولى",secondPoint:"حدد النقطة الثانية"},measurePoint:{...B.measurePoint,point:"حدد نقطة"},measurement:{...B.measurement,import:{...B.measurement.import,chooseFile:"اختر ملف JSON جانبيًا يحتوي على القياسات"}},markup:{...B.markup,author:"حدد اسم مؤلف المراجعة (سيتم حفظه للاستخدام لاحقًا)",text:{...B.markup.text,point:"حدد موضع علامة النص",content:"أدخل نص علامة المراجعة"},line:{...B.markup.line,firstPoint:"حدد النقطة الأولى لخط المراجعة",secondPoint:"حدد النقطة الثانية لخط المراجعة"},arrow:{...B.markup.arrow,firstPoint:"حدد نقطة بداية السهم",secondPoint:"حدد رأس السهم"},cloud:{...B.markup.cloud,firstCorner:"حدد الركن الأول للسحابة",secondCorner:"حدد الركن المقابل للسحابة"},rect:{...B.markup.rect,firstCorner:"حدد الركن الأول للمستطيل",secondCorner:"حدد الركن المقابل للمستطيل"},circle:{...B.markup.circle,center:"حدد مركز الدائرة",radius:"حدد نصف قطر الدائرة"},shape:{...B.markup.shape,calloutOn:"[وسيلة الشرح مفعلة]",calloutOff:"[وسيلة الشرح معطلة]",calloutAnchor:"حدد موضع نص وسيلة الشرح",keywords:{...B.markup.shape.keywords,callout:{display:"تعليق توضيحي(C)",local:"تعليق توضيحي",global:"Callout"},noCallout:{display:"بدون تعليق توضيحي(N)",local:"بدون تعليق توضيحي",global:"NoCallout"}}},highlight:{...B.markup.highlight,firstCorner:"حدد الركن الأول لمنطقة التمييز",secondCorner:"حدد الركن المقابل لمنطقة التمييز"},callout:{...B.markup.callout,tip:"حدد رأس خط التوجيه، أو حدد إطار سحابة/مستطيل/دائرة بدون تعليق توضيحي",anchor:"حدد موضع نص وسيلة الشرح",content:"أدخل نص وسيلة الشرح"},stamp:{...B.markup.stamp,kind:"أدخل معرّف الختم [approved/rejected/revised/for-review/custom]",imageUrl:"أدخل رابط صورة الختم المخصص (اختياري)",caption:"أدخل تسمية الختم (اختياري)",point:"حدد نقطة إدراج الختم"},import:{...B.markup.import,chooseFile:"اختر ملف JSON جانبيًا يحتوي على علامات المراجعة"}},pngout:{...B.pngout,boundsFirstCorner:"حدد الركن الأول لحدود الصورة",boundsSecondCorner:"حدد الركن المقابل",longSidePrompt:"أدخل حجم الضلع الأطول بالبكسل"},imageattach:{...B.imageattach,insertionPoint:"حدد نقطة الإدراج:",scale:"حدد معامل المقياس:",rotation:"حدد زاوية الدوران:",invalidScale:"يجب أن يكون معامل المقياس أكبر من 0.",decodeFailed:"فشلت قراءة ملف الصورة المحدد."},insert:{...B.insert,blockName:"أدخل اسم الكتلة:",insertionPoint:"حدد نقطة الإدراج:",scale:"حدد معامل المقياس:",rotation:"حدد زاوية الدوران:",invalidScale:"يجب أن يكون معامل المقياس أكبر من 0.",invalidBlockName:"اسم الكتلة غير صالح.",blockNotFound:"الكتلة غير موجودة",xrefNotAllowed:"لا يمكن إدراج مرجع خارجي باستخدام -INSERT."},xattach:{...B.xattach,insertionPoint:"حدد نقطة الإدراج:",scale:"حدد معامل المقياس:",rotation:"حدد زاوية الدوران:",invalidScale:"يجب أن يكون معامل المقياس أكبر من 0.",unsupportedFile:"اختر ملف DWG أو DXF.",loading:"جارٍ تحميل المرجع الخارجي...",loadFailed:"فشلت قراءة ملف الرسم المحدد."},revcloud:{...B.revcloud,firstCornerOrOptions:"حدد نقطة الركن الأول أو",firstCorner:"حدد نقطة الركن الأول",oppositeCorner:"حدد الركن المقابل",startPoint:"حدد نقطة البداية",nextPoint:"حدد النقطة التالية",nextPointOrUndo:"حدد النقطة التالية أو",firstPoint:"حدد النقطة الأولى",guideCursor:"حرّك المؤشر على مسار السحابة (اضغط Enter للإنهاء)",arcLength:"حدد طول القوس",selectObject:"حدد عنصرًا",style:"أدخل نمط أقواس سحابة المراجعة",reverseDirection:"اعكس الاتجاه",invalidArcLength:"يجب أن يكون طول القوس أكبر من 0.",invalidObject:"لا يمكن تحويل العنصر المحدد إلى سحابة مراجعة.",keywords:{...B.revcloud.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:{...B.sketch,specifySketch:"حدد الرسم الحر أو",sketching:"حرّك المؤشر للرسم (انقر أو اضغط Enter للإيقاف)",type:"أدخل نوع الرسم الحر",increment:"حدد مقدار زيادة الرسم",tolerance:"حدد سماحية منحنى Spline",firstPoint:"حدد النقطة الأولى",nextPoint:"حدد نقطة النهاية",keywords:{...B.sketch.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"}}},sysvar:{...B.sysvar,prompt:"أدخل القيمة الجديدة"},chtml:{...B.chtml,exportInvisibleLayers:"تصدير الطبقات غير المرئية",exportLayouts:"تصدير المخططات",initialView:"العرض الأولي عند فتح HTML",viewerMode:"وضع العارض دون اتصال",keywords:{...B.chtml.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"}}}},Sy={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:"جارٍ تحليل سجلات الكتل ...",header:"جارٍ تحليل رأس الملف ...",block:"جارٍ تحليل الكتل ...",entity:"جارٍ تحليل العناصر ...",object:"جارٍ تحليل القواميس المسماة ...",rendering:"جارٍ عرض الرسم ...",end:"اكتمل!"},about:{title:"حول",close:"إغلاق",product:"عارض CAD",tagline:"عارض CAD عالي الأداء للويب لملفات DWG وDXF.",website:"الموقع الإلكتروني",docs:"التوثيق",repository:"GitHub",copyright:"© {year} mlightcad. جميع الحقوق محفوظة.",ok:"موافق"},drawStyle:{color:"اللون",lineWeight:"سُمك الخط",fontSize:"ارتفاع النص"}},Ay={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"},close:{description:"Zavře aktuální 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:{}},Cy={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 vodítka, nebo obrys obláčku/obdélníku/kružnice bez odkazu",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"}}}},Py={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"}},_y={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"}},Ly={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"},close:{description:"Geçerli çizimi kapatı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:{}},Ey={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 veya çağrısı olmayan bulut/dikdörtgen/daire dış çerçevesini belirtin",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"}}}},Ty={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"}},Iy={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:"创建新图纸"},close:{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:{}},My={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"}}}},Dy={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:"字号"}};h.mergeLocaleMessage("en",{command:P,jig:B,main:_y}),h.mergeLocaleMessage("zh",{command:Iy,jig:My,main:Dy}),h.mergeLocaleMessage("tr",{command:Ly,jig:Ey,main:Ty}),h.mergeLocaleMessage("cs",{command:Ay,jig:Cy,main:Py}),h.mergeLocaleMessage("ar",{command:ky,jig:xy,main:Sy});const Kr=(s,e)=>{const t=`command.${s}.${e}`;return h.t(t)},Oy=s=>Kr(he.SYSTEMT_COMMAND_GROUP_NAME,s),Ny=s=>Kr(he.DEFAUT_COMMAND_GROUP_NAME,s);class Ur{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 cc{start(){return new Promise(e=>{this.resolve=e,this.onStart()})}finish(e){this.cleanup(),this.resolve(e)}}class By extends cc{constructor(e,t,i=!0){super(),this.cli=e,this.options=t,this.allowTyping=i,this.handler=new Ur(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 Fy extends cc{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 Ur(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 dc{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),h.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 By(this,e,t);this.activeSession=i;try{return await i.start()}finally{this.activeSession=void 0}}async getPromptInput(e,t,i){const n=new Fy(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 h.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,pe.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=h.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 jy{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 Hr{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 zy extends Hr{}class Ry extends Hr{}class uc extends Hr{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 Vy=/^-?(?:\d+\.?\d*|\.\d+)$/;function Gy(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 Ii{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(),u=r.slice(a+1).trim(),p=Number(c),y=Number(u);if(Number.isNaN(p)||Number.isNaN(y))return null;const g=y*Math.PI/180,f=p*Math.cos(g),v=p*Math.sin(g);return n?o?this.parse(String(o.x+f),String(o.y+v)):null:this.parse(String(f),String(v))}const l=Gy(r);if(l){const c=Number(l.x),u=Number(l.y);return Number.isNaN(c)||Number.isNaN(u)?null:n?o?this.parse(String(o.x+c),String(o.y+u)):null:this.parse(l.x,l.y)}if(Vy.test(r)){const c=Number(r),u=t==null?void 0:t.cursorPoint;if(!o||!u||Number.isNaN(c))return null;const p=u.x-o.x,y=u.y-o.y,f=Math.hypot(p,y)>1e-10?Math.atan2(y,p):0;return this.parse(String(o.x+c*Math.cos(f)),String(o.y+c*Math.sin(f)))}return null}}class Xn{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 hc{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 Ky{constructor(e){this.parent=e.parent,this.twoInputs=e.twoInputs??!0,this.boundOnInput=()=>this.handleInput(),this.boundOnKeyDown=t=>this.handleKeyDown(t),this.xInput=new hc(this.parent),this.xInput.addEventListener("input",this.boundOnInput),this.xInput.addEventListener("keydown",this.boundOnKeyDown),this.twoInputs&&(this.yInput=new hc(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 on=class on{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(on.stylesInjected)return;on.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))}};on.stylesInjected=!1;let Mi=on;class pc{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=(v,w,x)=>{const S=x.x-w.x,A=x.y-w.y,C=Math.sqrt(S*S+A*A),L=Math.atan2(A,S)*(180/Math.PI);v.style.width=`${C}px`,v.style.transformOrigin="0 0",v.style.transform=`translate(${w.x}px, ${w.y}px) rotate(${L}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,u=r/a,p={x:t.x+c*l,y:t.y+u*l},y={x:i.x+c*l,y:i.y+u*l};if(n(this.perpLineAtBase,t,p),n(this.perpLineAtCursor,i,y),n(this.connectorLine,p,y),this.labelEl){const v=(p.x+y.x)/2,w=(p.y+y.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=`${v-20}px`,this.labelEl.style.top=`${w}px`,this.labelEl.style.display=""}if(this.xAxisLine){const v=(this.options.baseAngle??0)*Math.PI/180,w={x:this.basePoint.x+Math.cos(v),y:this.basePoint.y+Math.sin(v),z:0},x=this.toContainerPoint(w),S=Math.atan2(x.y-t.y,x.x-t.x),A={x:t.x+a*Math.cos(S),y:t.y+a*Math.sin(S)};n(this.xAxisLine,t,A)}if(this.angleSvg&&this.anglePath&&this.angleLabelEl){const v=a,w=t.x,x=t.y,S=(this.options.baseAngle??0)*Math.PI/180,A={x:this.basePoint.x+Math.cos(S),y:this.basePoint.y+Math.sin(S),z:0},C=this.toContainerPoint(A),L=Math.atan2(C.y-t.y,C.x-t.x);let N=Math.atan2(i.y-t.y,i.x-t.x)-L;for(;N<=-Math.PI;)N+=Math.PI*2;for(;N>Math.PI;)N-=Math.PI*2;const F=L+N/2,M=w-v,V=x-v,U=v*2;this.angleSvg.style.left=`${M}px`,this.angleSvg.style.top=`${V}px`,this.angleSvg.setAttribute("width",`${U}`),this.angleSvg.setAttribute("height",`${U}`),this.angleSvg.setAttribute("viewBox",`0 0 ${U} ${U}`);const Z=v,J=v,X=Z+v*Math.cos(L),te=J+v*Math.sin(L),oe=Z+v*Math.cos(L+N),ae=J+v*Math.sin(L+N),Bt=Math.abs(N)>Math.PI?"1":"0",na=N>=0?"1":"0",fv=`M ${X} ${te} A ${v} ${v} 0 ${Bt} ${na} ${oe} ${ae}`;this.anglePath.setAttribute("d",fv);const vp=Math.abs(N),kp=(f=k.instance.curDocument)==null?void 0:f.database,bv=kp?kp.formatter.formatAngle(vp,{showUnits:!0,applyAngbaseAngdir:!1}):`${(vp*180/Math.PI).toFixed(1)}°`,wv=w+v*Math.cos(F),vv=x+v*Math.sin(F);this.angleLabelEl.textContent=bv;const kv=40;this.angleLabelEl.style.left=`${wv-kv/2}px`,this.angleLabelEl.style.top=`${vv-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 an=class an extends Mi{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 zr(e)),t.basePoint&&(this.rubberBand=new pc(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 Ky({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(an.inputStylesInjected)return;an.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 pc(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(wt.displayCenterMarks(this.view.osnapResolver.acquiredCenterMarks,this.lastOsnapPoint)),this.lastOsnapPoint&&(i.x=this.lastOsnapPoint.x,i.y=this.lastOsnapPoint.y,this.osnapMarkerManager.showMarker(this.lastOsnapPoint,wt.osnapModeToMarkerType(this.lastOsnapPoint.type)))),this.orthoReferencePoint){const n=rc(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"}};an.inputStylesInjected=!1;let Wr=an;class Di extends Error{constructor(e){super("keyword"),this.keyword=e}}class Oi extends Error{constructor(){super("none")}}const ln=class ln{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 dc(this.view.container);this._commandLine=i,i.visible=pe.instance.isShowCommandLine,pe.instance.events.modified.addEventListener(()=>{i.visible=pe.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(ln.stylesInjected)return;ln.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 re(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 Xn?"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 Ii||i===2?this.resolvePointInputContext(n):void 0;return t.parseCommandLine(r,o)}isPromptKeyword(e){return e instanceof Di}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 Zn(b.OK,t),t=>new Zn(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 zy(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 jy(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),u=e.baseAngle*Math.PI/180;let p=c-u;for(;p<=-Math.PI;)p+=Math.PI*2;for(;p>Math.PI;)p-=Math.PI*2;const y=p*180/Math.PI;return{value:y,raw:{x:this.formatNumber(y,"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 Ry(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 uc(e),e);return t!=null?new Yn(b.OK,t):this.executePrompt(()=>this.getNumberTyped(e,new uc(e)),i=>new Yn(b.OK,i),i=>new Yn(i))}async getString(e){const t=this.tryGetScriptedValue(new Xn(e),e);return t!=null?new ze(b.OK,t):this.executePrompt(async()=>{const i=()=>({value:"",raw:{x:""}}),n=new Xn(e);return await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:n,getDynamicValue:i})},i=>new ze(b.OK,i),i=>new ze(i))}async getKeywords(e){return this.executePrompt(async()=>{const t=this.tryGetScriptedValue(new Ur(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 Oi:new Error("cancelled"));return}i(o)},o=>{this._activeRejector===r&&(this._activeRejector=null),n(o)})})},t=>new ze(b.OK,t),t=>new ze(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 Mi(this.view,{parent:this.view.canvas,message:e.message}),o=new Set;let a=null,l=null,c=null,u=null;const p=L=>{if(!a||!c||!l)return;const _=this.view.screenToWorld(this.view.viewportToCanvas({x:L.clientX,y:L.clientY})),N=this.view.viewportToCanvas({x:L.clientX,y:L.clientY}),F=this.view.worldToScreen(a),M=this.view.worldToScreen(_),V=Math.min(F.x,M.x),U=Math.min(F.y,M.y),Z=Math.abs(F.x-M.x),J=Math.abs(F.y-M.y),X=this.view.getSelectionMode(l,N),te=this.view.getSelectionActionFromEvent(L,"add"),oe=this.view.getSelectionPreviewStyle(X,te);Object.assign(c.style,{left:`${V}px`,top:`${U}px`,width:`${Z}px`,height:`${J}px`,borderStyle:oe.borderStyle,background:oe.background}),c.style.setProperty("--line-color",oe.lineColor)},y=()=>{u&&p(u)};let g=!1;const f=L=>{v(),i(L??new Error("cancelled"))},v=()=>{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",w),this.view.canvas.removeEventListener("mousedown",S),this.view.canvas.removeEventListener("mousemove",A),this.view.canvas.removeEventListener("mouseup",C),this.view.canvas.removeEventListener("contextmenu",x),this.view.events.viewChanged.removeEventListener(y),this.view.events.viewResize.removeEventListener(y))};this._activeRejector=f,n==null||n.promise.then(L=>{if(!g){if(!L){f();return}f(new Di(L))}});const w=L=>{if(L.key==="Escape"){f();return}L.key==="Enter"&&(v(),t([...o]))},x=L=>{this.shouldUseRightClickEnter()&&L.preventDefault()},S=L=>{if(L.button===2){this.shouldUseRightClickEnter()&&(L.preventDefault(),v(),t([...o]));return}L.button===0&&(l=this.view.viewportToCanvas({x:L.clientX,y:L.clientY}),a=this.view.screenToWorld(l),c=document.createElement("div"),c.className="ml-jig-preview-rect",this.view.container.appendChild(c))},A=L=>{L.buttons===1&&(!a||!c||!l||(u=L,p(L)))},C=L=>{if(L.button!==0||!a||!l)return;const _=this.view.screenToWorld(this.view.viewportToCanvas({x:L.clientX,y:L.clientY})),N=this.view.viewportToCanvas({x:L.clientX,y:L.clientY});c==null||c.remove(),c=null,u=null;const F=this.view.getSelectionActionFromEvent(L,"add");if(this.view.isSelectionClick(l,N)){const M=this.view.pick(_);M.length>0?this.view.applySelection([M[0].id],F):F==="replace"&&this.view.selectionSet.clear()}else{const M=new d.AcGeBox2d().expandByPoint(a).expandByPoint(_),V=this.view.getSelectionMode(l,N);this.view.selectByBoxWithMode(M,V,F)}o.clear();for(const M of this.view.selectionSet.ids)o.add(M);e.singleOnly&&F!=="remove"&&o.size>0&&(v(),t([...o])),a=null,l=null};document.addEventListener("keydown",w),this.view.canvas.addEventListener("mousedown",S),this.view.canvas.addEventListener("mousemove",A),this.view.canvas.addEventListener("mouseup",C),this.view.canvas.addEventListener("contextmenu",x),this.view.events.viewChanged.addEventListener(y),this.view.events.viewResize.addEventListener(y)}),t=>new Ti(b.OK,new Kn(t)),t=>new Ti(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 Mi(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",y),this.view.canvas.removeEventListener("mousedown",u),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 Di(f))}});const u=f=>{if(f.button===2){this.shouldUseRightClickEnter()&&e.allowNone&&(f.preventDefault(),c(),i(null));return}},p=f=>{if(f.button!==0)return;const v=this.view.screenToWorld(this.view.viewportToCanvas({x:f.clientX,y:f.clientY})),w=this.view.pick(v,void 0,!0);if(w.length==0){this._commandLine.showMessage(e.rejectMessage,"warning");return}const x=this.getEntityById(w[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:v.x,y:v.y,z:0},c(),i(w[0].id)},y=f=>{if(f.key==="Escape"){l();return}f.key==="Enter"&&e.allowNone&&(c(),i(null))},g=f=>{this.shouldUseRightClickEnter()&&f.preventDefault()};document.addEventListener("keydown",y),this.view.canvas.addEventListener("mousedown",u),this.view.canvas.addEventListener("click",p),this.view.canvas.addEventListener("contextmenu",g)}),i=>new $n(b.OK,i||void 0,t),i=>new $n(i),{none:!1})}async getBox(e){return this.executePrompt(async()=>{const t=e.firstCornerMessage||h.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 Hn(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 v=this.view.worldToScreen(f),w=Math.min(v.x,o.x),x=Math.min(v.y,o.y),S=Math.abs(v.x-o.x),A=Math.abs(v.y-o.y);Object.assign(a.style,{left:`${w}px`,top:`${x}px`,width:`${S}px`,height:`${A}px`})},u=e.secondCornerMessage||h.t("main.inputManager.secondCorner"),p=new I(u);this.copyKeywords(e,p),p.useDashedLine=e.useDashedLine,p.useBasePoint=e.useBasePoint,p.disableOSnap=e.disableOSnap;const y=await this.getPointInternal(p,l,c),g=new d.AcGeBox2d().expandByPoint(r).expandByPoint(y);return new Hn(b.OK,g)},t=>t,t=>new Hn(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 Ii(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 Oi;const r=new Ii(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 Di(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 Oi;if(e instanceof Xn){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 Ii?2:1,t??new Ye(""));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 Oi}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 L;this.active=!0,this.entitySelectionActive=!1;let n=!1;const r=_=>{const N=e.handler.parse(_.x,_.y);return{isValid:N!=null,value:N??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,u="allowNone"in e.promptOptions?e.promptOptions.allowNone:!1,p=this.resolvePromptDefaultValue(e.promptOptions),y=new Wr(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:u,useDefaultValue:p.useDefaultValue,defaultValue:p.defaultValue,validate:r,getDynamicValue:e.getDynamicValue,drawPreview:_=>{var N;if(o.jig){const F=e.getDynamicValue(_);o.jig.update(F.value),o.jig.render()}(N=e.drawPreview)==null||N.call(e,_)},onCommit:(_,N)=>{let F=!1;return(!e.onCommit||e.onCommit(_,N))&&(f(_),F=!0),F&&y.lastPoint&&(this.lastPoint={x:y.lastPoint.x,y:y.lastPoint.y}),F},onCancel:()=>v(),onNone:()=>w()});(L=e.onFloatingInputCreated)==null||L.call(e,y);const g=()=>{var _,N;n||(n=!0,this.active=!1,this.entitySelectionActive=!1,this._activeRejector===v&&(this._activeRejector=null),(_=e.cleanup)==null||_.call(e),(N=o.jig)==null||N.end(),document.removeEventListener("keydown",S),document.removeEventListener("keydown",A),document.removeEventListener("keyup",A),this.view.canvas.removeEventListener("contextmenu",C),y.dispose(),a.cancel(),this._commandLine.clear())},f=_=>{g(),t(_)},v=_=>{g(),i(_??new Error("cancelled"))};this._activeRejector=v;const w=()=>{v(new Oi)},x=_=>{v(new Di(_))},S=_=>{_.key==="Escape"&&v()},A=_=>{const N=this.handleCtrlToggleKey(_),F=this.updateModifierStateFromEvent(_);(N||F)&&y.requestPreviewRefresh()},C=_=>{this.shouldUseRightClickEnter()&&(_.preventDefault(),w())};document.addEventListener("keydown",S),document.addEventListener("keydown",A),document.addEventListener("keyup",A),this.view.canvas.addEventListener("contextmenu",C),y.showAt(this.view.canvasToViewport(this.view.curMousePos)),a.promise.then(_=>{if(!n)switch(_.kind){case"value":if(e.handler instanceof Ii){const N=_.value;N&&Number.isFinite(N.x)&&Number.isFinite(N.y)&&(this.lastPoint={x:N.x,y:N.y})}f(_.value);break;case"keyword":x(_.keyword);break;case"none":u?w():v();break}})})}};ln.stylesInjected=!1;let qn=ln;class mc{constructor(e){this.events={sysVarChanged:new d.AcCmEventManager,commandWillStart:new d.AcCmEventManager,commandEnded:new d.AcCmEventManager},this._view=e,this._cursorManager=new Xl(e),this._inputManager=new qn(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 Ti(b.OK,new Kn(i))}catch{return new Ti(b.Error)}}}class $r{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=Jn(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 Jn(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 yc extends G{constructor(e,t){super(e),this._transientsPublished=!1,this._view=e,this.batchPreview=new $r(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 Zt extends G{constructor(e,t,i=1){super(e),this._transientsPublished=!1,this._lastTransforms=[],this._view=e,this.copyCount=i,this.batchPreview=new $r(e,t.map(n=>n.objectId),i),this.previewEntries=this.batchPreview.useBatchPreview?[]:Zt.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 Xe{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 Uy{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 gc{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 Yr(s,e="replace"){return s.shiftKey?"remove":s.ctrlKey||s.metaKey?"add":e}function fc(s){return Yr(s,"add")}var fe=(s=>(s[s.SELECTION=0]="SELECTION",s[s.PAN=1]="PAN",s))(fe||{});class bc{constructor(e,t){this._entitySelectionEnabled=!0,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 Kn,this._editor=new mc(this),this._osnapResolver=new wt(this),this._canvas.addEventListener("mousemove",a=>this.onMouseMove(a)),this._canvas.addEventListener("mousedown",a=>{a.button===1&&this._editor.setCursor(Ie.Grab)}),this._canvas.addEventListener("mouseup",a=>{a.button===1&&this._editor.restoreCursor()});const n=sa.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 gc(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 Yr(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(this.entitySelectionEnabled){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=>{Mn(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 entitySelectionEnabled(){return this._entitySelectionEnabled}set entitySelectionEnabled(e){this._entitySelectionEnabled!==e&&(this._entitySelectionEnabled=e,e||(this.clearHover(),this.selectionSet.clear()))}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.entitySelectionEnabled&&this.mode==0&&(this._editor.isActive||this._hoverController.handleMouseMove(t.x,t.y))}}function Xt(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 Zr=new Set;function wc(s,e="drawing"){const t=s==null?void 0:s.trim();return t&&(t.split(/[\\/]/).pop()??t).replace(/\.[^.]+$/,"").trim()||e}function Xr(s,e,t="drawing"){const i=wc(s,t),n=e.startsWith(".")?e:`.${e}`;let r=0,o=`${i}${n}`;for(;Zr.has(o);)r+=1,o=`${i}-${r+1}${n}`;return Zr.add(o),o}function Hy(){Zr.clear()}const Wy=64,He=class He{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=Wy){He.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;He._cacheDocId!==a&&(He._cache.clear(),He._cacheDocId=a);const l=r.tables.blockTable.getAt(i);if(!l||l.isXref)return;const c=`${a}\0${l.objectId}\0${t}`,u=He._cache.get(c);if(u)return u;const p=this.fromStoredIcon(l);if(p)return He._cache.set(c,p),p;const y=this.fromGeometry(l,o,t);return y&&He._cache.set(c,y),y}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()}}};He._cache=new Map,He._docListenerBound=!1;let qr=He;class vc{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 kc extends R{async execute(e){await this.withBusyIndicator(()=>{new vc().convert()},h.t("main.message.exportingDxf"))}}class xc{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 u=i.width/Math.max(i.height,1),p=e?this.getBoundsAspect(e):u;let y=Math.max(1,Math.round(i.width)),g=Math.max(1,Math.round(i.height));if(t&&t>0){const Z=this.resolveOutputSize(t,p);y=Z.width,g=Z.height}const f=e?{width:y,height:g}:this.resolveRenderSizeForCenterCrop(y,g,u),v=f.width,w=f.height,x=!e&&(v!==y||w!==g),S=c.zoom,A=c.position.clone(),C=c.left,L=c.right,_=c.top,N=c.bottom,F=a.getScissorTest(),M=a.getPixelRatio(),V=a.getRenderTarget();let U;try{e&&r.applyExportCamera(e,v,w),a.setPixelRatio(1),o.updateLineResolution(v,w),U=new T.WebGLRenderTarget(v,w,{minFilter:T.LinearFilter,magFilter:T.LinearFilter,format:T.RGBAFormat,type:T.UnsignedByteType}),a.setRenderTarget(U),a.setViewport(0,0,v,w),a.setScissorTest(!1),r.renderObject(l);const Z=new Uint8Array(v*w*4);a.readRenderTargetPixels(U,0,0,v,w,Z);const J=this.flipPixelsVertically(Z,v,w),X=x?this.cropPixelsCentered(J,v,w,y,g):J,te=this.createCanvasFromPixels(X,y,g);this.createFileAndDownloadIt(te)}finally{a.setRenderTarget(V),U==null||U.dispose(),c.zoom=S,c.position.copy(A),c.left=C,c.right=L,c.top=_,c.bottom=N,c.updateProjectionMatrix(),a.setPixelRatio(M),o.setSize(i.width,i.height),a.setScissorTest(F),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 u=((c+a)*t+o)*4,p=u+n*4,y=c*n*4;l.set(e.subarray(u,p),y)}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=Xr(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 Sc=1024;class Ac extends R{async execute(e){const t=new xc,i=k.instance.curView;this.syncActiveLayoutViewSize(i);const n=new Un(h.t("jig.pngout.boundsFirstCorner"),h.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 se(h.t("jig.pngout.longSidePrompt"));a.allowNone=!0,a.allowNegative=!1,a.allowZero=!1,a.defaultValue=Sc,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:Sc;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 Cc{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)),u=c.width,p=c.height,y=n.createEntityPreviewRoot(e,{scope:"all"});if(!y)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(y,{width:u,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{D.disposePreviewSubset(y)}}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=Xr(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 Pc=512;class _c extends R{constructor(){super(),this.mode=z.Read}async execute(e){const t=e.view.selectionSet;let i=t.count>0?t.ids:[];if(i.length===0){const c=new _t(h.sysCmdPrompt("entout")),u=await k.instance.editor.getSelection(c);if(u.status!==b.OK||!u.value||u.value.count===0)return;i=u.value.ids}const n=new se(h.t("jig.entout.longSidePrompt"));n.allowNone=!0,n.allowNegative=!1,n.allowZero=!1,n.defaultValue=Pc,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:Pc,a=k.instance.curView;this.syncActiveLayoutViewSize(a);const l=await this.withBusyIndicator(()=>new Cc().export(i,o),h.t("main.message.exportingEntityPreview"));if(l.ok){let c=`${l.exportedCount} ${h.t("jig.entout.exported")}`;l.skippedCount>0&&(c+=`, ${l.skippedCount} ${h.t("jig.entout.skipped")}`),this.showMessage(c,"success");return}this.showMessage(h.t(`jig.entout.failed.${l.reason}`),"error")}syncActiveLayoutViewSize(e){const t=e.activeLayoutView;t&&t.resize(e.width,e.height)}}class Lc{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:ne.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 Jr{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=Xt(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 u=this.db.openEntityForWrite(l);if(!u){o++;return}u.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 W(this.db,e,t)}runEntityEdit(e){return W(this.db,Cl,e)}}async function Ec(s){const e=await k.instance.editor.getSelection(new _t(h.sysCmdPrompt(s)));if(!(e.status!==b.OK||!e.value||e.value.count===0))return e.value.ids}async function Qn(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 Ec(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 Tc(s,e){const t=s.view.selectionSet;if(t.count>0)return t.ids;const i=await Ec(e);return i&&i.length>0?i:void 0}const $y="layerp";class Me extends R{shouldRecordUndoStack(e){return this.recordsUndoStack}onCommandWillStart(e){this.globalName.toLowerCase()!==$y&&e.doc.captureLayerPreviousState()}}class Ic extends Me{constructor(){super(),this._history=[],this.mode=z.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(h.t(`jig.laydel.keywords.${t}.display`),h.t(`jig.laydel.keywords.${t}.global`),h.t(`jig.laydel.keywords.${t}.local`))}async promptMainAction(){const e=new Ze(h.t("jig.laydel.selectPrompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(h.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 ue(h.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 ne(e.doc.database).getLayerSummaries();console.table(t),this.showMessage(h.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(h.t("jig.laydel.invalidSelection"),"warning");return}this.deleteLayerByName(e,n)}deleteLayerByName(e,t){const i=new ne(e.doc.database).deleteLayer(t);if(!i.ok)switch(i.reason){case"not_found":this.showMessage(`${h.t("jig.laydel.layerNotFound")}: ${t}`);return;case"layer_0":this.showMessage(h.t("jig.laydel.cannotDeleteZeroLayer"),"warning");return;case"current_layer":this.showMessage(h.t("jig.laydel.cannotDeleteCurrent"),"warning");return}this._history.push({layer:i.layer,entities:i.entities}),e.view.selectionSet.clear(),k.instance.regen(),this.showMessage(`${h.t("jig.laydel.deleted")}: ${i.layerName}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.showMessage(h.t("jig.laydel.nothingToUndo"),"warning");return}new ne(e.doc.database).restoreDeletedLayer(t.layer,t.entities),e.view.selectionSet.clear(),k.instance.regen(),this.showMessage(`${h.t("jig.laydel.restored")}: ${t.layer.name}`,"success")}}class Mc extends Me{constructor(){super(),this.mode=z.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(h.t("jig.laycur.currentLayerNotFound"),"warning");return}if(n.changedCount===0){this.showMessage(n.alreadyCurrent>0?h.t("jig.laycur.alreadyCurrent"):h.t("jig.laycur.noObjects"),n.alreadyCurrent>0&&n.missing===0?"info":"warning");return}e.view.selectionSet.clear(),k.instance.regen(),this.showMessage(`${h.t("jig.laycur.changed")}: ${n.changedCount} (${e.doc.database.clayer})`,"success")}async promptSelection(){var i;const e=new _t(h.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 Yy={viewportMode:"Freeze",blockSelectionMode:"None"},it=class it extends Me{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=z.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=it._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(h.t(`jig.layfrz.keywords.${t}.display`),h.t(`jig.layfrz.keywords.${t}.global`),h.t(`jig.layfrz.keywords.${t}.local`))}async promptSelection(){const e=new Ze(h.t("jig.layfrz.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(h.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 re(h.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 re(h.t("jig.layfrz.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(h.t("jig.layfrz.keywords.freeze.display"),h.t("jig.layfrz.keywords.freeze.global"),h.t("jig.layfrz.keywords.freeze.local")),i=e.keywords.add(h.t("jig.layfrz.keywords.vpfreeze.display"),h.t("jig.layfrz.keywords.vpfreeze.global"),h.t("jig.layfrz.keywords.vpfreeze.local"));e.keywords.default=it._settings.viewportMode==="Vpfreeze"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;r&&(it._settings.viewportMode=r,r==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.showMessage(h.t("jig.layfrz.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new re(h.t("jig.layfrz.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(h.t("jig.layfrz.keywords.block.display"),h.t("jig.layfrz.keywords.block.global"),h.t("jig.layfrz.keywords.block.local")),i=e.keywords.add(h.t("jig.layfrz.keywords.entity.display"),h.t("jig.layfrz.keywords.entity.global"),h.t("jig.layfrz.keywords.entity.local")),n=e.keywords.add(h.t("jig.layfrz.keywords.none.display"),h.t("jig.layfrz.keywords.none.global"),h.t("jig.layfrz.keywords.none.local"));e.keywords.default=it._settings.blockSelectionMode==="Block"?t:it._settings.blockSelectionMode==="Entity"?i:n;const r=await k.instance.editor.getKeywords(e);if(r.status!==b.OK)return;const o=r.stringResult;o&&(it._settings.blockSelectionMode=o,this.showMessage(h.t("jig.layfrz.nestedSelectionLimited")))}freezeEntityLayer(e,t){const n=new ne(e.doc.database).freezeLayerByEntity(t);if(!n.ok){switch(n.reason){case"invalid_selection":this.showMessage(h.t("jig.layfrz.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${h.t("jig.layfrz.layerNotFound")}: ${n.layerName}`,"warning");return;case"cannot_change_current":this.showMessage(h.t("jig.layfrz.cannotFreezeCurrent"),"warning");return;case"already_frozen":this.showMessage(`${h.t("jig.layfrz.alreadyFrozen")}: ${n.layerName}`,"info");return}return}it._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.showMessage(h.t("jig.layfrz.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:n.layerName,wasFrozen:n.previousFrozen??!1}),e.view.selectionSet.clear(),this.showMessage(`${h.t("jig.layfrz.frozen")}: ${n.layerName}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.showMessage(h.t("jig.layfrz.nothingToUndo"),"warning");return}if(!new ne(e.doc.database).setLayerFrozenByName(t.layerName,t.wasFrozen)){this.showMessage(`${h.t("jig.layfrz.layerNotFound")}: ${t.layerName}`,"warning");return}e.view.selectionSet.clear(),this.showMessage(`${h.t("jig.layfrz.restored")}: ${t.layerName}`,"success")}};it._settings={...Yy};let es=it;const Zy={isolationMode:"Off",offMode:"Off"},Le=class Le extends Me{constructor(){super(),this._vpfreezeHintShown=!1,this._lockFadeHintShown=!1,this.mode=z.Write}async execute(e){this._vpfreezeHintShown=Le._settings.offMode!=="Vpfreeze",this._lockFadeHintShown=Le._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(h.t(`jig.layiso.keywords.${t}.display`),h.t(`jig.layiso.keywords.${t}.global`),h.t(`jig.layiso.keywords.${t}.local`))}async promptSelection(){var i;const e=new _t(h.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 re(h.t("jig.layiso.settingsPrompt"));e.allowNone=!0;const t=e.keywords.add(h.t("jig.layiso.keywords.off.display"),h.t("jig.layiso.keywords.off.global"),h.t("jig.layiso.keywords.off.local")),i=e.keywords.add(h.t("jig.layiso.keywords.lockAndFade.display"),h.t("jig.layiso.keywords.lockAndFade.global"),h.t("jig.layiso.keywords.lockAndFade.local"));e.keywords.default=Le._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(Le._settings.isolationMode=r,r==="Off"){await this.promptOffMode();return}this._lockFadeHintShown=!0,this.showMessage(h.t("jig.layiso.lockFadeFallback"))}}async promptOffMode(){const e=new re(h.t("jig.layiso.offModePrompt"));e.allowNone=!0;const t=e.keywords.add(h.t("jig.layiso.keywords.off.display"),h.t("jig.layiso.keywords.off.global"),h.t("jig.layiso.keywords.off.local")),i=e.keywords.add(h.t("jig.layiso.keywords.vpfreeze.display"),h.t("jig.layiso.keywords.vpfreeze.global"),h.t("jig.layiso.keywords.vpfreeze.local"));e.keywords.default=Le._settings.offMode==="Vpfreeze"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;r&&(Le._settings.offMode=r,r==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.showMessage(h.t("jig.layiso.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}isolateSelectedObjectLayers(e,t){const i=new ne(e.doc.database),{layerNames:n,missingLayerNames:r}=i.collectLayerNamesFromEntities(t);if(r.length>0&&this.showMessage(`${h.t("jig.layiso.layerNotFound")}: ${r.join(", ")}`,"warning"),n.length===0){this.showMessage(h.t("jig.layiso.noLayers"),"warning");return}const o=e.doc.isolateLayers(n,Le._settings.isolationMode);if(!o){this.showMessage(h.t("jig.layiso.noLayers"),"warning");return}Le._settings.isolationMode==="Off"&&Le._settings.offMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.showMessage(h.t("jig.layiso.vpfreezeFallback")),this._vpfreezeHintShown=!0),Le._settings.isolationMode==="LockAndFade"&&!this._lockFadeHintShown&&(this.showMessage(h.t("jig.layiso.lockFadeFallback")),this._lockFadeHintShown=!0),e.view.selectionSet.clear(),this.showMessage(`${h.t("jig.layiso.isolated")}: ${n.join(", ")} (${h.t("jig.layiso.affectedLayers")}: ${o.affectedLayerCount})`,"success")}};Le._settings={...Zy};let ts=Le;class Dc extends Me{constructor(){super(),this.mode=z.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.lockEntityLayer(e,t)}}async promptSelection(){const e=new Ze(h.t("jig.laylck.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(h.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 ne(e.doc.database).lockLayerByEntity(t);if(!i.ok)switch(i.reason){case"invalid_selection":this.showMessage(h.t("jig.laylck.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${h.t("jig.laylck.layerNotFound")}: ${i.layerName}`,"warning");return;case"already_locked":this.showMessage(`${h.t("jig.laylck.alreadyLocked")}: ${i.layerName}`,"info");return}e.view.selectionSet.clear(),this.showMessage(`${h.t("jig.laylck.locked")}: ${i.layerName}`,"success")}}class Oc extends Me{constructor(){super(),this.mode=z.Write}async execute(e){const t=new ne(e.doc.database).setAllLayersOn();if(e.view.selectionSet.clear(),t===0){this.showMessage(h.t("jig.layon.alreadyOn"));return}this.showMessage(`${h.t("jig.layon.turnedOn")}: ${t}`,"success")}}const Xy={viewportMode:"Off",blockSelectionMode:"None"},nt=class nt extends Me{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=z.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=nt._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(h.t(`jig.layoff.keywords.${t}.display`),h.t(`jig.layoff.keywords.${t}.global`),h.t(`jig.layoff.keywords.${t}.local`))}async promptSelection(){const e=new Ze(h.t("jig.layoff.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(h.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 re(h.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 re(h.t("jig.layoff.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(h.t("jig.layoff.keywords.off.display"),h.t("jig.layoff.keywords.off.global"),h.t("jig.layoff.keywords.off.local")),i=e.keywords.add(h.t("jig.layoff.keywords.vpfreeze.display"),h.t("jig.layoff.keywords.vpfreeze.global"),h.t("jig.layoff.keywords.vpfreeze.local"));e.keywords.default=nt._settings.viewportMode==="Vpfreeze"?i:t;const n=await k.instance.editor.getKeywords(e);if(n.status!==b.OK)return;const r=n.stringResult;r&&(nt._settings.viewportMode=r,r==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.showMessage(h.t("jig.layoff.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new re(h.t("jig.layoff.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(h.t("jig.layoff.keywords.block.display"),h.t("jig.layoff.keywords.block.global"),h.t("jig.layoff.keywords.block.local")),i=e.keywords.add(h.t("jig.layoff.keywords.entity.display"),h.t("jig.layoff.keywords.entity.global"),h.t("jig.layoff.keywords.entity.local")),n=e.keywords.add(h.t("jig.layoff.keywords.none.display"),h.t("jig.layoff.keywords.none.global"),h.t("jig.layoff.keywords.none.local"));e.keywords.default=nt._settings.blockSelectionMode==="Block"?t:nt._settings.blockSelectionMode==="Entity"?i:n;const r=await k.instance.editor.getKeywords(e);if(r.status!==b.OK)return;const o=r.stringResult;o&&(nt._settings.blockSelectionMode=o,this.showMessage(h.t("jig.layoff.nestedSelectionLimited")))}turnOffEntityLayer(e,t){const n=new ne(e.doc.database).turnOffLayerByEntity(t);if(!n.ok){switch(n.reason){case"invalid_selection":this.showMessage(h.t("jig.layoff.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${h.t("jig.layoff.layerNotFound")}: ${n.layerName}`,"warning");return;case"cannot_change_current":this.showMessage(h.t("jig.layoff.cannotTurnOffCurrent"),"warning");return;case"already_off":this.showMessage(`${h.t("jig.layoff.alreadyOff")}: ${n.layerName}`,"info");return}return}nt._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.showMessage(h.t("jig.layoff.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:n.layerName,wasOff:n.previousOff??!1}),e.view.selectionSet.clear(),this.showMessage(`${h.t("jig.layoff.turnedOff")}: ${n.layerName}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.showMessage(h.t("jig.layoff.nothingToUndo"),"warning");return}if(!new ne(e.doc.database).setLayerOffByName(t.layerName,t.wasOff)){this.showMessage(`${h.t("jig.layoff.layerNotFound")}: ${t.layerName}`,"warning");return}e.view.selectionSet.clear(),this.showMessage(`${h.t("jig.layoff.restored")}: ${t.layerName}`,"success")}};nt._settings={...Xy};let is=nt;class Nc extends Me{constructor(){super(),this.mode=z.Write}async execute(e){e.doc.restoreLayerPreviousState()?this.showMessage(h.t("jig.layerp.restored"),"success"):this.showMessage(h.t("jig.layerp.noPreviousState")),e.view.selectionSet.clear()}}class Bc extends Me{constructor(){super(),this.mode=z.Write}async execute(e){const t=new ne(e.doc.database).thawAllLayers();if(e.view.selectionSet.clear(),t===0){this.showMessage(h.t("jig.laythw.alreadyThawed"));return}this.showMessage(`${h.t("jig.laythw.thawed")}: ${t}`,"success")}}class Fc extends Me{constructor(){super(),this.mode=z.Write}async execute(e){const t=e.doc.unisolateLayers();if(t===void 0){this.showMessage(h.t("jig.layuniso.noPrevious"),"warning");return}if(e.view.selectionSet.clear(),t===0){this.showMessage(h.t("jig.layuniso.nothingRestored"));return}this.showMessage(`${h.t("jig.layuniso.restored")}: ${t}`,"success")}}class jc extends Me{constructor(){super(),this.mode=z.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.unlockEntityLayer(e,t)}}async promptSelection(){const e=new Ze(h.t("jig.layulk.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(h.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 ne(e.doc.database).unlockLayerByEntity(t);if(!i.ok)switch(i.reason){case"invalid_selection":this.showMessage(h.t("jig.layulk.invalidSelection"),"warning");return;case"layer_not_found":this.showMessage(`${h.t("jig.layulk.layerNotFound")}: ${i.layerName}`,"warning");return;case"already_unlocked":this.showMessage(`${h.t("jig.layulk.alreadyUnlocked")}: ${i.layerName}`,"info");return}e.view.selectionSet.clear(),this.showMessage(`${h.t("jig.layulk.unlocked")}: ${i.layerName}`,"success")}}class zc extends R{async execute(e){ie.emit("close-layer-manager",{})}}class Rc extends Me{constructor(){super(),this.mode=z.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 ne(e.doc.database)}async promptMainKeyword(){const e=new re(h.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(h.t(`jig.layer.keywords.${t}.display`),h.t(`jig.layer.keywords.${t}.global`),h.t(`jig.layer.keywords.${t}.local`))}listLayers(e){const t=this.layerService(e).getLayerSummaries();console.table(t),this.showMessage(`${h.t("jig.layer.listSummary")} (${t.length})`,"info")}async promptLayerNames(e,t){const i=new ue(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(h.t("jig.layer.emptyInput"),"warning");return}return o}async promptSingleLayerName(e){const t=new ue(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(h.t("jig.layer.newPrompt"),e);if(!t)return;const{created:i,existed:n}=this.layerService(e).createLayers(t);i>0&&this.showMessage(`${h.t("jig.layer.created")}: ${i}`,"success"),n.length>0&&this.showMessage(`${h.t("jig.layer.alreadyExists")}: ${n.join(", ")}`,"warning")}async runSet(e){const t=await this.promptSingleLayerName(h.t("jig.layer.setPrompt"));t&&(this.layerService(e).setCurrentLayer(t)||this.showMessage(`${h.t("jig.layer.notFound")}: ${t}`,"warning"))}async runMake(e){const t=await this.promptSingleLayerName(h.t("jig.layer.makePrompt"));t&&this.layerService(e).makeLayer(t)}async runOnOff(e,t){const i=await this.promptLayerNames(t?h.t("jig.layer.offPrompt"):h.t("jig.layer.onPrompt"),e);if(!i)return;const n=this.layerService(e),{missing:r}=n.resolveLayers(i);r.length>0&&this.showMessage(`${h.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const{skippedCurrent:o}=n.setLayersVisibility(i,t);o.length>0&&this.showMessage(h.t("jig.layer.cannotChangeCurrent"),"warning")}async runFreeze(e,t){const i=await this.promptLayerNames(t?h.t("jig.layer.freezePrompt"):h.t("jig.layer.thawPrompt"),e);if(!i)return;const n=this.layerService(e),{missing:r}=n.resolveLayers(i);r.length>0&&this.showMessage(`${h.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const{skippedCurrent:o}=n.setLayersFrozen(i,t);o.length>0&&this.showMessage(h.t("jig.layer.cannotChangeCurrent"),"warning")}async runLock(e,t){const i=await this.promptLayerNames(t?h.t("jig.layer.lockPrompt"):h.t("jig.layer.unlockPrompt"),e);if(!i)return;const n=this.layerService(e),{missing:r}=n.resolveLayers(i);r.length>0&&this.showMessage(`${h.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning"),n.setLayersLocked(i,t)}async runColor(e){const t=await this.promptLayerNames(h.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(`${h.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning"),n.length===0)return;const o=new ue(h.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(h.t("jig.layer.invalidColor"),"warning");return}i.setLayersColor(t,l)}async runDescription(e){const t=await this.promptSingleLayerName(h.t("jig.layer.descriptionLayerPrompt"));if(!t)return;const i=new ue(h.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(`${h.t("jig.layer.notFound")}: ${t}`,"warning"))}}const qy={x:0,y:0,z:1},Jy={x:0,y:0,z:-1};function Qr(s,e){return Math.atan2(e.y-s.y,e.x-s.x)*180/Math.PI}function Vc(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 vt(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:Vc(t,{x:s.startPoint.x,y:s.startPoint.y},e),endAngle:Vc(t,{x:s.endPoint.x,y:s.endPoint.y},e),normalSign:e}}function Gc(s){return s===1?qy:Jy}function Kc(s){return s.normal.z>=0?1:-1}function Ni(s){return new d.AcDbArc(s.center,s.radius,s.startAngle,s.endAngle,Gc(s.normalSign))}function Uc(s,e){s.center=e.center,s.radius=e.radius,s.startAngle=e.startAngle,s.endAngle=e.endAngle,s.normal=Gc(e.normalSign)}function Re(s){return{center:{x:s.x,y:s.y,z:0},radius:1e-6,startAngle:0,endAngle:Math.PI/2,normalSign:1}}function Hc(s,e,t,i=!1){return vt(d.AcGeCircArc2d.tryCreateByThreePoints(s,e,t,i))}function Wc(s,e,t,i){return vt(d.AcGeCircArc2d.tryCreateByCenterStartEnd(s,e,t,i===-1))}function ns(s,e,t,i){return vt(d.AcGeCircArc2d.tryCreateByCenterStartProjectedEnd(s,e,t,i===-1))}function Bi(s,e,t){return vt(d.AcGeCircArc2d.tryCreateByCenterStartSweep(s,e,t))}function Fi(s,e,t){return vt(d.AcGeCircArc2d.tryCreateByCenterStartChord(s,e,t))}function eo(s,e,t){return vt(d.AcGeCircArc2d.tryCreateByStartEndAngle(s,e,t))}function to(s,e,t){return vt(d.AcGeCircArc2d.tryCreateByStartEndDirection(s,e,t))}function io(s,e,t){return vt(d.AcGeCircArc2d.tryCreateByStartEndRadius(s,e,t))}class ji extends G{constructor(e,t,i){super(e),this._builder=t,this._arc=Ni(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==Kc(this._arc)){this.end(),this._arc=Ni(t);return}Uc(this._arc,t)}}}class qt extends G{constructor(e,t,i){super(e),this._builder=t,this._arc=Ni(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==Kc(this._arc)){this.end(),this._arc=Ni(t);return}Uc(this._arc,t)}}}const Qy={"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 $c extends R{constructor(){super(),this.mode=z.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(h.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=Qy[t];return i?(k.instance.editor.consumeScriptInput(),i):"default"}addKeyword(e,t){e.keywords.add(h.t(`jig.arc.keywords.${t}.display`),h.t(`jig.arc.keywords.${t}.global`),h.t(`jig.arc.keywords.${t}.local`))}appendArc(e,t){e.doc.database.tables.blockTable.modelSpace.appendEntity(Ni(t))}warnInvalidGeometry(e){this.notify(h.t(`jig.arc.invalid.${e}`),"warning")}async promptStartPoint(){const e=new I(h.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(h.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 I(h.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 I(h.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 Ce(h.t("jig.arc.includedAngle"));c.allowNegative=!0,c.allowZero=!1,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new d.AcGePoint3d(n),c.baseAngle=Qr(n,i),c.jig=new qt(e.view,g=>Bi(n,i,this.applyCtrlDirectionValue(this.degToRad(g))),Re(i));const u=await k.instance.editor.getAngle(c),p=u.status===b.OK?u.value:void 0;if(p==null)return;const y=Bi(n,i,this.applyCtrlDirectionValue(this.degToRad(p)));y?this.appendArc(e,y):this.warnInvalidGeometry("angle");return}const r=new ke(h.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 qt(e.view,c=>Fi(n,i,this.applyCtrlDirectionValue(c)),Re(i));const o=await k.instance.editor.getDistance(r),a=o.status===b.OK?o.value:void 0;if(a==null)return;const l=Fi(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 Ce(h.t("jig.arc.includedAngle"));c.allowNegative=!0,c.allowZero=!1,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new d.AcGePoint3d(i),c.baseAngle=Qr(i,n),c.jig=new qt(e.view,g=>Bi(i,n,this.applyCtrlDirectionValue(this.degToRad(g))),Re(n));const u=await k.instance.editor.getAngle(c),p=u.status===b.OK?u.value:void 0;if(p==null)return;const y=Bi(i,n,this.applyCtrlDirectionValue(this.degToRad(p)));y?this.appendArc(e,y):this.warnInvalidGeometry("angle");return}const r=new ke(h.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 qt(e.view,c=>Fi(i,n,this.applyCtrlDirectionValue(c)),Re(n));const o=await k.instance.editor.getDistance(r),a=o.status===b.OK?o.value:void 0;if(a==null)return;const l=Fi(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 Ce(h.t("jig.arc.includedAngle"));c.allowNegative=!0,c.allowZero=!1,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new d.AcGePoint3d(i),c.baseAngle=Qr(i,n),c.jig=new qt(e.view,g=>eo(i,n,this.applyCtrlDirectionValue(this.degToRad(g))),Re(i));const u=await k.instance.editor.getAngle(c),p=u.status===b.OK?u.value:void 0;if(p==null)return;const y=eo(i,n,this.applyCtrlDirectionValue(this.degToRad(p)));y?this.appendArc(e,y):this.warnInvalidGeometry("angle");return}if(t==="direction"){const c=new I(h.t("jig.arc.tangentDirection"));c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new d.AcGePoint3d(i),c.jig=new ji(e.view,f=>to(i,n,Math.atan2(f.y-i.y,f.x-i.x)),Re(i));const u=await k.instance.editor.getPoint(c),p=u.status===b.OK?u.value:void 0;if(!p)return;const y=Math.atan2(p.y-i.y,p.x-i.x),g=to(i,n,y);g?this.appendArc(e,g):this.warnInvalidGeometry("direction");return}const r=new ke(h.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 qt(e.view,c=>io(i,n,this.applyCtrlDirectionValue(c)),Re(i));const o=await k.instance.editor.getDistance(r),a=o.status===b.OK?o.value:void 0;if(a==null)return;const l=io(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(h.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 I(h.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new d.AcGePoint3d(i),n.jig=new ji(e.view,a=>ns(t,i,a,this.applyCtrlDirectionSign(1)),Re(i));const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK)return;const o=ns(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(h.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 I(h.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new d.AcGePoint3d(t),n.jig=new ji(e.view,a=>Hc(t,i,a,this.isCtrlDirectionFlipped()),Re(t));const r=await k.instance.editor.getPoint(n);if(r.status!==b.OK)return;const o=Hc(t,i,r.value,this.isCtrlDirectionFlipped());o?this.appendArc(e,o):this.warnInvalidGeometry("threePoint")}async runCenterStartFlow(e){const t=new I(h.t("jig.arc.centerPoint")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK)return;const n=i.value,r=new I(h.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 I(h.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 I(h.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 ji(e.view,o=>ns(t,i,o,this.applyCtrlDirectionSign(1)),Re(i));const r=await k.instance.editor.getPoint(n);if(r.status===b.OK){const o=ns(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 se(h.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=Bi(t,i,this.applyCtrlDirectionValue(this.degToRad(a.value)));l?this.appendArc(e,l):this.warnInvalidGeometry("angle");return}if(r.stringResult==="ChordLength"){const o=new ke(h.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=Fi(t,i,this.applyCtrlDirectionValue(a.value));l?this.appendArc(e,l):this.warnInvalidGeometry("chordLength")}}}async runStartEndFlow(e,t){const i=new I(h.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 I(h.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 ji(e.view,l=>Wc(l,t,r,this.applyCtrlDirectionSign(1)),Re(t));const a=await k.instance.editor.getPoint(o);if(a.status===b.OK){const l=Wc(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 se(h.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 u=eo(t,r,this.applyCtrlDirectionValue(this.degToRad(c.value)));u?this.appendArc(e,u):this.warnInvalidGeometry("angle");return}if(a.stringResult==="Direction"){const l=new I(h.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 u=c.value,p=Math.atan2(u.y-t.y,u.x-t.x),y=to(t,r,p);y?this.appendArc(e,y):this.warnInvalidGeometry("direction");return}if(a.stringResult==="Radius"){const l=new ke(h.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 u=io(t,r,this.applyCtrlDirectionValue(c.value));u?this.appendArc(e,u):this.warnInvalidGeometry("radius")}}}degToRad(e){return e*Math.PI/180}}function Yc(s){return{center:{x:s.x,y:s.y,z:0},radius:1e-6}}function no(s,e){s.keywords.add(h.t(`jig.circle.keywords.${e}.display`),h.t(`jig.circle.keywords.${e}.global`),h.t(`jig.circle.keywords.${e}.local`))}function eg(s,e){s.center=e.center,s.radius=e.radius}function so(s){if(s)return{center:{x:s.center.x,y:s.center.y,z:0},radius:s.radius}}function Zc(s,e){return so(d.AcGeCircArc2d.tryCreateCircle(s,e))}function Xc(s,e){return so(d.AcGeCircArc2d.tryCreateCircleByDiameter(s,e))}function qc(s,e,t){return so(d.AcGeCircArc2d.tryCreateCircleByThreePoints(s,e,t))}class ro extends G{constructor(e,t){super(e),this._circle=new d.AcDbCircle(t,0)}get entity(){return this._circle}update(e){this._circle.radius=e}}class Jc extends G{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&&eg(this._circle,t)}}class Qc extends R{constructor(){super(),this.mode=z.Write}async execute(e){let t;class i{constructor(p,y){this.cmd=p,this.machine=y}buildPrompt(){const p=new I(h.t("jig.circle.centerOrOptions"));return no(p,"threeP"),no(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 y=p.stringResult??"";return y==="3P"?(this.machine.setState(new o(this.cmd,this.machine)),"continue"):y==="2P"?(this.machine.setState(new n(this.cmd,this.machine)),"continue"):"finish"}}class n{constructor(p,y){this.cmd=p,this.machine=y}buildPrompt(){return new I(h.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,y){this.cmd=p,this.firstPoint=y}buildPrompt(){const p=new I(h.t("jig.circle.twoPointSecond"));return p.useBasePoint=!0,p.useDashedLine=!0,p.basePoint=new d.AcGePoint3d(this.firstPoint),p.jig=new Jc(e.view,y=>Xc(this.firstPoint,y),Yc(this.firstPoint)),p}async handleResult(p){return p.status===b.OK&&(t=this.cmd.createFromTwoPoints(this.firstPoint,p.value)),"finish"}}class o{constructor(p,y){this.cmd=p,this.machine=y}buildPrompt(){return new I(h.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,y,g){this.cmd=p,this.machine=y,this.firstPoint=g}buildPrompt(){const p=new I(h.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,y,g){this.cmd=p,this.firstPoint=y,this.secondPoint=g}buildPrompt(){const p=new I(h.t("jig.circle.threePointThird"));return p.useBasePoint=!0,p.useDashedLine=!0,p.basePoint=new d.AcGePoint3d(this.secondPoint),p.jig=new Jc(e.view,y=>qc(this.firstPoint,this.secondPoint,y),Yc(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 Xe;c.setState(new i(this,c)),await c.run(u=>k.instance.editor.getPoint(u)),t&&e.doc.database.tables.blockTable.modelSpace.appendEntity(new d.AcDbCircle(t.center,t.radius))}async runCenterFlow(e,t){const i=new ke(h.t("jig.circle.radiusOrDiameter"));no(i,"diameter"),i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new d.AcGePoint3d(t),i.jig=new ro(e.view,t);const n=await k.instance.editor.getDistance(i);if(n.status===b.OK)return Zc(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 ke(h.t("jig.circle.diameter"));i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new d.AcGePoint3d(t),i.jig=new ro(e.view,t);const n=await k.instance.editor.getDistance(i);if(n.status!==b.OK)return;const r=(n.value??0)/2;return Zc(t,r)}createFromTwoPoints(e,t){return Xc(e,t)}createFromThreePoints(e,t,i){return qc(e,t,i)}}class ed extends G{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 td extends R{constructor(){super(),this.mode=z.Review}async execute(e){const t=new I(h.t("jig.dimlinear.xLine1Point")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK)return;const n=i.value,r=new I(h.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(h.t("jig.dimlinear.dimLinePoint"));l.jig=new ed(e.view,e.doc.database,n,a);const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK)return;const u=c.value,p=e.doc.database,y=new d.AcDbAlignedDimension(n,a,u),g=this.getAvaiableDimBlockName(p);p.tables.blockTable.add(y.createDimBlock(g)),y.dimBlockId=g,p.tables.blockTable.modelSpace.appendEntity(y)}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 ss extends G{constructor(e,t){super(e),this._line=new d.AcDbLine(t,t)}get entity(){return this._line}update(e){this._line.endPoint=e}}class Lt extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=e.doc.database,i=[],n=[],r=()=>!!Lt._lastEndpoint,o=()=>Lt._lastEndpoint?new d.AcGePoint3d(Lt._lastEndpoint):void 0,a=()=>{const x=c();x&&(Lt._lastEndpoint=new d.AcGePoint3d(x))},l=x=>{i.push(new d.AcGePoint3d(x))},c=()=>i[i.length-1],u=x=>{const S=c();if(!S)return;const A=new d.AcDbLine(new d.AcGePoint3d(S),x);t.tables.blockTable.modelSpace.appendEntity(A),n.push(A),e.view.addEntity(A),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()},y=()=>{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||u(x)},g=new I(r()?h.t("jig.line.firstPointOrContinue"):h.t("jig.line.firstPoint"));r()&&g.keywords.add(h.t("jig.line.keywords.continue.display"),h.t("jig.line.keywords.continue.global"),h.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 v{buildPrompt(){const S=new I(h.t("jig.line.nextPointWithOptions"));S.keywords.add(h.t("jig.line.keywords.undo.display"),h.t("jig.line.keywords.undo.global"),h.t("jig.line.keywords.undo.local")),i.length>1&&S.keywords.add(h.t("jig.line.keywords.close.display"),h.t("jig.line.keywords.close.global"),h.t("jig.line.keywords.close.local"));const A=c();return A&&(S.useDashedLine=!0,S.useBasePoint=!0,S.basePoint=new d.AcGePoint3d(A),S.jig=new ss(e.view,A)),S.allowNone=!0,S}async handleResult(S){if(S.status===b.OK)return u(S.value),"continue";if(S.status===b.Keyword){const A=S.stringResult??"";return A==="Undo"?(p(),"continue"):A==="Close"&&i.length>1?(y(),"finish"):"continue"}return"finish"}}const w=new Xe;w.setState(new v),await w.run(x=>k.instance.editor.getPoint(x)),a()}}const oo={x:0,y:0,z:1};function rs(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function tg(s,e){return{x:(s.x+e.x)/2,y:(s.y+e.y)/2,z:0}}function id(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 ig(s){return{x:-s.y,y:s.x,z:0}}function ao(s){return s*Math.PI/180}function ng(s){return s*180/Math.PI}function sg(s){return ng(Math.atan2(s.y,s.x))}function os(s,e,t){const i=ao(s);return Math.atan2(e*Math.sin(i),t*Math.cos(i))}function rg(s,e){return id(e.x-s.x,e.y-s.y)}function as(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=og(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:ig(e),majorRadius:i,minorRadius:t,startAngle:o.startAngle,endAngle:o.endAngle}}function og(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 nd(s){return new d.AcDbEllipse(s,oo,{x:1,y:0,z:0},1e-6,1e-6,0,d.TAU)}function sd(s,e){s.center=e.center,s.normal=oo,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 ag extends G{constructor(e,t,i){super(e),this._builder=t,this._ellipse=nd(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&sd(this._ellipse,t)}}class lo extends G{constructor(e,t,i){super(e),this._builder=t,this._ellipse=nd(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&sd(this._ellipse,t)}}class rd extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=new I(h.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(h.t(`jig.ellipse.keywords.${t}.display`),h.t(`jig.ellipse.keywords.${t}.global`),h.t(`jig.ellipse.keywords.${t}.local`))}appendEllipse(e,t){const i=new d.AcDbEllipse(t.center,oo,t.majorAxis,t.majorRadius,t.minorRadius,t.startAngle,t.endAngle);e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){this.notify(h.t(`jig.ellipse.invalid.${e}`),"warning")}async runArcEntryFlow(e){const t=new I(h.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(h.t("jig.ellipse.center")),n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new I(h.t("jig.ellipse.firstAxisEndpoint"));o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new d.AcGePoint3d(r),o.jig=new ss(e.view,r);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)return;const l=rg(r,a.value);if(!l){this.warnInvalidInput("axis");return}const c=rs(r,a.value),u=await this.promptOtherAxis(e,r,l,c,t);u&&this.appendEllipse(e,u)}async runAxisEndFlow(e,t,i){const n=new I(h.t("jig.ellipse.secondAxisEndpoint"));n.useDashedLine=!0,n.useBasePoint=!0,n.basePoint=new d.AcGePoint3d(t),n.jig=new ss(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=id(a,l);if(!c){this.warnInvalidInput("axis");return}const u=tg(t,o),p=rs(t,o)/2,y=await this.promptOtherAxis(e,u,c,p,i);y&&this.appendEllipse(e,y)}async promptOtherAxis(e,t,i,n,r){for(;;){const o=new I(h.t("jig.ellipse.otherAxisOrRotation"));this.addKeyword(o,"rotation"),o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new d.AcGePoint3d(t),o.jig=new ag(e.view,u=>{const p=rs(t,u);return as(t,i,n,p)},t);const a=await k.instance.editor.getPoint(o);if(a.status===b.Keyword){if(a.stringResult!=="Rotation")return;const u=new se(h.t("jig.ellipse.rotationAngle"));u.allowNegative=!1,u.allowZero=!0,u.jig=new lo(e.view,f=>{const v=n*Math.abs(Math.cos(ao(f)));return as(t,i,n,v)},t);const p=await k.instance.editor.getDouble(u);if(p.status!==b.OK)return;const y=n*Math.abs(Math.cos(ao(p.value??0))),g=as(t,i,n,y);if(!g){this.warnInvalidInput("rotation");continue}return r?await this.promptArcAngles(e,g):g}if(a.status!==b.OK)return;const l=rs(t,a.value),c=as(t,i,n,l);if(!c){this.warnInvalidInput("otherAxis");continue}return r?await this.promptArcAngles(e,c):c}}async promptArcAngles(e,t){const i=sg(t.majorAxis),n=new Ce(h.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 lo(e.view,c=>({...t,startAngle:os(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=os(r.value??0,t.majorRadius,t.minorRadius),a=new Ce(h.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 lo(e.view,c=>({...t,startAngle:o,endAngle:os(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:os(l.value??0,t.majorRadius,t.minorRadius)}}}const $s=class $s extends R{constructor(){super(),this.mode=z.Write}get settings(){return $s._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,u=e-i,p=t-n;if(Math.abs(l*p-c*u)>a)return!1;const g=u*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 ue(h.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 se(h.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 se(h.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 re(h.t("jig.hatch.style"));i.allowNone=!0;const n=i.keywords.add(h.t("jig.hatch.keywords.normal.display"),h.t("jig.hatch.keywords.normal.global"),h.t("jig.hatch.keywords.normal.local")),r=i.keywords.add(h.t("jig.hatch.keywords.outer.display"),h.t("jig.hatch.keywords.outer.global"),h.t("jig.hatch.keywords.outer.local")),o=i.keywords.add(h.t("jig.hatch.keywords.ignore.display"),h.t("jig.hatch.keywords.ignore.global"),h.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 re(h.t("jig.hatch.associative"));t.allowNone=!0;const i=t.keywords.add(h.t("jig.hatch.keywords.yes.display"),h.t("jig.hatch.keywords.yes.global"),h.t("jig.hatch.keywords.yes.local")),n=t.keywords.add(h.t("jig.hatch.keywords.no.display"),h.t("jig.hatch.keywords.no.global"),h.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 _t(h.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(h.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 Ze(h.t("jig.hatch.prompt"));i.allowNone=!0,i.setRejectMessage(h.t("jig.hatch.invalidBoundary")),i.addAllowedClass("Polyline"),i.addAllowedClass("Circle"),i.addAllowedClass("Arc"),i.addAllowedClass("Line"),i.keywords.add(h.t("jig.hatch.keywords.pick.display"),h.t("jig.hatch.keywords.pick.global"),h.t("jig.hatch.keywords.pick.local")),i.keywords.add(h.t("jig.hatch.keywords.select.display"),h.t("jig.hatch.keywords.select.global"),h.t("jig.hatch.keywords.select.local")),i.keywords.add(h.t("jig.hatch.keywords.pattern.display"),h.t("jig.hatch.keywords.pattern.global"),h.t("jig.hatch.keywords.pattern.local")),i.keywords.add(h.t("jig.hatch.keywords.scale.display"),h.t("jig.hatch.keywords.scale.global"),h.t("jig.hatch.keywords.scale.local")),i.keywords.add(h.t("jig.hatch.keywords.angle.display"),h.t("jig.hatch.keywords.angle.global"),h.t("jig.hatch.keywords.angle.local")),i.keywords.add(h.t("jig.hatch.keywords.style.display"),h.t("jig.hatch.keywords.style.global"),h.t("jig.hatch.keywords.style.local")),i.keywords.add(h.t("jig.hatch.keywords.associative.display"),h.t("jig.hatch.keywords.associative.global"),h.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}}};$s._lastSettings={patternName:d.HATCH_PATTERN_SOLID,patternScale:1,patternAngleDeg:0,style:d.AcDbHatchStyle.Normal,associative:!0};let ls=$s;const lg=".png,.jpg,.jpeg,.bmp,.gif,.tif,.tiff",cg=100;function dg(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 ug(s,e){const t=Math.max(1,s),i=Math.max(1,e),n=Math.max(t,i),r=n>0?cg/n:1;return{width:Math.max(1,t*r),height:Math.max(1,i*r)}}async function hg(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 pg(){return new Promise(s=>{const e=document.createElement("input");e.type="file",e.accept=lg,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 mg extends G{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 od extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=await pg();if(!t)return;let i;try{i=await hg(t)}catch{this.showMessage(h.t("jig.imageattach.decodeFailed"),"error");return}const n=ug(i.width,i.height),r=new mg(e.view,t,n.width,n.height);try{r.setMode("point");const o=new I(h.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 se(h.t("jig.imageattach.scale"));c.allowNone=!0,c.allowNegative=!1,c.allowZero=!1,c.useDefaultValue=!0,c.defaultValue=1,c.jig=r;const u=await k.instance.editor.getDouble(c);if(u.status===b.Cancel||u.status===b.Error)return;const p=u.status===b.OK&&u.value!==void 0?u.value:1;if(!(p>0)){this.showMessage(h.t("jig.imageattach.invalidScale"),"warning");return}r.setScale(p),r.setMode("rotation");const y=new Ce(h.t("jig.imageattach.rotation"));y.allowNone=!0,y.allowNegative=!0,y.allowZero=!0,y.useDefaultValue=!0,y.defaultValue=0,y.useBasePoint=!0,y.useDashedLine=!0,y.basePoint=l,y.jig=r;const g=await k.instance.editor.getAngle(y);if(g.status===b.Cancel||g.status===b.Error)return;const v=(g.status===b.OK&&g.value!==void 0?g.value:0)*Math.PI/180,w=e.doc.database,x=dg(w,t.name),S=Math.max(1e-6,n.width*p),A=Math.max(1e-6,n.height*p);yt(w,"IMAGEATTACH",()=>{const C=new d.AcDbRasterImageDef;C.sourceFileName=t.name,w.objects.imageDefinition.setAt(x,C);const L=new d.AcDbRasterImage;L.position=l,L.width=S,L.height=A,L.rotation=v,L.image=t,L.imageDefId=C.objectId,w.tables.blockTable.modelSpace.appendEntity(L)})}finally{r.end()}}}const ta=class ta{static set(e){this._options={...e}}static consume(){const e=this._options;return this._options=null,e}static clear(){this._options=null}};ta._options=null;let cs=ta;function ad(s){const e=s.trim();return!e||/[\r\n]/.test(e)?!1:!e.startsWith("*")}class yg extends G{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 ld extends R{constructor(){super(),this.mode=z.Write}async execute(e){const i=e.doc.database.tables.blockTable,n=cs.consume(),r=new ue(h.t("jig.insert.blockName")),o=await k.instance.editor.getString(r);if(o.status!==b.OK)return;const a=String(o.stringResult??"").trim();if(!ad(a)){this.showMessage(h.t("jig.insert.invalidBlockName"),"warning");return}if(!i.has(a)){this.showMessage(`${h.t("jig.insert.blockNotFound")}: ${a}`,"warning");return}const l=i.getAt(a);if(l!=null&&l.isXref){this.showMessage(h.t("jig.insert.xrefNotAllowed"),"warning");return}const c=new yg(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(h.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,u=1,p=1;if(!((n==null?void 0:n.specifyScale)!==!1)&&n)c=co(n.scaleX,1),u=co(n.scaleY,c),p=co(n.scaleZ,c),i.setScaleFactors(c,u,p);else{i.setMode("scale");const w=new se(h.t("jig.insert.scale"));w.allowNone=!0,w.allowNegative=!1,w.allowZero=!1,w.useDefaultValue=!0,w.defaultValue=1,w.jig=i;const x=await k.instance.editor.getDouble(w);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(h.t("jig.insert.invalidScale"),"warning"),!1;c=u=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 w=new Ce(h.t("jig.insert.rotation"));w.allowNone=!0,w.allowNegative=!0,w.allowZero=!0,w.useDefaultValue=!0,w.defaultValue=0,w.useBasePoint=!0,w.useDashedLine=!0,w.basePoint=l,w.jig=i;const x=await k.instance.editor.getAngle(w);if(x.status===b.Cancel||x.status===b.Error)return!1;g=x.status===b.OK&&x.value!==void 0?x.value:0}const v=g*Math.PI/180;return yt(r,"INSERT",()=>{const w=new d.AcDbBlockReference(t);w.position=l,w.scaleFactors=new d.AcGePoint3d(c,u,p),w.rotation=v,r.tables.blockTable.modelSpace.appendEntity(w)}),!0}}function co(s,e){return s!==void 0&&s>0?s:e}class cd extends G{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();uo(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();uo(this._mline,t,i.styleName,i.justification,i.scale,!1,i.elementOffsets)}}class dd extends R{constructor(){super(),this.mode=z.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 C=t.objects.mlineStyle.getAt(r);return wg((C==null?void 0:C.elements)??[],i,n)},c=C=>o.push(new d.AcGePoint3d(C)),u=()=>{o.length>1&&o.pop()},p=()=>{if(o.length<=1)return;const C=o[0],L=o[o.length-1];kg(C,L)||c(C),a=!0},y=async()=>{const C=new re(h.t("jig.mline.justificationPrompt"));C.allowNone=!0,C.keywords.add(h.t("jig.mline.keywords.top.display"),h.t("jig.mline.keywords.top.global"),h.t("jig.mline.keywords.top.local")),C.keywords.add(h.t("jig.mline.keywords.zero.display"),h.t("jig.mline.keywords.zero.global"),h.t("jig.mline.keywords.zero.local")),C.keywords.add(h.t("jig.mline.keywords.bottom.display"),h.t("jig.mline.keywords.bottom.global"),h.t("jig.mline.keywords.bottom.local"));const L=await k.instance.editor.getKeywords(C);if(L.status===b.None)return!0;if(L.status!==b.Keyword)return!1;const _=L.stringResult??"";return _==="Top"?i=d.AcDbMLineJustification.Top:_==="Bottom"?i=d.AcDbMLineJustification.Bottom:i=d.AcDbMLineJustification.Zero,!0},g=async()=>{const C=new se(h.t("jig.mline.scalePrompt"));C.allowNone=!0,C.allowZero=!0,C.allowNegative=!0,C.useDefaultValue=!0,C.defaultValue=n;const L=await k.instance.editor.getDouble(C);return L.status===b.None?!0:L.status!==b.OK?!1:(n=L.value??n,!0)},f=()=>{const C=[...t.objects.mlineStyle.entries()].map(([L])=>L);if(C.length<=0){this.showMessage(h.t("jig.mline.styleListEmpty"),"warning");return}this.showMessage(`${h.t("jig.mline.styleListHeader")} ${C.join(", ")}`,"info")},v=async()=>{for(;;){const C=new ue(h.t("jig.mline.stylePrompt"));C.allowEmpty=!1,C.allowSpaces=!1;const L=await k.instance.editor.getString(C);if(L.status!==b.OK)return!1;const _=(L.stringResult??"").trim();if(_){if(_==="?"){f();continue}return r=_,!0}}},w=async C=>C==="Justification"?await y():C==="Scale"?await g():C==="Style"?await v():!0;for(;;){const C=new I(h.t("jig.mline.startPointWithOptions"));C.keywords.add(h.t("jig.mline.keywords.justification.display"),h.t("jig.mline.keywords.justification.global"),h.t("jig.mline.keywords.justification.local")),C.keywords.add(h.t("jig.mline.keywords.scale.display"),h.t("jig.mline.keywords.scale.global"),h.t("jig.mline.keywords.scale.local")),C.keywords.add(h.t("jig.mline.keywords.style.display"),h.t("jig.mline.keywords.style.global"),h.t("jig.mline.keywords.style.local"));const L=await k.instance.editor.getPoint(C);if(L.status===b.OK){c(L.value);break}if(L.status!==b.Keyword||!await w(L.stringResult??""))return}class x{buildPrompt(){const L=new I(h.t("jig.mline.nextPointWithOptions"));return L.keywords.add(h.t("jig.mline.keywords.justification.display"),h.t("jig.mline.keywords.justification.global"),h.t("jig.mline.keywords.justification.local")),L.keywords.add(h.t("jig.mline.keywords.scale.display"),h.t("jig.mline.keywords.scale.global"),h.t("jig.mline.keywords.scale.local")),L.keywords.add(h.t("jig.mline.keywords.style.display"),h.t("jig.mline.keywords.style.global"),h.t("jig.mline.keywords.style.local")),L.keywords.add(h.t("jig.mline.keywords.undo.display"),h.t("jig.mline.keywords.undo.global"),h.t("jig.mline.keywords.undo.local")),o.length>1&&L.keywords.add(h.t("jig.mline.keywords.close.display"),h.t("jig.mline.keywords.close.global"),h.t("jig.mline.keywords.close.local")),L.useDashedLine=!0,L.useBasePoint=!0,L.basePoint=new d.AcGePoint3d(o[o.length-1]),L.jig=new cd(e.view,o,()=>({justification:i,scale:n,styleName:r,elementOffsets:l()})),L.allowNone=!0,L}async handleResult(L){if(L.status===b.OK)return c(L.value),"continue";if(L.status!==b.Keyword)return"finish";const _=L.stringResult??"";return _==="Undo"?(u(),"continue"):_==="Close"&&o.length>1?(p(),"finish"):await w(_)?"continue":"finish"}}const S=new Xe;if(S.setState(new x),await S.run(C=>k.instance.editor.getPoint(C)),o.length<2)return;const A=new d.AcDbMLine;uo(A,o,r,i,n,a,l()),t.tables.blockTable.modelSpace.appendEntity(A),t.cmlstyle=r,t.cmlscale=n}}function uo(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=gg(e,o)}function gg(s,e){const t=fg(s);return s.slice(1).map((i,n)=>{const r=n+1,o=bg(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 fg(s){const e=[];for(let t=0;t<s.length-1;t++){const i=s[t],n=s[t+1],r=ho({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 bg(s,e){if(s.length<=0)return{direction:{x:0,y:1,z:0},offsetScale:1};if(e<=0)return{direction:ds(s[0]),offsetScale:1};if(e>=s.length)return{direction:ds(s[s.length-1]),offsetScale:1};const t=ds(s[e-1]),i=ds(s[e]),n=ho({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(vg(n,i));return d.AcGeTol.isNonPositive(r)?{direction:n,offsetScale:1}:{direction:n,offsetScale:1/r}}function wg(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 ds(s){return ho({x:-s.y,y:s.x,z:0})??{x:0,y:1,z:0}}function ho(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 vg(s,e){return s.x*e.x+s.y*e.y+s.z*e.z}function kg(s,e){return d.DEFAULT_TOL.equalPoint3d(s,e)}class ud extends R{constructor(){super(),this.mtextEditor=new $e,this.mode=z.Write}async execute(e){const t=new Un(h.t("main.inputManager.firstCorner"),h.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))),u=await this.mtextEditor.open({view:o,location:l,width:r,textHeight:a,toolbarFontFamilies:c});if(!u||!u.contents.trim())return;const y=new d.AcDbMText;y.location=u.location,y.contents=u.contents,y.width=u.width,y.height=u.height,y.lineSpacingFactor=u.lineSpacingFactor,y.attachmentPoint=u.attachmentPoint,e.doc.database.tables.blockTable.modelSpace.appendEntity(y)}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 hd extends R{constructor(){super(),this.mode=z.Write}async execute(e){for(;;){const t=new I(h.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 xg=3,Sg=1024;function Ag(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function po(s,e){s.reset(!1),e.forEach((t,i)=>s.addVertexAt(i,t)),s.closed=!0}function pd(s,e,t,i){const n=Ag(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 u=0;u<e;u++){const p=l+u*r;c.push(new d.AcGePoint2d(s.x+a*Math.cos(p),s.y+a*Math.sin(p)))}return c}function md(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,u=i,p=n;for(let y=2;y<t;y++){const g=u*Math.cos(o)-p*Math.sin(o),f=u*Math.sin(o)+p*Math.cos(o);l+=g,c+=f,a.push(new d.AcGePoint2d(l,c)),u=g,p=f}return a}class Cg extends G{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=pd(this._center,this._sides,e,this._modeProvider());t&&po(this._polyline,t)}}class Pg extends G{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=md(this._firstPoint,e,this._sides);t&&po(this._polyline,t)}}const cn=class cn extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=await this.promptSides();if(t==null)return;const i=new I(h.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(h.t(`jig.polygon.keywords.${t}.display`),h.t(`jig.polygon.keywords.${t}.global`),h.t(`jig.polygon.keywords.${t}.local`))}appendPolygon(e,t){const i=new d.AcDbPolyline;po(i,t),e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){this.notify(h.t(`jig.polygon.invalid.${e}`),"warning")}async promptSides(){for(;;){const e=cn._lastSides,t=new ue(h.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>=xg&&r<=Sg)return cn._lastSides=r,r;this.warnInvalidInput("sides")}}async runCenterFlow(e,t,i){let n="Inscribed";for(;;){const r=new I(h.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 Cg(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=pd(i,t,o.value,n);if(!a){this.warnInvalidInput("radius");continue}this.appendPolygon(e,a);return}}async runEdgeFlow(e,t){const i=new I(h.t("jig.polygon.edgeStart")),n=await k.instance.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=new I(h.t("jig.polygon.edgeEnd"));o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new d.AcGePoint3d(r),o.jig=new Pg(e.view,r,t);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)return;const l=md(r,a.value,t);if(!l){this.warnInvalidInput("edge");return}this.appendPolygon(e,l)}};cn._lastSides=4;let us=cn;class yd extends G{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 _g extends G{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 gd extends R{constructor(){super(),this.mode=z.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,u=n/o,p=o/2*i;return{x:a+c*p,y:l+u*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,u=2*(o*l+a*c);if(d.AcGeTol.equalToZero(u))return;const p=(o*o+a*a)/u;if(!Number.isFinite(p))return;const y={x:e.x+l*p,y:e.y+c*p};return this.computeBulgeFromCenterWithTangent(e,t,y,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),u=Math.sin(n),p=t.x-e.x,y=t.y-e.y,g=r*u-o*c;let f;d.AcGeTol.isPositive(Math.abs(g))?f=g>0:f=p*u-y*c>=0;const v=Math.atan2(o,r),w=Math.atan2(l,a);let x;if(f?(x=w-v,d.AcGeTol.isNonPositive(x)&&(x+=Math.PI*2)):(x=v-w,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,u=r,p=2*(a*c+l*u);if(d.AcGeTol.equalToZero(p))return;const y=(a*a+l*l)/p;if(!Number.isFinite(y))return;const g={x:e.x+c*y,y:e.y+u*y},f=this.computeBulgeFromCenterWithTangent(e,t,g,i);if(f==null)return;const v=Math.tan(n/4);if(Number.isFinite(v))return Math.sign(f)*Math.abs(v)}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,u=Math.atan2(l,c);if(Number.isFinite(u))return Math.tan(u/4)}computeCircleCenter(e,t,i){const n=e.x,r=e.y,o=t.x,a=t.y,l=i.x,c=i.y,u=n-o,p=r-a,y=n-l,g=r-c,f=(n*n-o*o+r*r-a*a)/2,v=(n*n-l*l+r*r-c*c)/2,w=u*g-p*y;if(d.AcGeTol.equalToZero(w))return;const x=(g*f-p*v)/w,S=(-y*f+u*v)/w;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,u=Math.sqrt(Math.max(0,n*n-a*a/4)),p=-o/a,y=r/a,g=i>=0?1:-1,f=l+p*u*g,v=c+y*u*g,w=new d.AcGePoint2d(f,v);return this.computeBulgeFromCenter(e,t,w)}async execute(e){k.instance.editor.resetInputToggles();const t=[],i=[];let n=!1;const r=F=>F==null?F:k.instance.editor.getInputToggles().ctrlArcFlip?this.flipArcBulgeForCtrl(F):F,o=(F,M,V)=>this.computeBulgeFromCenter(F,M,V),a=(F,M,V)=>this.computeBulgeFromThreePoints(F,M,V),l=(F,M,V)=>this.computeBulgeFromRadius(F,M,V),c=()=>this.getIncomingTangentRadians(t,i),u=F=>{const M=f();if(M)return this.computeBulgeFromTangentDirection(M,F,c())},p=(F,M,V,U)=>this.computeBulgeFromTangentAndIncludedAngle(F,M,V,U),y=()=>new _g(e.view,t,i),g=(F,M)=>new yd(e.view,t,i,F,M),f=()=>t[t.length-1],v=F=>{t.length>0&&(i[t.length-1]=F)},w=F=>{t.push(new d.AcGePoint2d(F)),i.push(void 0)},x=()=>{t.length<=1||(t.pop(),i.pop(),i[i.length-1]=void 0)},S=F=>F!==b.OK&&F!==b.Keyword;class A{constructor(M){this.machine=M}buildPrompt(){const M=new I(h.t("jig.polyline.nextPointWithOptions"));M.keywords.add(h.t("jig.polyline.keywords.arc.display"),h.t("jig.polyline.keywords.arc.global"),h.t("jig.polyline.keywords.arc.local")),M.keywords.add(h.t("jig.polyline.keywords.undo.display"),h.t("jig.polyline.keywords.undo.global"),h.t("jig.polyline.keywords.undo.local")),M.keywords.add(h.t("jig.polyline.keywords.close.display"),h.t("jig.polyline.keywords.close.global"),h.t("jig.polyline.keywords.close.local")),M.useDashedLine=!0,M.useBasePoint=!0;const V=f();return V&&(M.basePoint=new d.AcGePoint3d(V)),M.jig=g(void 0),M.allowNone=!0,M}async handleResult(M){if(M.status===b.Keyword){const V=M.stringResult??"";if(V==="Arc")this.machine.setState(new C(this.machine));else if(V==="Undo")x();else if(V==="Close"&&t.length>1)return n=!0,v(void 0),"finish";return"continue"}return M.status===b.OK?(v(void 0),w(M.value),"continue"):"finish"}}class C{constructor(M){this.machine=M}buildPrompt(){const M=new I(h.t("jig.polyline.nextPointWithArcOptions"));M.keywords.add(h.t("jig.polyline.keywords.angle.display"),h.t("jig.polyline.keywords.angle.global"),h.t("jig.polyline.keywords.angle.local")),M.keywords.add(h.t("jig.polyline.keywords.center.display"),h.t("jig.polyline.keywords.center.global"),h.t("jig.polyline.keywords.center.local")),M.keywords.add(h.t("jig.polyline.keywords.secondPoint.display"),h.t("jig.polyline.keywords.secondPoint.global"),h.t("jig.polyline.keywords.secondPoint.local")),M.keywords.add(h.t("jig.polyline.keywords.radius.display"),h.t("jig.polyline.keywords.radius.global"),h.t("jig.polyline.keywords.radius.local")),M.keywords.add(h.t("jig.polyline.keywords.line.display"),h.t("jig.polyline.keywords.line.global"),h.t("jig.polyline.keywords.line.local")),M.keywords.add(h.t("jig.polyline.keywords.undo.display"),h.t("jig.polyline.keywords.undo.global"),h.t("jig.polyline.keywords.undo.local")),M.keywords.add(h.t("jig.polyline.keywords.close.display"),h.t("jig.polyline.keywords.close.global"),h.t("jig.polyline.keywords.close.local")),M.useDashedLine=!0,M.useBasePoint=!0;const V=f();return V&&(M.basePoint=new d.AcGePoint3d(V)),M.jig=g(void 0,U=>r(u(U))),M.allowNone=!0,M}async handleResult(M){if(M.status===b.OK){const Z=u(M.value);return Z===void 0||(v(r(Z)),w(M.value)),"continue"}if(M.status!==b.Keyword)return"finish";const V=M.stringResult??"";if(V==="Line")return this.machine.setState(new A(this.machine)),"continue";if(V==="Undo")return x(),"continue";if(V==="Close"&&t.length>1)return n=!0,v(void 0),"finish";const U=f();if(!U)return"finish";if(V==="Angle"){const Z=new se(h.t("jig.polyline.arcAngle"));Z.jig=y();const J=await k.instance.editor.getDouble(Z);if(S(J.status))return"finish";const X=new I(h.t("jig.polyline.arcEndPoint"));X.useDashedLine=!0,X.useBasePoint=!0,X.basePoint=new d.AcGePoint3d(U);const te=(J.value??0)*(Math.PI/180),oe=c();X.jig=g(void 0,na=>r(p(U,na,oe,te)));const ae=await k.instance.editor.getPoint(X);if(S(ae.status))return"finish";const Bt=p(U,ae.value,oe,te);return Bt===void 0||(v(r(Bt)),w(ae.value)),"continue"}if(V==="Center"){const Z=new I(h.t("jig.polyline.arcCenter"));Z.jig=y();const J=await k.instance.editor.getPoint(Z);if(S(J.status))return"finish";const X=new I(h.t("jig.polyline.arcEndPoint"));X.useDashedLine=!0,X.useBasePoint=!0,X.basePoint=new d.AcGePoint3d(U),X.jig=g(void 0,ae=>r(o(U,ae,J.value)));const te=await k.instance.editor.getPoint(X);if(S(te.status))return"finish";const oe=o(U,te.value,J.value);return oe===void 0||(v(r(oe)),w(te.value)),"continue"}if(V==="SecondPoint"){const Z=new I(h.t("jig.polyline.arcSecondPoint"));Z.jig=y(),Z.useDashedLine=!0,Z.useBasePoint=!0,Z.basePoint=new d.AcGePoint3d(U);const J=await k.instance.editor.getPoint(Z);if(S(J.status))return"finish";const X=new I(h.t("jig.polyline.arcEndPoint"));X.useDashedLine=!0,X.useBasePoint=!0,X.basePoint=new d.AcGePoint3d(U),X.jig=g(void 0,ae=>r(a(U,J.value,ae)));const te=await k.instance.editor.getPoint(X);if(S(te.status))return"finish";const oe=a(U,J.value,te.value);return oe===void 0||(v(r(oe)),w(te.value)),"continue"}if(V==="Radius"){const Z=new se(h.t("jig.polyline.arcRadius"));Z.jig=y();const J=await k.instance.editor.getDouble(Z);if(S(J.status))return"finish";const X=new I(h.t("jig.polyline.arcEndPoint"));X.useDashedLine=!0,X.useBasePoint=!0,X.basePoint=new d.AcGePoint3d(U),X.jig=g(void 0,ae=>r(l(U,ae,J.value??0)));const te=await k.instance.editor.getPoint(X);if(S(te.status))return"finish";const oe=l(U,te.value,J.value??0);return oe===void 0||(v(r(oe)),w(te.value)),"continue"}return"continue"}}const L=new I(h.t("jig.polyline.firstPoint")),_=await k.instance.editor.getPoint(L);if(_.status!==b.OK)return;w(_.value);const N=new Xe;if(N.setState(new A(N)),await N.run(F=>k.instance.editor.getPoint(F)),t.length>=2){const F=e.doc.database,M=new d.AcDbPolyline;t.forEach((V,U)=>M.addVertexAt(U,V,i[U])),n&&(M.closed=!0),F.tables.blockTable.modelSpace.appendEntity(M)}}}function fd(s,e){const t=new d.AcGePoint3d(e).sub(s);if(d.AcGeTol.isPositive(t.length()))return t.normalize()}class Lg extends G{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=fd(this._startPoint,e);t&&(this._ray.basePoint=new d.AcGePoint3d(this._startPoint),this._ray.unitDir=t)}}class bd extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=e.doc.database,i=new I(h.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 I(h.t("jig.ray.throughPoint"));o.useDashedLine=!0,o.useBasePoint=!0,o.basePoint=new d.AcGePoint3d(r),o.jig=new Lg(e.view,r);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)break;const l=fd(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 Eg=Math.tan(Math.PI/8),Tg={chamferDist1:0,chamferDist2:0,filletRadius:0,width:0,elevation:0,thickness:0,rotation:0};function kt(s,e){s.keywords.add(h.t(`jig.rect.keywords.${e}.display`),h.t(`jig.rect.keywords.${e}.global`),h.t(`jig.rect.keywords.${e}.local`))}function Ig(s,e){s.keywords.add(h.t(`jig.rect.keywords.${e}.display`),h.t(`jig.rect.keywords.${e}.global`),h.t(`jig.rect.keywords.${e}.local`))}function Mg(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 Dg(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 Jt(s){return Number.isFinite(s??NaN)?Math.max(0,s??0):0}function mo(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 wd(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(Jt(t),o/2),c=Math.min(Jt(i),a/2);if(d.AcGeTol.isNonPositive(l)&&d.AcGeTol.isNonPositive(c))return mo(s,e);const u=new d.AcGePoint2d(n*l,0),p=new d.AcGePoint2d(0,r*c),y=new d.AcGePoint2d(s-n*l,0),g=new d.AcGePoint2d(s,r*c),f=new d.AcGePoint2d(s,e-r*c),v=new d.AcGePoint2d(s-n*l,e),w=new d.AcGePoint2d(n*l,e),x=new d.AcGePoint2d(0,e-r*c);return[{point:u},{point:y},{point:g},{point:f},{point:v},{point:w},{point:x},{point:p}]}function Og(s,e,t){const i=Math.abs(s),n=Math.abs(e),r=Math.min(Jt(t),i/2,n/2);if(d.AcGeTol.isNonPositive(r))return mo(s,e);const o=wd(s,e,r,r),l=(s*e>=0?1:-1)*Eg;return o.map((c,u)=>({point:c.point,bulge:u%2===1?l:void 0}))}function Ng(s,e,t){return d.AcGeTol.isPositive(t.filletRadius)?Og(s,e,t.filletRadius):d.AcGeTol.isPositive(t.chamferDist1)||d.AcGeTol.isPositive(t.chamferDist2)?wd(s,e,t.chamferDist1,t.chamferDist2):mo(s,e)}function yo(s,e,t,i){let n=0,r=0;if(t.mode==="corner"){const l=Dg(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=Ng(n,r,i),a=Jt(i.width);return o.forEach((l,c)=>{const u=Mg(e,l.point,i.rotation);d.AcGeTol.isPositive(a)?s.addVertexAt(c,u,l.bulge,a,a):s.addVertexAt(c,u,l.bulge)}),s.elevation=i.elevation,s.closed=!0,!0}class vd extends G{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){yo(this._rect,this._firstPoint,{mode:"corner",secondPoint:e},this._settingsProvider())}}class Qt extends G{constructor(e,t,i,n){super(e),this._rect=new d.AcDbPolyline,yo(this._rect,t,i,n)}get entity(){return this._rect}update(e){}}function go(s){return{chamferDist1:s.chamferDist1,chamferDist2:s.chamferDist2,filletRadius:s.filletRadius,width:s.width,elevation:s.elevation,thickness:s.thickness,rotation:s.rotation}}function at(s){return Number.isFinite(s??NaN)&&d.AcGeTol.isPositive(s??0)}const dn=class dn extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=go(dn._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(!yo(r,i,n,t)){this.warnRectMessage("invalidRect");return}d.AcGeTol.isPositive(t.thickness)&&this.warnRectMessage("thicknessNotSupported"),e.doc.database.tables.blockTable.modelSpace.appendEntity(r),dn._settings=go(t)}warnRectMessage(e){this.notify(h.t(`jig.rect.${e}`),"warning")}async promptFirstCorner(e){for(;;){const t=new I(h.t("jig.rect.firstPointWithOptions"));kt(t,"chamfer"),kt(t,"elevation"),kt(t,"fillet"),kt(t,"thickness"),kt(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(h.t("jig.rect.otherCornerWithOptions"));return kt(l,"area"),kt(l,"dimensions"),kt(l,"rotation"),l.useDashedLine=!1,l.useBasePoint=!0,l.basePoint=new d.AcGePoint3d(t),l.jig=new vd(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 u=await this.cmd.promptDimensions(e,t,i);return u&&(n=u),"finish"}if(c==="Area"){const u=await this.cmd.promptArea(e,t,i);return u&&(n=u),"finish"}return"continue"}}const o=new Xe;return o.setState(new r(this)),await o.run(a=>k.instance.editor.getPoint(a)),n}async promptPositiveDouble(e,t){for(;;){const i=new se(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(at(n.value))return n.value;this.warnRectMessage("invalidPositive")}}async promptChamfer(e){const t=await this.promptPositiveDouble(h.t("jig.rect.chamferFirst"));if(!at(t))return!1;const i=await this.promptPositiveDouble(h.t("jig.rect.chamferSecond"));return at(i)?(e.chamferDist1=t,e.chamferDist2=i,e.filletRadius=0,!0):!1}async promptFillet(e){const t=await this.promptPositiveDouble(h.t("jig.rect.filletRadius"));return at(t)?(e.filletRadius=t,e.chamferDist1=0,e.chamferDist2=0,!0):!1}async promptWidth(e){const t=new se(h.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=Jt(i.value),!0)}async promptElevation(e){const t=new se(h.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 se(h.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=Jt(i.value),!0)}async promptRotation(e,t,i){const n=new Ce(h.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(h.t("jig.rect.dimensionLength"),new Qt(e.view,t,n,i));if(!at(r))return;const o=await this.promptPositiveDouble(h.t("jig.rect.dimensionWidth"),new Qt(e.view,t,{mode:"dimensions",length:r,width:1},i));if(at(o))return{mode:"dimensions",length:r,width:o}}async promptArea(e,t,i){const n=await this.promptPositiveDouble(h.t("jig.rect.areaValue"),new Qt(e.view,t,{mode:"dimensions",length:1,width:1},i));if(!at(n))return;const r=new se(h.t("jig.rect.areaLengthOrWidth"));Ig(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(h.t("jig.rect.areaSpecifyWidth"),new Qt(e.view,t,{mode:"dimensions",length:1,width:1},i));return at(l)?{mode:"dimensions",length:(n??0)/(l??1),width:l}:void 0}if(o.status!==b.OK||!at(o.value))return;const a=o.value;return{mode:"dimensions",length:a,width:(n??0)/a}}};dn._settings=go(Tg);let hs=dn;const fo=1,Bg=.005,Fg=.1;function kd(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 xd(s){const t=kd(s)*Bg;return Number.isFinite(t)&&t>0?t:1}function Et(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function bo(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 Sd(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 Ad(s){const e=s.map(t=>new d.AcGePoint2d(t.x,t.y));return e.length>=3&&Sd(e)<0&&e.reverse(),e}function Cd(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+=Et(r,o)}return t}function jg(s,e,t){const i=Cd(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],u=Et(l,c);if(n<=u||a===r-1){const p=u>0?n/u:0;return new d.AcGePoint2d(l.x+(c.x-l.x)*p,l.y+(c.y-l.y)*p)}n-=u}const o=s[e?0:s.length-1];return new d.AcGePoint2d(o.x,o.y)}function zg(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 Rg(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*zg(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 Pd(s,e,t,i){if(e.length<2)return!1;const n=t?Ad(e):e,r=Cd(n,t);if(!d.AcGeTol.isPositive(r))return!1;const o=Math.max(i.arcLength,r*1e-4),a=Rg(r,o,i.variance!==!1);if(t&&a.length<3){const y=r/3;a.length=0,a.push(y,y,y)}const l=i.reverse?-fo:fo,c=i.style==="calligraphy",u=c?o*Fg:void 0;s.reset(!1);let p=0;return a.forEach((y,g)=>{const f=jg(n,t,p);c&&u!=null?s.addVertexAt(g,f,l,0,u):s.addVertexAt(g,f,l),p+=y}),s.closed=t,s.numberOfVertices>=2}function _d(s,e,t){const i=Et(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 Vg(s,e,t,i){if(Math.abs(t)<1e-12)return _d(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)),u=(s.x+e.x)/2,p=(s.y+e.y)/2,y=-r/o,g=n/o,f=c*Math.cos(l/2),v=u+y*f*a,w=p+g*f*a,x=Math.atan2(s.y-w,s.x-v),S=l*a,A=Math.abs(c*S),C=Math.max(2,Math.ceil(A/Math.max(i,1e-8))),L=[];for(let _=0;_<C;_++){const N=x+S*_/C;L.push(new d.AcGePoint2d(v+c*Math.cos(N),w+c*Math.sin(N)))}return L}function Gg(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 Kg(s,e){const t=Gg(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(...Vg(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 Ug(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 Hg(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,u=a,p=Math.PI*(3*(t+i)-Math.sqrt((3*t+i)*(t+3*i))),y=Math.max(12,Math.ceil(p/Math.max(e,1e-8))),g=s.center,f=s.startAngle??0;let w=(s.endAngle??Math.PI*2)-f;w<=0&&(w+=Math.PI*2);const S=Math.abs(w-Math.PI*2)<1e-6?y:y+1,A=[];for(let C=0;C<S;C++){const L=f+w*C/y,_=t*Math.cos(L),N=i*Math.sin(L);A.push(new d.AcGePoint2d(g.x+a*_+c*N,g.y+l*_+u*N))}return A}function Wg(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(..._d(l,c,e))}if(!s.closed){const a=i[i.length-1];n.push(new d.AcGePoint2d(a.x,a.y))}return n}function Ld(s,e){if(s instanceof d.AcDbPolyline){const t=Kg(s,e);return t.length>=2?{points:t,closed:s.closed}:void 0}if(s instanceof d.AcDbCircle){const t=Ug(s,e);return t.length>=2?{points:t,closed:!0}:void 0}if(s instanceof d.AcDbEllipse){const t=Hg(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=Wg(s,e);return t.length>=2?{points:t,closed:!!s.closed}:void 0}}function wo(s,e,t){return Et(s,e)<=Math.max(t*.5,1e-6)}const $g={mode:"rectangular",style:"normal",variance:!0};function zi(s,e){s.keywords.add(h.t(`jig.revcloud.keywords.${e}.display`),h.t(`jig.revcloud.keywords.${e}.global`),h.t(`jig.revcloud.keywords.${e}.local`))}function qe(s){return new d.AcGePoint2d(s.x,s.y)}function Tt(s,e,t,i,n=!1){return Pd(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 d.AcDbPolyline,this._path=t.map(qe),this._closed=i,this._settings=n,this.rebuild()}get entity(){return this._cloud}updatePath(e,t){this._path=e.map(qe),this._closed=t,this.rebuild()}update(e){if(this._path.length===0)return;const t=[...this._path,qe(e)],i=this._closed&&t.length>=3;Tt(this._cloud,t,i,this._settings)}rebuild(){if(this._path.length<2){this._cloud.reset(!1);return}Tt(this._cloud,this._path,this._closed,this._settings)}}class Yg extends G{constructor(e,t,i){super(e),this._cloud=new d.AcDbPolyline,this._firstPoint=qe(t),this._settings=i}get entity(){return this._cloud}update(e){Tt(this._cloud,bo(this._firstPoint,e),!0,this._settings)}}class Zg extends G{constructor(e,t,i){super(e),this._closed=!1,this._cloud=new d.AcDbPolyline,this._points=[qe(t)],this._settings=i}get entity(){return this._cloud}get points(){return this._points}get closed(){return this._closed}addPoint(e){const t=qe(e),i=this._points[this._points.length-1];i&&Et(i,t)<1e-8||this._points.push(t)}update(e){const t=this._settings.arcLength??1,i=this._points[this._points.length-1];i&&Et(i,e)>=t&&this._points.push(qe(e)),this._closed=this._points.length>=3&&wo(this._points[0],e,t);const n=this._closed?this._points:[...this._points,qe(e)];Tt(this._cloud,n,this._closed,this._settings)}}class Xg extends G{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=Tt(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=Tt(this._cloud,this._path,this._closed,this._settings,this._reverse),this.render()}}const Ys=class Ys extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=Ys._settings;for(t.arcLength==null&&(t.arcLength=xd(e.view));;){const i=new I(h.t("jig.revcloud.firstCornerOrOptions"));zi(i,"arcLength"),zi(i,"object");const n=i.keywords.add(h.t("jig.revcloud.keywords.rectangular.display"),h.t("jig.revcloud.keywords.rectangular.global"),h.t("jig.revcloud.keywords.rectangular.local")),r=i.keywords.add(h.t("jig.revcloud.keywords.polygonal.display"),h.t("jig.revcloud.keywords.polygonal.global"),h.t("jig.revcloud.keywords.polygonal.local")),o=i.keywords.add(h.t("jig.revcloud.keywords.freehand.display"),h.t("jig.revcloud.keywords.freehand.global"),h.t("jig.revcloud.keywords.freehand.local"));zi(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 ke(h.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(h.t("jig.revcloud.invalidArcLength"),"warning"),!0)}async promptStyle(e){const t=new re(h.t("jig.revcloud.style"));t.allowNone=!0;const i=t.keywords.add(h.t("jig.revcloud.keywords.normal.display"),h.t("jig.revcloud.keywords.normal.global"),h.t("jig.revcloud.keywords.normal.local")),n=t.keywords.add(h.t("jig.revcloud.keywords.calligraphy.display"),h.t("jig.revcloud.keywords.calligraphy.global"),h.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(h.t("jig.revcloud.oppositeCorner"));r.useBasePoint=!0,r.basePoint=new d.AcGePoint3d(n.x,n.y,0),r.useDashedLine=!1,r.jig=new Yg(e.view,n,t);const o=await k.instance.editor.getPoint(r);if(o.status!==b.OK||!o.value)return;const a=bo(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=[qe(n)];class o{buildPrompt(){const c=new I(h.t(r.length>=2?"jig.revcloud.nextPointOrUndo":"jig.revcloud.nextPoint"));r.length>=2&&zi(c,"undo"),c.useDashedLine=!1,c.useBasePoint=!0;const u=r[r.length-1];return c.basePoint=new d.AcGePoint3d(u.x,u.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(qe(c.value)),"continue"):"finish"}}const a=new Xe;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 Zg(e.view,n,t),o=t.arcLength??1;for(;;){const a=new I(h.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&&wo(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 Ze(h.t("jig.revcloud.selectObject"));i.setRejectMessage(h.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=Ld(r,(t.arcLength??1)*.5);if(!o){this.showMessage(h.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 Xg(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 Tt(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 re(h.t("jig.revcloud.reverseDirection"));t.jig=e,t.allowNone=!0,zi(t,"yes");const i=t.keywords.add(h.t("jig.revcloud.keywords.no.display"),h.t("jig.revcloud.keywords.no.global"),h.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(h.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)}};Ys._settings={...$g};let ps=Ys;const qg={type:"line",increment:.1,tolerance:.5};function vo(s,e){s.keywords.add(h.t(`jig.sketch.keywords.${e}.display`),h.t(`jig.sketch.keywords.${e}.global`),h.t(`jig.sketch.keywords.${e}.local`))}function ms(s,e){return Math.hypot(e.x-s.x,e.y-s.y)}function xt(s){return new d.AcGePoint2d(s.x,s.y)}function ys(s){return new d.AcGePoint3d(s.x,s.y,0)}function Td(s,e,t){const i=xt(e);if(s.length===0)return s.push(i),!0;const n=s[s.length-1];return ms(n,i)<t?!1:(s.push(i),!0)}function Id(s,e){if(s.length<=2)return s.map(xt);const t=Math.max(e,1e-8),i=[xt(s[0])];for(let o=1;o<s.length-1;o++){const a=i[i.length-1];ms(a,s[o])>=t&&i.push(xt(s[o]))}const n=xt(s[s.length-1]),r=i[i.length-1];return ms(r,n)>1e-8&&i.push(n),i}class Md extends G{constructor(e,t,i){super(e),this._polyline=new d.AcDbPolyline,this._points=[xt(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 Jg{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,xt(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 gs extends G{constructor(e,t){super(e),this.preview=t}update(e){}render(){this.preview.render()}}const Zs=class Zs extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=Zs._settings,i=[],n=new Jg(e.view);try{for(;;){n.render();const r=new I(h.t("jig.sketch.specifySketch"));vo(r,"type"),vo(r,"increment"),vo(r,"tolerance"),r.allowNone=!0,r.disableOSnap=!0,r.jig=new gs(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 re(h.t("jig.sketch.type"));i.allowNone=!0,t&&(i.jig=new gs(t.view,t));const n=i.keywords.add(h.t("jig.sketch.keywords.line.display"),h.t("jig.sketch.keywords.line.global"),h.t("jig.sketch.keywords.line.local")),r=i.keywords.add(h.t("jig.sketch.keywords.polyline.display"),h.t("jig.sketch.keywords.polyline.global"),h.t("jig.sketch.keywords.polyline.local")),o=i.keywords.add(h.t("jig.sketch.keywords.spline.display"),h.t("jig.sketch.keywords.spline.global"),h.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 ke(h.t("jig.sketch.increment"));i.allowNegative=!1,i.allowZero=!1,i.useDefaultValue=!0,i.defaultValue=e.increment,t&&(i.jig=new gs(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 ke(h.t("jig.sketch.tolerance"));i.allowNegative=!1,i.allowZero=!0,i.useDefaultValue=!0,i.defaultValue=e.tolerance,t&&(i.jig=new gs(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 I(h.t("jig.sketch.sketching"));o.jig=r,o.useDashedLine=!1,o.useBasePoint=!0,o.basePoint=ys(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||ms(c,a.value)>1e-8)&&l.push(xt(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(ys(n[o-1]),ys(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(ys),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)}};Zs._settings={...qg};let fs=Zs;class Dd 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 d.AcGePoint2d(e),i=this._points[this._points.length-1],r=!i||!tf(i,t)?[...this._points,t]:[...this._points];try{this.rebuildSpline(r)}catch{this.rebuildSpline(this._points)}}createSpline(e){return ko(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=Ri(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=Nd(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=Ri(t.length,i);this._spline.rebuild(t,r,void 0,i,!1),n&&(this._spline.closed=!0)}}class Od extends R{constructor(){super(),this.mode=z.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 Dd(e.view,t,i,n),u=()=>new Qg(e.view,t,i,n),p=async()=>{const S=new re(h.t("jig.spline.methodPrompt"));S.keywords.add(h.t("jig.spline.keywords.fit.display"),h.t("jig.spline.keywords.fit.global"),h.t("jig.spline.keywords.fit.local")),S.keywords.add(h.t("jig.spline.keywords.cv.display"),h.t("jig.spline.keywords.cv.global"),h.t("jig.spline.keywords.cv.local"));const A=await k.instance.editor.getKeywords(S);return A.status!==b.OK?!1:(A.stringResult==="Fit"?i.method="fit":A.stringResult==="CV"&&(i.method="cv"),!0)},y=async()=>{const S=new re(h.t("jig.spline.knotsPrompt"));S.jig=u(),S.keywords.add(h.t("jig.spline.keywords.chord.display"),h.t("jig.spline.keywords.chord.global"),h.t("jig.spline.keywords.chord.local")),S.keywords.add(h.t("jig.spline.keywords.sqrtChord.display"),h.t("jig.spline.keywords.sqrtChord.global"),h.t("jig.spline.keywords.sqrtChord.local")),S.keywords.add(h.t("jig.spline.keywords.uniform.display"),h.t("jig.spline.keywords.uniform.global"),h.t("jig.spline.keywords.uniform.local"));const A=await k.instance.editor.getKeywords(S);return A.status!==b.OK?!1:(A.stringResult==="Chord"?i.knotsType="chord":A.stringResult==="SqrtChord"?i.knotsType="sqrtChord":A.stringResult==="Uniform"&&(i.knotsType="uniform"),!0)},g=async()=>{const S=new Gr(h.t("jig.spline.degreePrompt"),1,10);S.jig=u();const A=await k.instance.editor.getInteger(S);if(A.status!==b.OK)return!1;const C=Math.floor(A.value??i.degree);return i.degree=Math.max(1,C),!0},f=S=>{S.useDashedLine=!0,S.useBasePoint=!0;const A=a();A&&(S.basePoint=new d.AcGePoint3d(A)),S.jig=c(),S.allowNone=!0};class v{constructor(A){this.machine=A}buildPrompt(){const A=new I(h.t("jig.spline.nextPointWithFitOptions"));return A.keywords.add(h.t("jig.spline.keywords.method.display"),h.t("jig.spline.keywords.method.global"),h.t("jig.spline.keywords.method.local")),A.keywords.add(h.t("jig.spline.keywords.knots.display"),h.t("jig.spline.keywords.knots.global"),h.t("jig.spline.keywords.knots.local")),A.keywords.add(h.t("jig.spline.keywords.undo.display"),h.t("jig.spline.keywords.undo.global"),h.t("jig.spline.keywords.undo.local")),A.keywords.add(h.t("jig.spline.keywords.close.display"),h.t("jig.spline.keywords.close.global"),h.t("jig.spline.keywords.close.local")),f(A),A}async handleResult(A){if(A.status===b.OK)return r(A.value),"continue";if(A.status!==b.Keyword)return"finish";const C=A.stringResult??"";return C==="Method"?await p()?(i.method==="cv"&&this.machine.setState(new w(this.machine)),"continue"):"finish":C==="Knots"?await y()?"continue":"finish":C==="Undo"?(o(),"continue"):C==="Close"&&l()?(n=!0,"finish"):"continue"}}class w{constructor(A){this.machine=A}buildPrompt(){const A=new I(h.t("jig.spline.nextPointWithCvOptions"));return A.keywords.add(h.t("jig.spline.keywords.method.display"),h.t("jig.spline.keywords.method.global"),h.t("jig.spline.keywords.method.local")),A.keywords.add(h.t("jig.spline.keywords.degree.display"),h.t("jig.spline.keywords.degree.global"),h.t("jig.spline.keywords.degree.local")),A.keywords.add(h.t("jig.spline.keywords.undo.display"),h.t("jig.spline.keywords.undo.global"),h.t("jig.spline.keywords.undo.local")),A.keywords.add(h.t("jig.spline.keywords.close.display"),h.t("jig.spline.keywords.close.global"),h.t("jig.spline.keywords.close.local")),f(A),A}async handleResult(A){if(A.status===b.OK)return r(A.value),"continue";if(A.status!==b.Keyword)return"finish";const C=A.stringResult??"";return C==="Method"?await p()?(i.method==="fit"&&this.machine.setState(new v(this.machine)),"continue"):"finish":C==="Degree"?await g()?"continue":"finish":C==="Undo"?(o(),"continue"):C==="Close"&&l()?(n=!0,"finish"):"continue"}}for(;t.length===0;){const S=new I(h.t("jig.spline.firstPointWithOptions"));S.keywords.add(h.t("jig.spline.keywords.method.display"),h.t("jig.spline.keywords.method.global"),h.t("jig.spline.keywords.method.local"));const A=await k.instance.editor.getPoint(S);if(A.status===b.OK){r(A.value);break}if(A.status===b.Keyword&&A.stringResult==="Method"){if(!await p())return;continue}return}const x=new Xe;if(x.setState(i.method==="fit"?new v(x):new w(x)),await x.run(S=>k.instance.editor.getPoint(S)),t.length>=2){const S=e.doc.database,A=ko(t,i,n);S.tables.blockTable.modelSpace.appendEntity(A)}}}class Qg extends G{constructor(e,t,i,n){super(e),this._spline=ko(t,i,n)}get entity(){return this._spline}update(e){}}function ko(s,e,t){if(s.length<2){const c=[new d.AcGePoint3d(0,0,0),new d.AcGePoint3d(1,1,0)],u=1,p=Ri(c.length,u);return new d.AcDbSpline(c,p,void 0,u)}const i=s.map(c=>new d.AcGePoint3d(c.x,c.y,0)),n=e.method==="fit"?ef(i):i;if(n.length<2){const c=[new d.AcGePoint3d(0,0,0),new d.AcGePoint3d(1,1,0)],u=1,p=Ri(c.length,u);return new d.AcDbSpline(c,p,void 0,u)}const r=Nd(n.length,e),o=t&&n.length>=3;if(e.method==="fit")return new d.AcDbSpline(n,Bd(e.knotsType),r,o);const a=Ri(n.length,r),l=new d.AcDbSpline(n,a,void 0,r,!1);return o&&(l.closed=!0),l}function Nd(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 ef(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];nf(i,n)||e.push(new d.AcGePoint3d(n))}return e}function tf(s,e){return d.DEFAULT_TOL.equalPoint2d(s,e)}function nf(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 Ri(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 xo(s,e){const t=d.acdbHostApplicationServices(),i=t._workingDatabase;t.workingDatabase=s;try{return await e()}finally{t._workingDatabase=i}}const sf=".dwg,.dxf",Fd=100;function rf(s){var a,l,c,u,p,y,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=(u=t==null?void 0:t.getPathForFile)==null?void 0:u.call(t,s))==null?void 0:p.trim();if(i)return i;const n=s,r=(y=n.path)==null?void 0:y.trim();if(r)return r;const o=(g=n.mozFullPath)==null?void 0:g.trim();return o||s.name}function of(s){return s.replace(/\.(dwg|dxf)$/i,"")||s}function af(s,e){const t=of(e);if(!s.tables.blockTable.has(t))return t;let i=1;for(;s.tables.blockTable.has(`${t}_${i}`);)i++;return`${t}_${i}`}function lf(){return new Promise(s=>{const e=document.createElement("input");e.type="file",e.accept=sf,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 cf(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(Fd,Fd,0)):t}class df extends G{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 jd extends R{constructor(){super(),this.mode=z.Write}async execute(e){var a;const t=await lf();if(!t)return;const i=(a=t.name.split(".").pop())==null?void 0:a.toLocaleLowerCase();if(i!=="dwg"&&i!=="dxf"){this.showMessage(h.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 xo(c,async()=>{await c.read(l,{readOnly:!0},i==="dwg"?d.AcDbFileType.DWG:d.AcDbFileType.DXF)}),c},h.t("jig.xattach.loading"))}catch{this.showMessage(h.t("jig.xattach.loadFailed"),"error");return}const r=cf(n),o=new df(e.view,r);try{o.setMode("point");const l=new I(h.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 u=c.status===b.OK&&c.value?new d.AcGePoint3d(c.value):new d.AcGePoint3d(0,0,0);o.setPosition(u),o.setMode("scale");const p=new se(h.t("jig.xattach.scale"));p.allowNone=!0,p.allowNegative=!1,p.allowZero=!1,p.useDefaultValue=!0,p.defaultValue=1,p.jig=o;const y=await k.instance.editor.getDouble(p);if(y.status===b.Cancel||y.status===b.Error)return;const g=y.status===b.OK&&y.value!==void 0?y.value:1;if(!(g>0)){this.showMessage(h.t("jig.xattach.invalidScale"),"warning");return}o.setScale(g),o.setMode("rotation");const f=new Ce(h.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=u,f.jig=o;const v=await k.instance.editor.getAngle(f);if(v.status===b.Cancel||v.status===b.Error)return;const x=(v.status===b.OK&&v.value!==void 0?v.value:0)*Math.PI/180,S=e.doc.database,A=af(S,t.name),C=rf(t),L={position:u,scale:g,rotationRad:x},_=await St.instance.attachOverlay({blockName:A,fileName:t.name,sourceDb:n,sourcePath:C,transform:L});try{yt(S,"XATTACH",()=>{const{insert:N}=St.createHostXrefInsert(S,A,C,L,n.tables.blockTable.modelSpace.origin);_.insertId=N.objectId})}catch(N){throw St.instance.unload(_.id),N}ie.emit("missed-data-changed",{})}finally{o.end()}}}const ei=1e6;class zd extends R{constructor(){super(),this.mode=z.Write}async execute(e){let t="point";for(;;){const i=new I(h.t("jig.xline.firstPointOrOptions"));i.keywords.add(h.t("jig.xline.keywords.hor.display"),h.t("jig.xline.keywords.hor.global"),h.t("jig.xline.keywords.hor.local")),i.keywords.add(h.t("jig.xline.keywords.ver.display"),h.t("jig.xline.keywords.ver.global"),h.t("jig.xline.keywords.ver.local")),i.keywords.add(h.t("jig.xline.keywords.ang.display"),h.t("jig.xline.keywords.ang.global"),h.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 u=new I(h.t("jig.xline.secondPoint"));u.useBasePoint=!0,u.useDashedLine=!0,u.basePoint=new d.AcGePoint3d(n.value);const p=await k.instance.editor.getPoint(u);if(p.status!==b.OK||!p.value)return;const y={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,y)||this.showMessage(h.t("jig.xline.invalidDirection"),"warning");continue}else return;if(t==="hor"){const u=new I(h.t("jig.xline.throughPoint")),p=await k.instance.editor.getPoint(u);if(p.status!==b.OK||!p.value)return;this.appendFiniteXLine(e,p.value,{x:1,y:0,z:0});continue}if(t==="ver"){const u=new I(h.t("jig.xline.throughPoint")),p=await k.instance.editor.getPoint(u);if(p.status!==b.OK||!p.value)return;this.appendFiniteXLine(e,p.value,{x:0,y:1,z:0});continue}const r=new se(h.t("jig.xline.angle")),o=await k.instance.editor.getDouble(r);if(o.status!==b.OK||o.value==null)return;const a=new I(h.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*ei,t.y-n.y*ei,t.z-n.z*ei),o=new d.AcGePoint3d(t.x+n.x*ei,t.y+n.y*ei,t.z+n.z*ei);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 Rd(s){const e=s.htmlTransientManager,t=s.activeLayoutBtrId;zt(s,"Clear Measurements",()=>{e.deselectAll();for(const i of e.groupsOnLayer(Y))(i.layoutId==null||i.layoutId===t)&&e.detach(i.id)}),e.clear(le),s.isHtmlDirty=!0}class Vd extends R{constructor(){super(),this.mode=z.Read}async execute(e){Rd(e.view)}}class Gd extends R{constructor(){super(),this.mode=z.Read,this.recordsUndoStack=!1}async execute(e){const t=e.view;Va(t,!yr())}}function bs(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 Kd(s,e,t,i,n,r=2){const o=bs(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=Se(n),a.lineWidth=r,a.stroke(),a.restore()}function Ud(s,e,t,i,n,r,o=2){const a=bs(s,e);if(!a)return;const{ctx:l}=a,c=e.worldToScreen(t),u=e.worldToScreen(i),p=e.worldToScreen(n);l.strokeStyle=Se(r),l.lineWidth=o,l.beginPath(),l.moveTo(c.x,c.y),l.lineTo(u.x,u.y),l.moveTo(c.x,c.y),l.lineTo(p.x,p.y),l.stroke();const y=Math.hypot(u.x-c.x,u.y-c.y),g=Math.hypot(p.x-c.x,p.y-c.y),f=Math.max(Math.min(y,g)*.3,15),v=Math.atan2(u.y-c.y,u.x-c.x),w=Math.atan2(p.y-c.y,p.x-c.x),x=d.AcGeMathUtil.normalizeAngle(w-v)>Math.PI;l.beginPath(),l.arc(c.x,c.y,f,v,w,x),l.stroke(),l.restore()}function Hd(s,e,t,i,n=2.5){const r=bs(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=dr(i,.2),o.fill(),o.strokeStyle=Se(i),o.lineWidth=n,o.stroke(),o.restore()}function ws(s,e,t,i,n,r,o,a){const l=e.worldToScreen({x:t.cx,y:t.cy}),c=e.worldToScreen(i),u=e.worldToScreen(n),p=Math.hypot(c.x-l.x,c.y-l.y);if(!(p>0))return;const y=Math.atan2(c.y-l.y,c.x-l.x),g=Math.atan2(u.y-l.y,u.x-l.x),f=a?d.AcGeCircArc2d.tryCreateByThreePoints(i,a,n):void 0,v=f?!f.clockwise:d.AcGeMathUtil.normalizeAngle(g-y)>Math.PI;s.beginPath(),s.arc(l.x,l.y,p,y,g,v),s.strokeStyle=Se(r),s.lineWidth=o,s.stroke()}function Wd(s,e,t,i,n,r,o=4,a){const l=bs(s,e);l&&(ws(l.ctx,e,t,i,n,r,o,a),l.ctx.restore())}function $d(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 So(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 Yd(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 It(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 vs(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,u={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(u.x,u.y),s.lineTo(p.x,p.y),s.closePath(),s.fill()}function Ao(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&&vs(s,t,e,i)}function Co(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 Po{worldDraw(e){return this.subWorldDraw(e)}subGetGripPoints(){return[]}subMoveGripPointsAt(e,t){return this}hitTest(e,t,i){return!1}primaryPoint(){}}function _o(s,e){const t=s.viewportToCanvas({x:e.clientX,y:e.clientY}),i=s.screenToWorld(t);return{x:i.x,y:i.y}}function Je(s,e,t){s.htmlTransientManager.updatePosition(e.id,t)}const Zd=4,ti={capture:!0,passive:!1};function Mt(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 u=c.target;if(c.detail>=2||u!=null&&u.isContentEditable||u!=null&&u.closest('[contenteditable="true"]')||t.querySelector('[contenteditable="true"]'))return;const p=c.pointerId,y=c.clientX,g=c.clientY;let f=!1;const v=()=>{window.removeEventListener("pointermove",w,ti),window.removeEventListener("pointerup",x,ti),window.removeEventListener("pointercancel",x,ti),a===v&&(a=void 0)},w=S=>{if(S.pointerId===p){if(!f){const A=S.clientX-y,C=S.clientY-g;if(A*A+C*C<Zd*Zd)return;f=!0,S.preventDefault(),t.style.cursor="grabbing",i==null||i()}n(_o(e,S),S),e.isHtmlDirty=!0}},x=S=>{S.pointerId===p&&(v(),f&&(t.style.cursor=o,r()))};a==null||a(),a=v,window.addEventListener("pointermove",w,ti),window.addEventListener("pointerup",x,ti),window.addEventListener("pointercancel",x,ti)};return t.addEventListener("pointerdown",l),()=>{t.removeEventListener("pointerdown",l),a==null||a()}}function ks(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 u=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=Mt({view:e,el:t.element,onDragStart:()=>{c={tip:{...n.tip},anchor:{...n.anchor}},o==null||o()},onMove:g=>{n.tip=r?r(g):g,Je(e,t,n.tip),a()},onCommit:()=>{const g={tip:{...n.tip},anchor:{...n.anchor}};u(g)||l(g)}}),y=Mt({view:e,el:i.element,onDragStart:()=>{c={tip:{...n.tip},anchor:{...n.anchor}},o==null||o()},onMove:g=>{n.anchor=g,Je(e,i,n.anchor),a()},onCommit:()=>{const g={tip:{...n.tip},anchor:{...n.anchor}};u(g)||l(g)}});return()=>{p(),y()}}class ii extends Po{constructor(e,t,i){super(),this.entityId=e,this.layoutIdOption=t,this.style=i}get id(){return this.entityId}hitTest(e,t,i){return rr(this.toRecord().geometry,e,t,i)}commit(e,t){const i=this.subWorldDrawWithDb(e,t);Ya(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 D.AcTrHtmlGroup({id:this.entityId,layer:Y,layoutId:this.resolveLayoutId(e),selectable:!0})}resolveLayoutId(e){return this.layoutIdOption??e.activeLayoutBtrId}}class Vi extends ii{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 Vi(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:gt(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=Yd(this.vertex,this.arm1,this.arm2),r=this.resolveLayoutId(e),o=new D.AcTrHtmlCanvasOverlay({id:`angle-canvas-${this.entityId}`,container:e.container,layer:Y,layoutId:r}),a=(M=this.style)=>Ud(o.canvas,e,this.vertex,this.arm1,this.arm2,M.color,Te(M.lineWeight));a();const l=()=>a(Pt(this.entityId)??this.style);e.events.viewChanged.addEventListener(l);const c=this.arm1.x-this.vertex.x,u=this.arm1.y-this.vertex.y,p=this.arm2.x-this.vertex.x,y=this.arm2.y-this.vertex.y,g=Math.hypot(c,u),f=Math.hypot(p,y),v=g>0?c/g:1,w=g>0?u/g:0,x=f>0?p/f:1,S=f>0?y/f:0;let A=v+x,C=w+S;const L=Math.hypot(A,C);L>0?(A/=L,C/=L):(A=-w,C=v);const _=Math.max(Math.min(g,f)*.4,Math.max(g,f)*.15),N={x:this.vertex.x+A*_,y:this.vertex.y+C*_};return{group:this.createGroup(e).add(new D.AcTrHtmlDot({id:`${this.entityId}-dotV`,color:i,worldPosition:this.vertex,layer:Y}),new D.AcTrHtmlDot({id:`${this.entityId}-dot1`,color:i,worldPosition:this.arm1,layer:Y}),new D.AcTrHtmlDot({id:`${this.entityId}-dot2`,color:i,worldPosition:this.arm2,layer:Y}),new D.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:i,text:bn(t,n*Math.PI/180),worldPosition:N,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 Gi extends ii{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 Gi(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:gt(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 D.AcTrHtmlCanvasOverlay({id:`arc-canvas-${this.entityId}`,container:e.container,layer:Y,layoutId:o}),l=(y=this.style)=>Wd(a.canvas,e,this.geom,this.start,this.end,y.color,Te(y.lineWeight),this.through);l();const c=()=>l(Pt(this.entityId)??this.style);return e.events.viewChanged.addEventListener(c),{group:this.createGroup(e).add(new D.AcTrHtmlDot({id:`${this.entityId}-dot1`,color:i,worldPosition:this.start,layer:Y}),...this.through?[new D.AcTrHtmlDot({id:`${this.entityId}-dot-through`,color:i,worldPosition:this.through,layer:Y})]:[],new D.AcTrHtmlDot({id:`${this.entityId}-dot2`,color:i,worldPosition:this.end,layer:Y}),new D.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:i,text:Ee(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 Ki extends ii{constructor(e,t){super(t.id??`area-${Date.now()}`,t.layoutId,t.style),this.points=e}static create(e,t,i){return new Ki(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=So(this.points);return{x:e.x,y:e.y,z:0}}toRecord(e){return{id:this.entityId,type:"area",layoutId:e,style:gt(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=$d(this.points),r=this.resolveLayoutId(e),o=So(this.points),a=new D.AcTrHtmlCanvasOverlay({id:`area-canvas-${this.entityId}`,container:e.container,layer:Y,layoutId:r}),l=(p=this.style)=>Hd(a.canvas,e,this.points,p.color,Te(p.lineWeight));l();const c=()=>l(Pt(this.entityId)??this.style);return e.events.viewChanged.addEventListener(c),{group:this.createGroup(e).add(new D.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:i,text:`${Ee(t,n)}²`,worldPosition:o,layer:Y,fontSize:this.style.fontSize}),...this.points.map((p,y)=>new D.AcTrHtmlDot({id:`${this.entityId}-dot${y}`,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 uf(s,e){const t=e.x-s.x,i=e.y-s.y;return Math.sqrt(t*t+i*i)}class Ui extends ii{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 Ui(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:gt(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=uf(this.p1,this.p2),n=this.style.color,r=this.resolveLayoutId(e),o=this.primaryPoint(),a=new D.AcTrHtmlCanvasOverlay({id:`dist-canvas-${this.entityId}`,container:e.container,layer:Y,layoutId:r}),l=(p=this.style)=>Kd(a.canvas,e,this.p1,this.p2,p.color,Te(p.lineWeight));l();const c=()=>l(Pt(this.entityId)??this.style);return e.events.viewChanged.addEventListener(c),{group:this.createGroup(e).add(new D.AcTrHtmlDot({id:`${this.entityId}-dot1`,color:n,worldPosition:this.p1,layer:Y}),new D.AcTrHtmlDot({id:`${this.entityId}-dot2`,color:n,worldPosition:this.p2,layer:Y}),new D.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:n,text:Ee(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 Hi extends ii{constructor(e,t){super(t.id??`point-${Date.now()}`,t.layoutId,t.style),this.point=e}static create(e,t,i){return new Hi(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:gt(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 D.AcTrHtmlDot({id:`${this.entityId}-dot`,color:r,worldPosition:this.point,layer:Y}),new D.AcTrHtmlBadge({id:`${this.entityId}-badge`,color:r,text:ar(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=Ba(s.style),t={id:s.id,layoutId:s.layoutId,style:e},i=s.geometry;switch(i.type){case"distance":return new Ui({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 Vi({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 Ki(i.points.map(n=>({x:n.x,y:n.y,z:0})),t);case"arc":return new Gi({cx:i.center.x,cy:i.center.y,r:i.radius},i.start,i.end,t,i.through);case"point":return new Hi({x:i.position.x,y:i.position.y,z:0},t)}}function hf(s){return`${s}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function qd(s,e,t){const i=t.geometry.type==="distance"?"dist":t.geometry.type,n={...t,id:hf(i)};try{return Xd(n).commit(s,e),!0}catch{return!1}}function pf(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 mf(){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 Jd extends R{constructor(){super(),this.mode=z.Read,this.recordsUndoStack=!1}async execute(e){const t=e.view,i=e.doc.fileName||e.doc.docTitle,n=ja({version:1,drawingName:i,measurements:Wa(t)});pf(za(i),n)}}class Qd extends R{constructor(){super(),this.mode=z.Read,this.recordsUndoStack=!1}async execute(e){new ue(h.t("jig.measurement.import.chooseFile"));const t=await mf();if(t==null)return;let i;try{i=Fa(t)}catch(o){console.error(o);return}const n=e.view,r=e.doc.database;zt(n,"Import Measurements",()=>{for(const o of i.measurements)qd(n,r,o)})}}class xe{constructor(e,t,i){this.drawFn=null,this.onViewChanged=()=>this.acapPaint(),this.view=e,this.overlay=new D.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=It(this.overlay.canvas,this.view.container);e&&((t=this.drawFn)==null||t.call(this,e,this.view))}}function lt(s,e,t,i,n,r,o){const a=typeof n=="string"?n:Se(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&&vs(s,l,c,a)}function ni(s,e,t,i,n,r){if(t.length<2)return;const o=typeof i=="string"?i:Se(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 Lo(s,e,t,i,n,r){if(i<=0)return;const o=typeof n=="string"?n:Se(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 yf(s,e,t,i,n,r){Co(s,e.worldToScreen(t),e.worldToScreen(i),n,r)}function Eo(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 gf(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 eu(s,e,t,i,n,r,o){Vi.create(t,i,n,r,o).commit(s,e)}class ff extends G{constructor(e,t,i){super(e),this._vertex=t,this._cursor=t,this._color=i,this._preview=new xe(e,`live-angle-arm1-${Date.now()}`,le)}get entity(){return null}update(e){this._cursor=e;const t=Te(st());this._preview.acapSetDraw((i,n)=>{lt(i,n,this._vertex,this._cursor,this._color,t)})}end(){super.end(),this._preview.acapDispose()}}class bf 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 D.AcTrHtmlBadge({id:this._badgeId,color:r,worldPosition:i,layer:le,layoutId:this._view.activeLayoutBtrId,fontSize:Fe(),transform:"translate(-50%, calc(-50% - 30px))"}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new xe(this._view,`live-angle-arm2-${Date.now()}`,le)}get entity(){return null}update(e){this._arm2=e,this._color=Be(this._db),this._badge.setColor(this._color),this._badge.setFontSize(Fe());const t=Te(st());this._preview.acapSetDraw((n,r)=>{lt(n,r,this._vertex,this._arm1,this._color,t,{dashed:!0}),lt(n,r,this._vertex,this._arm2,this._color,t)});const i=gf(this._vertex,this._arm1,e);this._badge.setText(bn(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 tu extends R{constructor(){super(),this.mode=z.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Be(i);await e.view.withMode(fe.SELECTION,()=>t.withCursor(Ie.Crosshair,async()=>{const r=new I(h.t("jig.measureAngle.vertex")),o=await t.getPoint(r);if(o.status!==b.OK)return;const a=o.value,l=new I(h.t("jig.measureAngle.arm1"));l.useBasePoint=!0,l.jig=new ff(e.view,a,n);const c=await t.getPoint(l);if(c.status!==b.OK)return;const u=c.value,p=new I(h.t("jig.measureAngle.arm2"));p.jig=new bf(e.view,i,a,u,n);const y=await t.getPoint(p);if(y.status!==b.OK)return;const g=y.value;eu(e.view,i,a,u,g,pt(i))}))}}class wf extends G{constructor(e,t,i,n){super(e),this._onMove=n}get entity(){return null}update(e){this._onMove(e)}}function vf(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,u=t.y-s.y,p=(c*a-u*o)/l,y=(c*r-u*n)/l;return p>0&&p<1&&y>0&&y<1}function kf(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 xf(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 iu(s,e,t,i,n){t.length<3||Ki.create(t,i,n).commit(s,e)}class nu extends R{constructor(){super(),this.mode=z.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Be(i),r=pt(i),o=Te(r.lineWeight),a=[],l=new D.AcTrHtmlCanvasOverlay({id:`live-area-canvas-${Date.now()}`,container:e.view.container,layer:le,layoutId:e.view.activeLayoutBtrId}),c=l.canvas,u=e.view.htmlTransientManager;u.add(l);const p=`live-area-badge-${Date.now()}`,y=new D.AcTrHtmlBadge({id:p,color:n,worldPosition:{x:0,y:0},layer:le,layoutId:e.view.activeLayoutBtrId,fontSize:r.fontSize});y.object.visible=!1,u.add(y);const g=w=>{const x=e.view.canvas.getBoundingClientRect(),S=window.devicePixelRatio||1,A=Math.round(x.width),C=Math.round(x.height),L=e.view.canvasToContainer({x:0,y:0});c.style.left=`${L.x}px`,c.style.top=`${L.y}px`,c.style.width=`${A}px`,c.style.height=`${C}px`,(c.width!==A*S||c.height!==C*S)&&(c.width=A*S,c.height=C*S);const _=c.getContext("2d");if(!_||a.length<1)return;_.clearRect(0,0,c.width,c.height),_.save(),_.scale(S,S);const N=a.map(M=>e.view.worldToScreen(M)),F=w?[...N,e.view.worldToScreen(w)]:N;if(F.length>=3){_.beginPath(),_.moveTo(F[0].x,F[0].y);for(let M=1;M<F.length;M++)_.lineTo(F[M].x,F[M].y);_.closePath(),_.fillStyle=dr(n,.2),_.fill()}if(N.length>=2){_.beginPath(),_.moveTo(N[0].x,N[0].y);for(let M=1;M<N.length;M++)_.lineTo(N[M].x,N[M].y);_.strokeStyle=Se(n),_.lineWidth=o,_.setLineDash([8,5]),_.stroke(),_.setLineDash([])}if(w&&N.length>=1){const M=N[N.length-1],V=e.view.worldToScreen(w);_.beginPath(),_.moveTo(M.x,M.y),_.lineTo(V.x,V.y),_.strokeStyle=Se(n),_.lineWidth=o,_.stroke()}_.restore()},f=()=>g();e.view.events.viewChanged.addEventListener(f);const v=()=>{u.remove(p),u.remove(l.id),e.view.events.viewChanged.removeEventListener(f)};try{await e.view.withMode(fe.SELECTION,()=>t.withCursor(Ie.Crosshair,async()=>{const w=await t.getPoint(new I(h.t("jig.measureArea.firstPoint")));if(w.status!==b.OK)return;const x=w.value;a.push(x),g();try{for(;a.length<50;){const S=new I(h.t("jig.measureArea.nextPoint"));S.useBasePoint=!0,S.allowNone=!0;const A=_=>{if(a.length<2){g(_);return}const N=[...a,_],F=kf(N);y.setText(`${Ee(i,F)}²`),y.setPosition(xf(N)),y.object.visible=!0,g(_)};S.jig=new wf(e.view,a[a.length-1],n,A);const C=await t.getPoint(S);if(C.status!==b.OK)break;const L=C.value;if(y.object.visible=!1,a.length>=3){const _=e.view.worldToScreen(L),N=F=>{const M=e.view.worldToScreen(F),V=_.x-M.x,U=_.y-M.y;return V*V+U*U<=196};if(N(a[0])||N(a[a.length-1]))break}if(a.length>=3){const _=a[a.length-1];let N=!1;for(let F=0;F<a.length-2;F++)if(vf(_,L,a[F],a[F+1])){N=!0;break}if(N)break}a.push(L),g()}}catch{}}))}finally{v()}a.length<3||iu(e.view,i,a,pt(i))}}const Sf=1e-12;function su(s,e,t,i){const n=s-t,r=e-i;return n*n+r*r}function Af(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=su(e.x,e.y,s.startPoint.x,s.startPoint.y)<=o,l=su(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 u=a&&!l?c[1]:c[c.length-2],p=u.x-e.x,y=u.y-e.y,g=Math.hypot(p,y);return g>1e-18?(i*p+n*y)/g:0}function Cf(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 ru(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 Pf(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 ou(s,e,t,i,n){return{x:s+(n===-1?-1:1)*t*Math.cos(i),y:e+t*Math.sin(i)}}function _f(s,e){let t=e-s;for(;t<=0;)t+=d.TAU;for(;t>d.TAU;)t-=d.TAU;return t}function Lf(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=ou(t,i,n,s.startAngle,e),o=ou(t,i,n,s.endAngle,e),a=_f(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 Ef(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 Tf(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=Lf(s);return n?[n]:[]}if(!(s instanceof d.AcDbPolyline))return[];const e=Ef(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)>Sf))continue;const a=new d.AcGeCircArc2d(r,o,r.bulge);a.radius>0&&i.push(a)}return i}const xs=20,If=.02;function Mf(s){return d.AcGeMathUtil.normalizeAngle(s+Math.PI)-Math.PI}function au(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 De(s){return{x:s.x,y:s.y}}function To(s){return{cx:s.center.x,cy:s.center.y,r:s.radius}}function lu(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 Io(s,e){const t=s.doc.database.tables.blockTable,i=s.view.curPos,n=new Set,r=[...s.view.pick(i,xs),...s.view.pick(e,xs)].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=xs,u=-1/0;for(const p of r){const y=t.getEntityById(p.id);if(y)for(const g of Tf(y)){if(!(g.radius>0))continue;const f=g.nearestPoint(a),v=s.view.worldToScreen(f),w=Math.hypot(o.x-v.x,o.y-v.y);if(w>xs)continue;const x=Af(g,{x:f.x,y:f.y},{x:i.x,y:i.y});(!l||Cf(w*w,x,c*c,u))&&(c=w,u=x,l={geom:To(g),snapped:{x:f.x,y:f.y,z:0}})}}return l}function Mo(s,e,t,i,n,r,o,a){Gi.create(t,i,r,o,{...a,through:n}).commit(s,e)}class Df extends G{constructor(e,t){super(e.view),this._ctx=e,this._indicatorId=`live-arc-snap-${Date.now()}`,this._htManager=e.view.htmlTransientManager,this._indicator=new D.AcTrHtmlSnapIndicator({id:this._indicatorId,color:t,worldPosition:{x:0,y:0,z:0},layer:le,layoutId:e.view.activeLayoutBtrId}),this._indicator.object.visible=!1,this._htManager.add(this._indicator)}get entity(){return null}update(e){const t=Io(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 Of extends G{constructor(e,t,i,n,r){super(e.view),this._baseClockwise=null,this._ctx=e,this._view=e.view,this._geom=i,this._start=De(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 D.AcTrHtmlSnapIndicator({id:this._indicatorId,color:r,worldPosition:n,layer:le,layoutId:this._view.activeLayoutBtrId}),this._htManager.add(this._indicator),this._badgeId=`live-arc-locked-badge-${Date.now()}`,this._badge=new D.AcTrHtmlBadge({id:this._badgeId,color:r,worldPosition:n,layer:le,layoutId:this._view.activeLayoutBtrId,fontSize:Fe()}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new xe(this._view,`live-arc-locked-${Date.now()}`,le)}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=Mf(t-this._lastAngle);Math.abs(i)>If&&(this._baseClockwise=i<0)}this._lastAngle=t}update(e){const t=this._view.curPos,i=Io(this._ctx,e);i&&ru(this._start,i.geom)&&!Pf(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=lu(t,this._geom),r=De(n);this._trackSweepDirection(r),this._color=Be(this._db),this._indicator.setPosition(n),this._badge.setColor(this._color),this._badge.setFontSize(Fe());const o=Te(st()),a=au(this._start,r,this._geom,this.clockwise);if(this._preview.acapSetDraw((l,c)=>{ws(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(Ee(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 Nf extends G{constructor(e,t,i){super(e),this._start=t,this._cursor=t,this._color=i,this._preview=new xe(e,`live-arc-through-${Date.now()}`,le)}get entity(){return null}update(e){this._cursor=e;const t=Te(st());this._preview.acapSetDraw((i,n)=>{lt(i,n,this._start,this._cursor,this._color,t)})}end(){super.end(),this._preview.acapDispose()}}class Bf extends G{constructor(e,t,i,n,r){super(e),this._view=e,this._start=De(i),this._through=De(n),this._end=De(n),this._color=r,this._db=t,this._badgeId=`live-arc-badge-${Date.now()}`,this._htManager=this._view.htmlTransientManager,this._badge=new D.AcTrHtmlBadge({id:this._badgeId,color:r,worldPosition:i,layer:le,layoutId:this._view.activeLayoutBtrId,fontSize:Fe()}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new xe(this._view,`live-arc-end-${Date.now()}`,le)}get entity(){return null}update(e){this._end=De(e),this._color=Be(this._db),this._badge.setColor(this._color),this._badge.setFontSize(Fe());const t=Te(st()),i=d.AcGeCircArc2d.tryCreateByThreePoints(this._start,this._through,this._end),n=i?To(i):null;if(this._preview.acapSetDraw((r,o)=>{if(!n){ni(r,o,[this._start,this._through,this._end],this._color,t);return}ws(r,o,n,this._start,this._end,this._color,t,this._through)}),!i){this._badge.object.visible=!1;return}this._badge.setText(Ee(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 cu extends R{constructor(){super(),this.mode=z.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Be(i),r=e.view;await e.view.withMode(fe.SELECTION,()=>t.withCursor(Ie.Crosshair,async()=>{t.resetInputToggles();const o=new I(h.t("jig.measureArc.startPoint"));o.jig=new Df(e,n);const a=await t.getPoint(o);if(a.status!==b.OK)return;const l=a.value,c=Io(e,l);if(c){const C=ru(De(l),c.geom)?l:c.snapped;await this.commitLockedArc(e,r,i,n,c.geom,C);return}const u=new I(h.t("jig.measureArc.throughPoint"));u.useBasePoint=!0,u.jig=new Nf(e.view,l,n);const p=await t.getPoint(u);if(p.status!==b.OK)return;const y=p.value,g=new I(h.t("jig.measureArc.endPoint"));g.jig=new Bf(e.view,i,l,y,n);const f=await t.getPoint(g);if(f.status!==b.OK)return;const v=f.value,w=De(l),x=De(y),S=De(v),A=d.AcGeCircArc2d.tryCreateByThreePoints(w,x,S);if(!A){this.showMessage(h.t("jig.measureArc.invalidPoints"),"warning");return}Mo(r,i,To(A),w,x,S,pt(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 D.AcTrHtmlDot({id:l,color:n,worldPosition:o,layer:le,layoutId:t.activeLayoutBtrId}));const c=new I(h.t("jig.measureArc.lockedEndPoint")),u=new Of(e,i,r,o,n);c.jig=u;let p;try{const w=await e.view.editor.getPoint(c);if(w.status!==b.OK)return;p=w.value}finally{a.remove(l)}if(!p)return;const y=u.geom,g=De(o),f=De(lu(p,y)),v=au(g,f,y,u.clockwise);if(!v){this.showMessage(h.t("jig.measureArc.invalidPoints"),"warning");return}Mo(t,i,y,g,v.through,f,pt(i))}}function Ff(s,e){const t=e.x-s.x,i=e.y-s.y;return Math.sqrt(t*t+i*i)}function du(s,e,t,i,n,r){Ui.create(t,i,n,r).commit(s,e)}class uu 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 D.AcTrHtmlBadge({id:this._badgeId,color:n,worldPosition:i,layer:le,layoutId:this._view.activeLayoutBtrId,fontSize:Fe()}),this._badge.object.visible=!1,this._htManager.add(this._badge),this._preview=new xe(this._view,`live-dist-stroke-${Date.now()}`,le)}get entity(){return null}update(e){this._p2=e,this._color=Be(this._db),this._badge.setColor(this._color),this._badge.setFontSize(Fe());const t=Ff(this._p1,e),i=Te(st());if(this._preview.acapSetDraw((n,r)=>{lt(n,r,this._p1,this._p2,this._color,i)}),t<1e-4){this._badge.object.visible=!1;return}this._badge.setText(Ee(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 hu extends R{constructor(){super(),this.mode=z.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Be(i);await e.view.withMode(fe.SELECTION,()=>t.withCursor(Ie.Crosshair,async()=>{const r=new I(h.t("jig.measureDistance.firstPoint")),o=await t.getPoint(r);if(o.status!==b.OK)return;const a=o.value,l=new I(h.t("jig.measureDistance.secondPoint"));l.useBasePoint=!0,l.jig=new uu(e.view,i,a,n);const c=await t.getPoint(l);if(c.status!==b.OK)return;const u=c.value;du(e.view,i,a,u,pt(i))}))}}function pu(s,e,t,i,n){Hi.create(t,i,n).commit(s,e)}class mu extends R{constructor(){super(),this.mode=z.Read}async execute(e){const t=e.view.editor,i=e.doc.database;await e.view.withMode(fe.SELECTION,()=>t.withCursor(Ie.Crosshair,async()=>{const n=new I(h.t("jig.measurePoint.point")),r=await t.getPoint(n);if(r.status!==b.OK)return;const o=r.value;pu(e.view,i,o,pt(i))}))}}let Ss;function yu(s){Ss=s}function Wi(s,e){Ss==null||Ss(s,e)}function Do(){return new d.AcCmColor(d.AcCmColorMethod.ByACI,1)}const As=d.AcGiLineWeight.LineWeight070,gu=12;let fu=Do(),bu=As,wu=gu;const Oo=new Set;function No(){for(const s of Oo)s()}function Cs(s){return Oo.add(s),()=>{Oo.delete(s)}}function ee(){return fu.clone()}function _e(){return bu}function Qe(){return wu}function vu(s){fu=s.clone(),No()}function ku(s){s>0&&(bu=s,No())}function xu(s){!Number.isFinite(s)||s<=0||(wu=s,No())}function Ve(s){const e=Number(s);return!Number.isFinite(e)||e<=0?2:Math.max(1,e/28)}function Dt(s){return s.cssColor??`rgb(${s.red}, ${s.green}, ${s.blue})`}function Bo(s){const e=d.AcCmColor.fromString(s);if(e)return gi(e);try{return gi(new d.AcCmColor().setRGBFromCss(s))}catch{return Do()}}function Ps(){return{color:Dt(ee()),lineWeight:_e(),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 Au(){return new Date().toISOString()}function Cu(s){const e=d.AcDbSysVarManager.instance().getVar(d.AcDbSystemVariables.LOGINNAME,s);return typeof e=="string"?e.trim():""}function Pu(s){const e=s.style.lineWeight!=null&&s.style.lineWeight>0?s.style.lineWeight:As;return{color:Bo(s.style.color),lineWeight:e,canvasLineWidth:Ve(e),layer:fn,layoutId:s.layoutId}}class Ot extends Po{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 Pu(this.record)}hitTest(e,t,i){return ir(this.record.geometry,e,t,i)}primaryPoint(){const e=yn(this.record.geometry);if(e)return{x:e.x,y:e.y,z:0}}subGetGripPoints(){const e=yn(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:er(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 D.AcTrHtmlGroup({id:this.record.id,layer:e,layoutId:t,selectable:!0})}}const _u=z.Review;function Ge(s){s.mode=_u,s.recordsUndoStack=!1}function Ke(s,e,t,i){const n=Au();return{id:Su(s),type:s,layoutId:e.activeLayoutBtrId,style:Ps(),text:i==null?void 0:i.text,comment:(i==null?void 0:i.comment)??"",status:"open",author:Cu(t.doc.database),createdAt:n,updatedAt:n}}async function Fo(s,e,t=""){const i=new ue(h.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 _s(s,e){return(await Ir({el:s.textElement,listenOn:s.element,multiline:(e==null?void 0:e.multiline)??!0,initialText:(e==null?void 0:e.initialText)??""})??"").trim()}async function et(s,e){await s.view.withMode(fe.SELECTION,()=>s.view.editor.withCursor(Ie.Crosshair,e))}const jf=8;function zf(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 $i(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},u=zf(t,jf,c),p=Math.max(u,1e-6),y=Math.max(4,Math.ceil(a/p)*2),g=Math.max(4,Math.ceil(l/p)*2),f=[];let v=0;const w=x=>x?.4:-.4;for(let x=0;x<=y;x++){const S=x/y;f.push({x:i+a*S,y:r,bulge:x<y?w(v++%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?w(v++%2===0):0})}for(let x=1;x<=y;x++){const S=1-x/y;f.push({x:i+a*S,y:o,bulge:x<y?w(v++%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?w(v++%2===0):0})}return f}function Lu(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 Rf(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),u=Math.atan2(s.y-l,s.x-a);let y=Math.atan2(e.y-l,e.x-a)-u;t>0?y<=0&&(y+=Math.PI*2):y>=0&&(y-=Math.PI*2);const g=[],f=Math.max(2,i);for(let v=1;v<=f;v++){const w=v/f,x=u+y*w;g.push({x:a+c*Math.cos(x),y:l+c*Math.sin(x)})}return g}function Ls(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=Rf({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 Eu(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=$i(t,i,e),u=Ls(c).map(y=>({x:y.x+a,y:y.y+l}));if(u.length<2)return;const p=u.map(y=>e.worldToScreen(y));s.strokeStyle=n,s.lineWidth=r,s.beginPath(),s.moveTo(p[0].x,p[0].y);for(let y=1;y<p.length;y++)s.lineTo(p[y].x,p[y].y);s.closePath(),s.stroke()}function Vf(s,e,t,i){const n=$i(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 Gf(s,e,t){const i=Lu(e,t);s.reset(!1);for(let n=0;n<i.length;n++)s.addVertexAt(n,i[n]);s.closed=!0}let si=!0;function Kf(){return si}function Uf(s){si=s}async function Es(s,e){for(;;){const t=si?"jig.markup.shape.calloutOn":"jig.markup.shape.calloutOff",i=new I(`${h.t(e)} ${h.t(t)}`);i.keywords.add(h.t("jig.markup.shape.keywords.callout.display"),h.t("jig.markup.shape.keywords.callout.global"),h.t("jig.markup.shape.keywords.callout.local")),i.keywords.add(h.t("jig.markup.shape.keywords.noCallout.display"),h.t("jig.markup.shape.keywords.noCallout.global"),h.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"){si=!0;continue}if(r==="NoCallout"){si=!1;continue}continue}return n.status!==b.OK?void 0:n.value}}function Hf(s){return s.kind==="circle"?{...s.center}:{x:(s.corner1.x+s.corner2.x)/2,y:(s.corner1.y+s.corner2.y)/2}}function ri(s,e){if(s.kind==="circle"){const{center:v,radius:w}=s,x=e.x-v.x,S=e.y-v.y,A=Math.hypot(x,S);if(A<1e-9||w<=0)return{x:v.x+w,y:v.y};const C=w/A;return{x:v.x+x*C,y:v.y+S*C}}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,u=e.x-o,p=e.y-a;if(Math.abs(u)<1e-9&&Math.abs(p)<1e-9)return{x:i,y:a};const y=Math.abs(u)>1e-9?l/Math.abs(u):Number.POSITIVE_INFINITY,g=Math.abs(p)>1e-9?c/Math.abs(p):Number.POSITIVE_INFINITY,f=Math.min(y,g);return{x:o+u*f,y:a+p*f}}function Wf(s,e,t){return Ls($i(s,e,t))}class $f extends G{constructor(e,t,i,n){super(e),this._view=e,this._outline=t,this._previewShape=(n==null?void 0:n.previewShape)!==!1,this._color=i,this._ht=this._view.htmlTransientManager;const r=Hf(t),o=(n==null?void 0:n.toward)??{x:r.x+1,y:r.y};this._tip=ri(t,o),this._anchor={...this._tip};const a=Date.now();this._tipDotId=`live-shape-callout-tip-${a}`,this._bubbleId=`live-shape-callout-bubble-${a}`;const l=this._view.activeLayoutBtrId;this._tipDot=new D.AcTrHtmlDot({id:this._tipDotId,color:i,worldPosition:this._tip,layer:de,layoutId:l}),this._ht.add(this._tipDot),this._bubble=new D.AcTrHtmlCallout({id:this._bubbleId,color:i,text:"",fontSize:Qe(),worldPosition:this._tip,layer:de,layoutId:l}),this._ht.add(this._bubble),this._preview=new xe(this._view,`live-shape-callout-stroke-${a}`,de),this._unsubDrawStyle=Cs(()=>this.applyCurrentStyle()),this.paintPreview(),this._view.isHtmlDirty=!0}get entity(){return null}update(e){const t={x:e.x,y:e.y};this._tip=ri(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(Qe()),this.paintPreview(),this._view.isHtmlDirty=!0}paintPreview(){const e=this._outline,t=this._color,i=Ve(_e()),n=this._tip,r=this._anchor,o=this._view,a=this._previewShape;this._preview.acapSetDraw((l,c)=>{if(a)if(e.kind==="circle")Lo(l,c,e.center,e.radius,t,i);else if(e.kind==="cloud"){const u=Wf(e.corner1,e.corner2,o);ni(l,c,u,t,i,{closed:!0})}else ni(l,c,Eo(e.corner1,e.corner2),t,i,{closed:!0});lt(l,c,n,r,t,i)})}}async function Yi(s,e,t){if(!(t!=null&&t.force)&&!si)return;const i=ee(),n=new $f(s.view,e,i,{previewShape:t==null?void 0:t.previewShape,toward:t==null?void 0:t.toward});try{const r=new I(h.t("jig.markup.shape.calloutAnchor"));r.useBasePoint=!1,r.jig=n;const o=await s.view.editor.getPoint(r);if(o.status!==b.OK)return;const a=o.value,l=ri(e,{x:a.x,y:a.y}),c=await _s(n.capsule);return{tip:l,anchor:{x:a.x,y:a.y},text:c||void 0}}finally{n.disposePreview()}}function Zi(s,e){H().setSelectedId(e),s.htmlTransientManager.selectGroup(e)}function Tu(s){const{view:e,group:t,record:i,callout:n,style:r,cleanups:o,outline:a}=s,{color:l,layer:c,layoutId:u}=r,p=e.container,y=new D.AcTrHtmlCanvasOverlay({id:`${i.id}-shape-leader`,container:p,layer:c,layoutId:u});t.addCanvas(y);const g={tip:{...n.tip},anchor:{...n.anchor}},f=()=>{const S=It(y.canvas,p);S&&Ao(S,e.worldToScreen(g.tip),e.worldToScreen(g.anchor),i.style.color,!1,Ve(i.style.lineWeight!=null&&i.style.lineWeight>0?i.style.lineWeight:As))};f(),e.events.viewChanged.addEventListener(f),o.push(()=>e.events.viewChanged.removeEventListener(f));const v=new D.AcTrHtmlCallout({id:`${i.id}-shape-bubble`,color:l,text:n.text||i.text||"",fontSize:i.style.fontSize,worldPosition:g.anchor,layer:c,layoutId:u}),w=new D.AcTrHtmlDot({id:`${i.id}-shape-tip`,color:l,worldPosition:g.tip,layer:c,layoutId:u});return t.add(v,w),o.push(Fn({view:e,el:v.textElement,listenOn:v.element,recordId:i.id,multiline:!0})),{live:g,redraw:f,tipDot:w,bubble:v,bindGrips:()=>{o.push(ks({view:e,tipEl:w,bubbleEl:v,state:g,constrainTip:S=>ri(a,S),onDragStart:()=>Zi(e,i.id),onLiveChange:f,onCommit:S=>{const A=H().get(i.id);if(!A||A.geometry.type!==a.kind)return;const C=A.geometry;C.type!=="cloud"&&C.type!=="rect"&&C.type!=="circle"||ve(e,"Move Callout",()=>{var _;const L=H().updateGeometry(i.id,{...C,callout:{tip:S.tip,anchor:S.anchor,text:((_=C.callout)==null?void 0:_.text)??n.text}});L&&Wi(e,L)})}}))}}}function Xi(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 Mt({view:e,el:i.element,cursor:"move",onDragStart:()=>{Zi(e,t);const c=H().get(t);o=(c?yn(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 u=c.x-o.x,p=c.y-o.y;n==null||n(u,p),Je(e,i,c),r&&l&&(r.live.tip=ce(l.tip,u,p),r.live.anchor=ce(l.anchor,u,p),Je(e,r.tipDot,r.live.tip),Je(e,r.bubble,r.live.anchor),r.redraw())},onCommit:()=>{const c=a.x-o.x,u=a.y-o.y;if(Math.hypot(c,u)<1e-9){n==null||n(0,0);return}ve(e,"Move Markup",()=>{const p=H().get(t);if(!p)return;const y=H().updateGeometry(t,er(p.geometry,c,u));y&&Wi(e,y)})}})}class Iu extends Ot{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=[],u=e.container,p=new D.AcTrHtmlCanvasOverlay({id:`${this.record.id}-leader`,container:u,layer:r,layoutId:o});a.addCanvas(p);const y={tip:{...t.tip},anchor:{...t.anchor}},g=()=>{const S=It(p.canvas,u);S&&Ao(S,e.worldToScreen(y.tip),e.worldToScreen(y.anchor),this.record.style.color,!0,n)};g(),e.events.viewChanged.addEventListener(g),l.push(()=>e.events.viewChanged.removeEventListener(g));const f=new D.AcTrHtmlCallout({id:`${this.record.id}-bubble`,color:i,text:this.record.text||this.record.comment||"Callout",fontSize:this.record.style.fontSize,worldPosition:y.anchor,layer:r,layoutId:o}),v=new D.AcTrHtmlDot({id:`${this.record.id}-tip`,color:i,worldPosition:y.tip,layer:r,layoutId:o}),w=new D.AcTrHtmlDot({id:`${this.record.id}-center`,color:i,worldPosition:{x:(y.tip.x+y.anchor.x)/2,y:(y.tip.y+y.anchor.y)/2},layer:r,layoutId:o});a.add(f,v,w),l.push(Fn({view:e,el:f.textElement,listenOn:f.element,recordId:this.record.id,multiline:!0}));const x=()=>{Je(e,w,{x:(y.tip.x+y.anchor.x)/2,y:(y.tip.y+y.anchor.y)/2})};return c.push(()=>{l.push(ks({view:e,tipEl:v,bubbleEl:f,state:y,onDragStart:()=>Zi(e,this.record.id),onLiveChange:()=>{g(),x()},onCommit:S=>{ve(e,"Move Callout",()=>{const A=H().updateGeometry(this.record.id,{type:"callout",tip:S.tip,anchor:S.anchor});A&&Wi(e,A)})}}),Xi({view:e,recordId:this.record.id,centerEl:w,attached:{live:y,redraw:g,tipDot:v,bubble:f}}))}),{group:a,entityIds:[],dispose:()=>{for(const S of l)try{S()}catch{}},bindGrips:()=>{for(const S of c)S()}}}}class Mu extends Ot{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,u=new D.AcTrHtmlCanvasOverlay({id:`${this.record.id}-hl`,container:c,layer:r,layoutId:o});a.addCanvas(u);const p=()=>{const y=It(u.canvas,c);y&&Co(y,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 D.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 y of l)try{y()}catch{}}}}}class Du extends Ot{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=[],u={start:{...t.start},end:{...t.end}},p=new D.AcTrHtmlDot({id:`${this.record.id}-dot1`,color:i,worldPosition:u.start,layer:r,layoutId:o}),y=new D.AcTrHtmlDot({id:`${this.record.id}-dot2`,color:i,worldPosition:u.end,layer:r,layoutId:o});a.add(p,y);const g=e.container,f=new D.AcTrHtmlCanvasOverlay({id:`${this.record.id}-stroke`,container:g,layer:r,layoutId:o});a.addCanvas(f);let v={start:{...u.start},end:{...u.end}};const w=t.type==="arrow",x=()=>{const C=It(f.canvas,g);if(!C)return;const L=e.worldToScreen(u.start),_=e.worldToScreen(u.end);C.strokeStyle=this.record.style.color,C.lineWidth=n,C.beginPath(),C.moveTo(L.x,L.y),C.lineTo(_.x,_.y),C.stroke(),w&&vs(C,L,_,this.record.style.color)};x(),e.events.viewChanged.addEventListener(x),l.push(()=>e.events.viewChanged.removeEventListener(x));const S=()=>{Zi(e,this.record.id),v={start:{...u.start},end:{...u.end}}},A=()=>{const C=Math.hypot(u.start.x-v.start.x,u.start.y-v.start.y),L=Math.hypot(u.end.x-v.end.x,u.end.y-v.end.y);if(C<1e-9&&L<1e-9){x();return}ve(e,w?"Move Arrow":"Move Line",()=>{const _=H().updateGeometry(this.record.id,w?{type:"arrow",start:{...u.start},end:{...u.end}}:{type:"line",start:{...u.start},end:{...u.end}});_&&Wi(e,_)})};return c.push(()=>{l.push(Mt({view:e,el:p.element,onDragStart:S,onMove:C=>{u.start=C,Je(e,p,C),x()},onCommit:A}),Mt({view:e,el:y.element,onDragStart:S,onMove:C=>{u.end=C,Je(e,y,C),x()},onCommit:A}))}),{group:a,entityIds:[],dispose:()=>{for(const C of l)try{C()}catch{}},bindGrips:()=>{for(const C of c)C()}}}}class Ou extends Ot{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 u,p,y={dx:0,dy:0};t.type==="cloud"?(u={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"?(u={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}):(u={...t.center},p={kind:"circle",center:t.center,radius:t.radius});const g=e.container,f=new D.AcTrHtmlCanvasOverlay({id:`${this.record.id}-shape`,container:g,layer:r,layoutId:o});a.addCanvas(f);const v=()=>{const S=It(f.canvas,g);if(!S)return;const A=this.record.style.color;if(t.type==="cloud")Eu(S,e,t.corner1,t.corner2,A,n,y);else if(t.type==="rect"){const C=Eo(t.corner1,t.corner2).map(L=>({x:L.x+y.dx,y:L.y+y.dy}));ni(S,e,C,A,n,{closed:!0})}else Lo(S,e,{x:t.center.x+y.dx,y:t.center.y+y.dy},t.radius,A,n)};v(),e.events.viewChanged.addEventListener(v),l.push(()=>e.events.viewChanged.removeEventListener(v));const w=new D.AcTrHtmlDot({id:`${this.record.id}-dot`,color:i,worldPosition:u,layer:r,layoutId:o});a.add(w);const x=t.callout?Tu({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(Xi({view:e,recordId:this.record.id,centerEl:w,attached:x,onLiveOffset:(A,C)=>{y={dx:A,dy:C},v()}}))}),{group:a,entityIds:[],dispose:()=>{for(const S of l)try{S()}catch{}},bindGrips:()=>{for(const S of c)S()}}}}class Nu extends Ot{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,u=new D.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(u),l.push(()=>{a.push(Xi({view:e,recordId:this.record.id,centerEl:u}))}),{group:o,entityIds:[],dispose:()=>{for(const p of a)try{p()}catch{}},bindGrips:()=>{for(const p of l)p()}}}}class Bu extends Ot{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 D.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(Fn({view:e,el:c.element,recordId:this.record.id})),l.push(()=>{a.push(Xi({view:e,recordId:this.record.id,centerEl:c}))}),{group:o,entityIds:[],dispose:()=>{for(const u of a)try{u()}catch{}},bindGrips:()=>{for(const u of l)u()}}}}function Ts(s){switch(s.geometry.type){case"text":return new Bu(s);case"line":case"arrow":return new Du(s);case"cloud":case"rect":case"circle":return new Ou(s);case"highlight":return new Mu(s);case"callout":return new Iu(s);case"stamp":case"symbol":return new Nu(s)}}const Yf=Ts;function Pv(s){return s}class Fu{constructor(){this.published=new Set,this.suppressingStoreRemove=!1}republishAll(e){this.clearVisuals(e,{clearStore:!1});for(const t of H().list())this.publish(e,t)}publish(e,t){var f;const i=e,n=H().selectedId===t.id;this.published.has(t.id)&&this.unpublish(e,t.id,{keepInStore:!0});const o=Ts(t).worldDraw(i),{group:a,entityIds:l}=o,c={entityIds:l,dispose:o.dispose},u=H(),p=a.onSelectedChanged;a.onSelectedChanged=(v,w)=>{p==null||p(v,w),v?(u.setSelectedId(w.id),c.entityIds.length>0&&i.highlight(c.entityIds)):(u.selectedId===w.id&&u.setSelectedId(void 0),c.entityIds.length>0&&i.unhighlight(c.entityIds))};const y=a.onVisibleChanged;a.onVisibleChanged=(v,w)=>{y==null||y(v,w);for(const x of c.entityIds)i.setTransientEntityVisible(x,v)};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||u.removeRecord(t.id)},i.htmlTransientManager.add(a),(f=o.bindGrips)==null||f.call(o),i.isHtmlDirty=!0,this.published.add(t.id),n&&(H().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&&!we().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||H().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&&!we().isBusy){ve(e,"Clear Markups",n);return}n()}clearLayout(e,t,i){const n=(i==null?void 0:i.clearStore)!==!1,r=()=>{const o=H().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&&!we().isBusy){ve(e,"Clear Markups",r);return}r()}clearVisualsInternal(e,t){const i=e;this.suppressingStoreRemove=!0;try{i.htmlTransientManager.deselectAll(),i.htmlTransientManager.clear(fn),i.htmlTransientManager.clear(de),this.published.clear()}finally{this.suppressingStoreRemove=!1}t&&H().clear({markDirty:!0}),i.isHtmlDirty=!0}forgetPublished(){this.published.clear()}select(e,t){e.htmlTransientManager.selectGroup(t),H().setSelectedId(t)}focus(e,t){const i=Ts(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)}}function tt(){return mi().presenter}yu((s,e)=>{tt().publish(s,e)});function jo(){we().clear(),Ct().clear(),H().reset(),tt().forgetPublished(),mt()}function Ue(s,e){ve(s,"Create Markup",()=>{H().upsert(e),tt().publish(s,e)})}function ju(s,e,t){const i=H(),n=i.get(e);return!n||!ui(n.geometry)?!1:(ve(s,"Attach Callout",()=>{const r=i.get(e);if(!r||!ui(r.geometry))return;const o={...r,text:t.text,geometry:{...r.geometry,callout:t},updatedAt:new Date().toISOString()};i.upsert(o),tt().publish(s,o)}),!0)}function Is(s,e){const t=H(),i=t.selectedId;i&&ve(s,"Markup Style",()=>{const n=t.updateStyle(i,e);n&&tt().publish(s,n)})}ga(()=>({store:new ba,presenter:new Fu,history:new Ea,sessionUndo:new Ta}));class zu extends R{constructor(){super(),Ge(this)}async execute(e){const t=e.view;tt().clearLayout(t,t.activeLayoutBtrId,{clearStore:!0})}}class Zf extends G{constructor(e,t,i){super(e),this._view=e,this._p1=t,this._p2=t,this._color=i,this._preview=new xe(this._view,`live-markup-arrow-${Date.now()}`,de)}get entity(){return null}update(e){this._p2=e,this._color=ee();const t=Ve(_e());this._preview.acapSetDraw((i,n)=>{lt(i,n,this._p1,this._p2,this._color,t,{arrow:!0})})}end(){super.end(),this._preview.acapDispose()}}class Ru extends R{constructor(){super(),Ge(this)}async execute(e){await et(e,async()=>{const t=ee(),i=new I(h.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(h.t("jig.markup.arrow.secondPoint"));o.useBasePoint=!0,o.jig=new Zf(e.view,r,t);const a=await e.view.editor.getPoint(o);if(a.status!==b.OK)return;const l=a.value,u={...Ke("arrow",e.view,e),type:"arrow",geometry:{type:"arrow",start:{x:r.x,y:r.y},end:{x:l.x,y:l.y}}};Ue(e.view,u)})}}class Xf 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 D.AcTrHtmlDot({id:this._tipDotId,color:n,worldPosition:this._tip,layer:de,layoutId:r}),this._ht.add(this._tipDot),this._bubble=new D.AcTrHtmlCallout({id:this._bubbleId,color:n,text:i,fontSize:Qe(),worldPosition:this._tip,layer:de,layoutId:r}),this._ht.add(this._bubble),this._preview=new xe(this._view,`live-markup-callout-leader-${o}`,de),this._unsubDrawStyle=Cs(()=>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(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=ee(),this._tipDot.setColor(this._color),this._bubble.setColor(this._color),this._bubble.setFontSize(Qe()),this.paintLeader(),this._view.isHtmlDirty=!0}paintLeader(){const e=Ve(_e()),t=this._color,i=this._tip,n=this._anchor;this._preview.acapSetDraw((r,o)=>{lt(r,o,n,i,t,e,{arrow:!0})})}}class Vu extends R{constructor(){super(),Ge(this)}async execute(e){await et(e,async()=>{const t=ee(),i=new I(h.t("jig.markup.callout.tip")),n=await e.view.editor.getPoint(i);if(n.status!==b.OK)return;const r=n.value,o=e.view,a=el(o,{x:r.x,y:r.y});if(a&&ui(a.geometry)){const c=ya(a.geometry),u=await Yi(e,c,{force:!0,previewShape:!1,toward:{x:r.x,y:r.y}});u&&ju(e.view,a.id,u);return}const l=new Xf(e.view,r,"",t);try{const c=new I(h.t("jig.markup.callout.anchor"));c.basePoint=new d.AcGePoint3d(r.x,r.y,r.z??0),c.useBasePoint=!0,c.useDashedLine=!1,c.jig=l;const u=await e.view.editor.getPoint(c);if(u.status!==b.OK)return;const p=u.value,y=await _s(l.capsule),f={...Ke("callout",e.view,e,{text:y||void 0}),type:"callout",geometry:{type:"callout",tip:{x:r.x,y:r.y},anchor:{x:p.x,y:p.y}}};Ue(e.view,f)}finally{l.disposePreview()}})}}function qf(s,e){return _o(s,e)}function Jf(s,e,t){Je(s,e,t)}function Qf(s){return Mt(s)}function eb(s){const{outline:e,...t}=s;return ks({...t,constrainTip:e?i=>ri(e,i):void 0})}class tb extends G{constructor(e,t,i){super(e),this._radius=0,this._view=e,this._center=t,this._color=i,this._preview=new xe(this._view,`live-markup-circle-${Date.now()}`,de)}get entity(){return null}update(e){this._radius=Math.max(e,0),this._color=ee();const t=Ve(_e());this._preview.acapSetDraw((i,n)=>{Lo(i,n,this._center,this._radius,this._color,t)})}end(){super.end(),this._preview.acapDispose()}}class Gu extends R{constructor(){super(),Ge(this)}async execute(e){await et(e,async()=>{const t=ee(),i=await Es(e,"jig.markup.circle.center");if(!i)return;const n=new ke(h.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 tb(e.view,i,t);const r=await e.view.editor.getDistance(n);if(r.status!==b.OK)return;const o=r.value,a=await Yi(e,{kind:"circle",center:{x:i.x,y:i.y},radius:o}),c={...Ke("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}};Ue(e.view,c)})}}function ib(s,e,t){return Ls($i(s,e,t))}class nb extends G{constructor(e,t,i){super(e),this._view=e,this._first=t,this._second=t,this._color=i,this._preview=new xe(this._view,`live-markup-cloud-${Date.now()}`,de)}get entity(){return null}update(e){this._second=e,this._color=ee();const t=Ve(_e()),i=ib(this._first,this._second,this._view);this._preview.acapSetDraw((n,r)=>{ni(n,r,i,this._color,t,{closed:!0})})}end(){super.end(),this._preview.acapDispose()}}class Ku extends R{constructor(){super(),Ge(this)}async execute(e){await et(e,async()=>{const t=ee(),i=await Es(e,"jig.markup.cloud.firstCorner");if(!i)return;const n=new I(h.t("jig.markup.cloud.secondCorner"));n.useBasePoint=!0,n.jig=new nb(e.view,i,t);const r=await e.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=await Yi(e,{kind:"cloud",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y}}),c={...Ke("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}};Ue(e.view,c)})}}class sb extends G{constructor(e,t,i){super(e),this._view=e,this._first=t,this._second=t,this._colorCss=Dt(i),this._preview=new xe(this._view,`live-markup-highlight-${Date.now()}`,de)}get entity(){return null}update(e){this._second=e,this._colorCss=Dt(ee());const t=Ve(_e());this._preview.acapSetDraw((i,n)=>{yf(i,n,this._first,this._second,this._colorCss,t)})}end(){super.end(),this._preview.acapDispose()}}class Uu extends R{constructor(){super(),Ge(this)}async execute(e){await et(e,async()=>{const t=ee(),i=Dt(t),n=new I(h.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(h.t("jig.markup.highlight.secondCorner"));a.useBasePoint=!0,a.jig=new sb(e.view,o,t);const l=await e.view.editor.getPoint(a);if(l.status!==b.OK)return;const c=l.value,p={...Ke("highlight",e.view,e),type:"highlight",style:{color:i,lineWeight:_e()},geometry:{type:"highlight",corner1:{x:o.x,y:o.y},corner2:{x:c.x,y:c.y}}};Ue(e.view,p)})}}const rb=["text","line","arrow","cloud","rect","circle","highlight","callout","stamp","symbol"];function oi(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function Oe(s){return oi(s)&&typeof s.x=="number"&&typeof s.y=="number"}function Hu(s){return!(!oi(s)||!Oe(s.tip)||!Oe(s.anchor)||s.text!==void 0&&typeof s.text!="string")}function ob(s){return typeof s=="string"&&wa.includes(s)}function ab(s){return typeof s=="string"&&rb.includes(s)}function lb(s){if(!oi(s)||typeof s.id!="string"||!ab(s.type)||!oi(s.style)||typeof s.style.color!="string"||!oi(s.geometry)||s.geometry.type!==s.type||!ob(s.status))return;const e=s.geometry;switch(s.type){case"text":if(!Oe(e.position))return;break;case"line":case"arrow":if(!Oe(e.start)||!Oe(e.end))return;break;case"cloud":case"rect":case"highlight":if(!Oe(e.corner1)||!Oe(e.corner2)||(s.type==="cloud"||s.type==="rect")&&e.callout!==void 0&&!Hu(e.callout))return;break;case"circle":if(!Oe(e.center)||typeof e.radius!="number"||!(e.radius>0)||e.callout!==void 0&&!Hu(e.callout))return;break;case"callout":if(!Oe(e.tip)||!Oe(e.anchor))return;break;case"stamp":if(!Oe(e.position)||typeof e.stampId!="string")return;break;case"symbol":if(!Oe(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 Wu(s){let e;try{e=JSON.parse(s)}catch{throw new Error("Invalid markup sidecar: not JSON")}if(!oi(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=lb(i);n&&t.push(n)}return{version:1,drawingName:typeof e.drawingName=="string"?e.drawingName:void 0,markups:t}}function $u(s){return`${JSON.stringify(s,null,2)}
575
+ `}function Yu(s){return s?`${s.replace(/\.(dwg|dxf)$/i,"")}.markup.json`:"drawing.markup.json"}function cb(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 db(){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 Zu extends R{constructor(){super(),this.mode=z.Read,this.recordsUndoStack=!1}async execute(e){const t=H();t.drawingName||(t.drawingName=e.doc.fileName||e.doc.docTitle);const i=$u(t.toSidecar());cb(Yu(t.drawingName),i),t.markClean()}}class Xu extends R{constructor(){super(),this.mode=z.Review,this.recordsUndoStack=!1}async execute(e){new ue(h.t("jig.markup.import.chooseFile"));const t=await db();if(t==null)return;let i;try{i=Wu(t)}catch(r){console.error(r);return}const n=H();ve(e.view,"Import Markups",()=>{n.replaceAll(i.markups,i.drawingName),tt().republishAll(e.view)})}}class ub 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 D.AcTrHtmlBadge({id:this._badgeId,color:i,text:n,worldPosition:t,layer:de,layoutId:this._view.activeLayoutBtrId}),this._badge.object.visible=!1,this._ht.add(this._badge),this._preview=new xe(this._view,`live-markup-line-stroke-${Date.now()}`,de)}get entity(){return null}update(e){this._p2=e,this._color=ee(),this._badge.setColor(this._color);const t=Ve(_e());this._preview.acapSetDraw((i,n)=>{lt(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 qu extends R{constructor(){super(),Ge(this)}async execute(e){await et(e,async()=>{const t=ee(),i=new I(h.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(h.t("jig.markup.line.secondPoint"));o.useBasePoint=!0,o.jig=new ub(e.view,r,t,"Line");const a=await e.view.editor.getPoint(o);if(a.status!==b.OK)return;const l=a.value,u={...Ke("line",e.view,e),type:"line",style:{color:Dt(t),lineWeight:_e()},geometry:{type:"line",start:{x:r.x,y:r.y},end:{x:l.x,y:l.y}}};Ue(e.view,u)})}}class hb extends G{constructor(e,t,i){super(e),this._view=e,this._first=t,this._second=t,this._color=i,this._preview=new xe(this._view,`live-markup-rect-${Date.now()}`,de)}get entity(){return null}update(e){this._second=e,this._color=ee();const t=Ve(_e()),i=Eo(this._first,this._second);this._preview.acapSetDraw((n,r)=>{ni(n,r,i,this._color,t,{closed:!0})})}end(){super.end(),this._preview.acapDispose()}}class Ju extends R{constructor(){super(),Ge(this)}async execute(e){await et(e,async()=>{const t=ee(),i=await Es(e,"jig.markup.rect.firstCorner");if(!i)return;const n=new I(h.t("jig.markup.rect.secondCorner"));n.useBasePoint=!0,n.jig=new hb(e.view,i,t);const r=await e.view.editor.getPoint(n);if(r.status!==b.OK)return;const o=r.value,a=await Yi(e,{kind:"rect",corner1:{x:i.x,y:i.y},corner2:{x:o.x,y:o.y}}),c={...Ke("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}};Ue(e.view,c)})}}const Qu=new Set(["approved","rejected","revised","for-review","custom"]);class eh extends R{constructor(){super(),Ge(this)}async execute(e){await et(e,async()=>{const t=new ue(h.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"||!Qu.has(n))&&(r=await Fo(e,"jig.markup.stamp.imageUrl",""));const o=await Fo(e,"jig.markup.stamp.caption",""),a=new I(h.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"&&!Qu.has(n)){const f={...Ke("symbol",e.view,e,{text:o||void 0}),type:"symbol",style:Ps(),geometry:{type:"symbol",position:{x:c.x,y:c.y},symbolId:n,imageUrl:r||void 0}};Ue(e.view,f);return}const y={...Ke("stamp",e.view,e,{text:o||void 0}),type:"stamp",style:Ps(),geometry:{type:"stamp",position:{x:c.x,y:c.y},stampId:n,imageUrl:r||void 0}};Ue(e.view,y)})}}class th extends R{constructor(){super(),Ge(this)}async execute(e){await et(e,async()=>{const t=new I(h.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 D.AcTrHtmlBadge({id:o,color:ee(),text:"",fontSize:Qe(),worldPosition:n,layer:de,layoutId:r.activeLayoutBtrId});r.htmlTransientManager.add(a),r.isHtmlDirty=!0;const l=Cs(()=>{a.setColor(ee()),a.setFontSize(Qe()),r.isHtmlDirty=!0});let c="Note";try{c=await _s({textElement:a.element,element:a.element},{multiline:!1})||"Note"}finally{l(),r.htmlTransientManager.remove(o),r.isHtmlDirty=!0}const p={...Ke("text",r,e,{text:c}),type:"text",geometry:{type:"text",position:{x:n.x,y:n.y}}};Ue(e.view,p)})}}let zo=!0;function pb(){return zo}function ih(s,e){zo=e,s.htmlTransientManager.setVisible(e,fn),s.htmlTransientManager.setVisible(e,de),s.isHtmlDirty=!0}class nh extends R{constructor(){super(),this.mode=z.Review,this.recordsUndoStack=!1}async execute(e){const t=e.view;ih(t,!zo)}}class Ro extends Zt{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=Jn(t,n.copyFactor,this.copyCount,this._fitMode);return{objectId:n.entity.objectId,matrix:new d.AcGeMatrix3d().makeTranslation(r.x,r.y,r.z)}})}}const un=class un extends R{constructor(){super(),this.mode=z.Write}addKeyword(e,t){e.keywords.add(h.t(`jig.copy.keywords.${t}.display`),h.t(`jig.copy.keywords.${t}.global`),h.t(`jig.copy.keywords.${t}.local`))}computeDisplacement(e,t){return new d.AcGePoint3d(t).sub(e)}scaleDisplacement(e,t,i,n){return Jn(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(u=>u.clone()).filter(u=>!!u),l=this.scaleDisplacement(t,o,i,n),c=new d.AcGeMatrix3d().makeTranslation(l.x,l.y,l.z);a.forEach(u=>u.transformBy(c)),r.push(...a)}return r}async promptCopyMode(e){const t=new re(h.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 Gr(h.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(h.t("jig.copy.arraySecondPointOrFit"));this.addKeyword(l,"fit"),l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=i,l.jig=new Ro(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 u=new I(h.t("jig.copy.arrayFitSecondPoint"));u.useBasePoint=!0,u.useDashedLine=!0,u.basePoint=i,u.jig=new Ro(e.view,t,i,a,!0);const p=await k.instance.editor.getPoint(u);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 I(h.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 Ro(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 Qn(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=un._defaultMode,o,a=!1;for(;!o;){const l=new I(h.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 u=c.stringResult??"";if(u==="Displacement"){o=new d.AcGePoint3d(0,0,0),a=!0;break}if(u==="Multiple"){r="Multiple";continue}if(u!=="Mode"){t.clear();return}const p=await this.promptCopyMode(r);if(!p){t.clear();return}r=p,un._defaultMode=p}await this.executeCopyLoop(e,n,o,r,a),t.clear()}};un._defaultMode="Multiple";let Ms=un;class sh extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=e.view.selectionSet,i=await Tc(e,"erase");i&&(e.doc.entityService.eraseEntities(i),t.clear())}}class rh extends R{async execute(e){const t=e.view.selectionSet;let i=t.count>0?t.ids:[];if(i.length===0){const r=new _t(h.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=dp(e,i);n>0&&this.showMessage(`${n} ${h.t("jig.hideobjects.hidden")}`,"success")}}class oh extends Zt{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 ah extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=e.view.selectionSet,i=await Qn(e,{promptKey:"move"});if(!i)return;const{entities:n}=i;let r,o;const a=y=>{y.keywords.add(h.t("jig.move.keywords.displacement.display"),h.t("jig.move.keywords.displacement.global"),h.t("jig.move.keywords.displacement.local"))};class l{constructor(g){this.machine=g}buildPrompt(){const g=new I(h.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 u),"continue"):g.status===b.Keyword&&g.stringResult==="Displacement"?(this.machine.setState(new u),"continue"):"finish"}}class c{constructor(g){this.machine=g}buildPrompt(){const g=new I(h.t("jig.move.secondPointOrDisplacement"));return a(g),r&&(g.useBasePoint=!0,g.useDashedLine=!0,g.basePoint=r,g.jig=new oh(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 u),"continue"):"finish"}}class u{buildPrompt(){const g=new I(h.t("jig.move.displacement"));return g.useBasePoint=!0,g.useDashedLine=!0,g.basePoint=new d.AcGePoint3d(0,0,0),g.jig=new oh(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 Xe;if(p.setState(new l(p)),await p.run(y=>k.instance.editor.getPoint(y)),!o){t.clear();return}e.doc.entityService.translateEntities(n,o),t.clear()}}function mb(s){return s instanceof d.AcDbCurve}function lh(s,e,t){try{const i=s.getOffsetSideAtPoint(t),n=s.getOffsetCurves(e*i);return n.forEach(r=>Jr.copyDisplayTraits(s,r)),n}catch{return[]}}class yb 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=lh(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 qi extends R{constructor(){super(),this.mode=z.Write}async execute(e){const t=(u,p="info")=>{this.showMessage(u,p)},i=e.doc.database.tables.blockTable;let n,r;class o{constructor(p){this.machine=p}buildPrompt(){const p=qi._lastDistance,y=new ke(h.t("jig.offset.distance"));return y.useBasePoint=!1,y.useDashedLine=!0,y.allowZero=!1,y.allowNegative=!1,p!=null&&(y.defaultValue=p,y.useDefaultValue=!0,y.allowNone=!0),y}handleResult(p){return!(p instanceof Pe)||p.status!==b.OK||p.value==null?"finish":!Number.isFinite(p.value)||d.AcGeTol.isNonPositive(p.value)?(t(h.t("jig.offset.invalidDistance"),"warning"),"finish"):(n=p.value,qi._lastDistance=p.value,this.machine.setState(new a(this.machine)),"continue")}}class a{constructor(p){this.machine=p}buildPrompt(){const p=new Ze(h.t("jig.offset.selectObject"));return p.allowNone=!0,p.allowObjectOnLockedLayer=!0,p.setRejectMessage(h.t("jig.offset.invalidSelection")),p}handleResult(p){if(!(p instanceof $n)||p.status===b.None||p.status!==b.OK||!p.objectId)return"finish";const y=e.doc.database.openEntityForRead(p.objectId);return mb(y)?(r=y,this.machine.setState(new l(this.machine)),"continue"):(t(h.t("jig.offset.invalidSelection"),"warning"),"continue")}}class l{constructor(p){this.machine=p}buildPrompt(){const p=new I(h.t("jig.offset.sidePoint"));if(p.allowNone=!0,p.disableOSnap=!0,r&&n!=null){const y=new yb(e.view,r,n);y.update({...e.view.curPos,z:0}),y.render(),p.jig=y}return p}handleResult(p){if(!(p instanceof Zn)||p.status!==b.OK||!p.value||!r||n==null)return"finish";const y=lh(r,n,new d.AcGePoint3d(p.value));return y.length===0?t(h.t("jig.offset.offsetFailed"),"warning"):i.modelSpace.appendEntity(y),r=void 0,this.machine.setState(new a(this.machine)),"continue"}}const c=new Xe;c.setState(new o(c)),await c.run(u=>u instanceof ke?k.instance.editor.getDistance(u):u instanceof Ze?k.instance.editor.getEntity(u):k.instance.editor.getPoint(u))}}class Ds extends yc{}class ch extends Zt{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,Xt(this._basePoint,t)),this._lastAngleRad=t;return}this._lastAngleRad=t,super.update(e)}buildTransforms(e){const t=(e-this._referenceAngleDeg)*Math.PI/180,i=Xt(this._basePoint,t);return this.previewEntries.map(n=>({objectId:n.entity.objectId,matrix:i}))}}const ia=class ia extends R{constructor(){super(),this.mode=z.Write}addKeyword(e,t){e.keywords.add(h.t(`jig.rotate.keywords.${t}.display`),h.t(`jig.rotate.keywords.${t}.global`),h.t(`jig.rotate.keywords.${t}.local`))}warnInvalidInput(e){this.notify(h.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 Ce(h.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 Ds(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(h.t("jig.rotate.firstReferencePoint"));o.jig=new Ds(e.view,t);const a=await k.instance.editor.getPoint(o);if(a.status!==b.OK)return;const l=new I(h.t("jig.rotate.secondReferencePoint"));l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new d.AcGePoint3d(a.value),l.jig=new Ds(e.view,t);const c=await k.instance.editor.getPoint(l);if(c.status!==b.OK)return;const u=this.computeAngleDeg(a.value,c.value);if(u==null){this.warnInvalidInput("referencePoints");continue}return u}return}}async promptRotationAngle(e,t,i){let n=!1;for(;;){const r=new Ce(h.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 ch(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 Ce(h.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 ch(e.view,t,i,l);const u=await k.instance.editor.getAngle(c);return u.status!==b.OK?void 0:{copyMode:n,angleRad:((u.value??0)-l)*Math.PI/180}}}async execute(e){const t=e.view.selectionSet,i=await Qn(e,{promptKey:"rotate"});if(!i)return;const{entities:n}=i,r=new I(h.t("jig.rotate.basePoint"));r.jig=new Ds(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=Xt(a,l.angleRad),u=e.doc.entityService;l.copyMode?u.cloneAndTransform(n,c):u.transformEntities(n,c),t.clear()}};ia.createRotationMatrix=Xt;let Os=ia;class dh extends R{async execute(e){const t=up(e);if(t>0){this.showMessage(`${t} ${h.t("jig.hideobjects.restored")}`,"success");return}this.showMessage(h.t("jig.hideobjects.nothingToRestore"),"info")}}const Ne=class Ne{constructor(e){this.disposed=!1,Ne.ensureStyles();const t=e.host??document.body,i=e.titleId??`ml-ui-dialog-title-${Ne.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",Or(e.theme??Nr(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(Ne.stylesInjected)return;if(document.getElementById(Ne.styleId)){Ne.stylesInjected=!0;return}const e=document.createElement("style");e.id=Ne.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),Ne.stylesInjected=!0}};Ne.styleId="ml-ui-dialog-styles",Ne.stylesInjected=!1,Ne.nextTitleId=0;let Ns=Ne;const me=class me extends Ns{constructor(e){super({host:e,title:h.t("main.about.title"),closeLabel:h.t("main.about.close"),titleId:"ml-ui-about-title",dialogClassName:"ml-ui-about-dialog"}),me.ensureAboutStyles(),this.buildContent()}static open(e=document.body){var i;(i=me.openInstance)==null||i.close();const t=new me(e);return me.openInstance=t,t.show()}close(){me.openInstance===this&&(me.openInstance=null),super.close()}buildContent(){const e=ca({className:"ml-ui-about-brand",iconSize:"56px"}),t=document.createElement("div");t.className="ml-ui-about-product",t.textContent=h.t("main.about.product");const i=document.createElement("div");i.className="ml-ui-about-tagline",i.textContent=h.t("main.about.tagline");const n=document.createElement("div");n.className="ml-ui-about-links",n.appendChild(this.createLink(h.t("main.about.website"),oa)),n.appendChild(this.createLink(h.t("main.about.docs"),aa)),n.appendChild(this.createLink(h.t("main.about.repository"),la));const r=document.createElement("div");r.className="ml-ui-about-copyright",r.textContent=h.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=h.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(me.aboutStylesInjected)return;if(document.getElementById(me.aboutStyleId)){me.aboutStylesInjected=!0;return}const e=document.createElement("style");e.id=me.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),me.aboutStylesInjected=!0}};me.aboutStyleId="ml-ui-about-dialog-styles",me.aboutStylesInjected=!1,me.openInstance=null;let Bs=me;class uh extends R{constructor(){super(...arguments),this.recordsUndoStack=!1}async execute(e){var i;const t=((i=e.view)==null?void 0:i.container)??document.body;await Bs.open(t)}}let Ji=null;ie.on("font-file-selected",({file:s})=>{Ji==null||Ji(s),Ji=null});function gb(){return new Promise(s=>{Ji=s,ie.emit("cache-font",{})})}class Qi extends R{static async cacheFontFile(e,t){const i=(t==null?void 0:t.notify)??!0,n=new Qi;try{const r=await sn.cacheFont(e,void 0,t==null?void 0:t.aliases);return i&&(r.status==="Success"?n.notify(`${h.t("main.message.fontCached")}: ${r.fontName}`,"success"):n.notify(`${h.t("main.message.fontCacheFailed")}: ${e.name}`,"error")),r}catch{return i&&n.notify(`${h.t("main.message.fontCacheFailed")}: ${e.name}`,"error"),{fontName:"",url:"",status:"FailedToLoad"}}}async execute(e){const t=await gb();t&&await Qi.cacheFontFile(t)}}class hh extends R{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(u=>(o[0]=u.line.indexed.geometrySize/1024,o[1]=u.line.nonIndexed.geometrySize/1024,o[2]=u.mesh.indexed.geometrySize/1024,o[3]=u.mesh.nonIndexed.geometrySize/1024,o[4]=u.point.indexed.geometrySize/1024,o[5]=u.point.nonIndexed.geometrySize/1024,o[6]=u.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+=u.unbatched.count,{name:u.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":u.unbatched.count,"unbatched line":u.unbatched.byType.line,"unbatched mesh":u.unbatched.byType.mesh,"unbatched point":u.unbatched.byType.point,"unbatched other":u.unbatched.byType.other,"total geo (KB)":(u.summary.totalGeometrySize/1024).toFixed(1),"total mapping (KB)":(u.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 ph(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 fb(){const e=performance.memory;if(e)return{usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit}}function mh(s){return Object.entries(s).map(([e,t])=>({name:e,count:t.count,estimatedBytes:t.bytes})).sort((e,t)=>t.estimatedBytes-e.estimatedBytes)}function bb(s){const e=d.acdbEstimateDatabaseMemory(s);return{estimate:e,categories:mh(e.byCategory),entitiesByType:mh(e.byEntityType),estimatedBytes:e.totalBytes,entityCount:e.entityCount,objectCount:e.objectCount,isEstimated:!0}}function wb(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 yh(s,e){try{for(const t of e.tables.blockTable.newIterator())if(t.objectId===s)return String(t.name??s)}catch{}return s}function gh(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 vb(){const s=O.FontManager.instance.missedFonts??{},e=Object.keys(s),t=await D.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:gh(t).length,indexedDbBytes:t.indexedDbFontCache.totalBytes,indexedDbFontCount:t.indexedDbFontCache.fontCount,fonts:gh(t),report:t,isEstimated:!0}}async function fh(s,e){const t=s.stats,i=[...s.cadScene.layouts.entries()],n=i.map(([S])=>yh(S,e)),r=wb(t,n),o=i.map(([S,A])=>({layoutKey:yh(S,e),stats:A.spatialIndexStats})),a=o.reduce((S,A)=>S+A.stats.estimatedBytes,0),l=o.reduce((S,A)=>S+(A.stats.rootItemCount??A.stats.itemCount),0),c=o.reduce((S,A)=>S+(A.stats.childItemCount??0),0),u=bb(e),p=s.renderer.styleManager.getStats(),y=await vb(),g=fb(),f=t.summary.totalSize.geometry,v=t.summary.totalSize.mapping,w=[`${y.loadedFontCount} loaded`];y.missedCount>0&&w.push(`${y.missedCount} missed`);const x=[{id:"geometry",bytes:f,isEstimated:!1,detail:`${t.summary.entityCount} entities`},{id:"mapping",bytes:v,isEstimated:!0,detail:"batch slot metadata"},{id:"spatial",bytes:a,isEstimated:!0,detail:`${l} root / ${c} child items`},{id:"dataModel",bytes:u.estimatedBytes,isEstimated:!0,detail:`${u.entityCount} entities`},{id:"materials",bytes:p.totalEstimatedBytes,isEstimated:!0,detail:`${p.totalCount} cached`},{id:"fonts",bytes:y.estimatedBytes,isEstimated:!0,detail:w.join(" · ")}];return g&&x.unshift({id:"heap",bytes:g.usedJSHeapSize,isEstimated:!0,detail:`limit ${ph(g.jsHeapSizeLimit)}`}),{collectedAt:Date.now(),heap:g,summary:x,geometry:{scene:t,layers:r},spatial:{layouts:o,totalEstimatedBytes:a,totalRootItems:l,totalChildItems:c},dataModel:u,materials:p,fonts:y}}class kb{static collect(e,t){return fh(e,t)}}class bh extends R{async execute(e){ie.emit("open-file",{})}}class wh extends R{async execute(e){await k.instance.closeDocument()}}class vh extends R{async execute(e){if(!await k.instance.newDocument())throw new Error("Failed to create new drawing")}}class kh extends R{async execute(){k.instance.regen()}}class xh extends R{async execute(e){e.view.mode=fe.SELECTION,e.view.setCursor(Ie.Crosshair)}}class Sh extends R{constructor(){super(),this.mode=z.Review}async execute(e){const t=d.AcDbSysVarManager.instance(),i=t.getVar(this.globalName,e.doc.database),n=h.t("jig.sysvar.prompt").trim(),r=new ue(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 Ah extends R{async execute(e){const t=e.doc.database,i=e.view,n=i.activeLayoutBtrId===i.modelSpaceBtrId,r=Sr(n),o=d.AcDbSysVarManager.instance();if(!o.getDescriptor(r))return;const l=o.getVar(r,t);o.setVar(r,vl(l),t)}}class Ch extends R{constructor(){super(),this.globalName="undo",this.localName="Undo",this.recordsUndoStack=!1}async execute(e){const t=Ct().undo(e.doc.database);if(!t){const i=h.sysCmdKey(this.globalName,"nothingToUndo");this.showMessage(h.sysCmd(this.globalName,"nothingToUndo"),"info",i);return}t==="markup"&&tt().republishAll(e.view),mt()}}class Ph extends R{constructor(){super(),this.globalName="redo",this.localName="Redo",this.recordsUndoStack=!1}async execute(e){const t=Ct().redo(e.doc.database);if(!t){const i=h.sysCmdKey(this.globalName,"nothingToRedo");this.showMessage(h.sysCmd(this.globalName,"nothingToRedo"),"info",i);return}t==="markup"&&tt().republishAll(e.view),mt()}}class Nt extends R{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){Nt.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 I(h.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 Un(h.t("jig.zoom.firstCorner"),h.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(h.t("jig.zoom.centerPoint")),i=await k.instance.editor.getPoint(t);if(i.status!==b.OK||!i.value)return;const n=new ue(h.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,u=a*l/2,p=new d.AcGeBox2d().expandByPoint({x:i.value.x-u,y:i.value.y-c}).expandByPoint({x:i.value.x+u,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},u=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(u,1)}runPrevious(e){if(!Nt.previousViewBox)return;const t=this.captureCurrentViewBox(e);e.view.zoomTo(Nt.previousViewBox,1),Nt.previousViewBox=t}async execute(e){const t=new I(h.t("jig.zoom.mainPrompt"));t.allowNone=!0,t.keywords.add(h.t("jig.zoom.keywords.all.display"),h.t("jig.zoom.keywords.all.global"),h.t("jig.zoom.keywords.all.local")),t.keywords.add(h.t("jig.zoom.keywords.center.display"),h.t("jig.zoom.keywords.center.global"),h.t("jig.zoom.keywords.center.local")),t.keywords.add(h.t("jig.zoom.keywords.extents.display"),h.t("jig.zoom.keywords.extents.global"),h.t("jig.zoom.keywords.extents.local")),t.keywords.add(h.t("jig.zoom.keywords.previous.display"),h.t("jig.zoom.keywords.previous.global"),h.t("jig.zoom.keywords.previous.local")),t.keywords.add(h.t("jig.zoom.keywords.scale.display"),h.t("jig.zoom.keywords.scale.global"),h.t("jig.zoom.keywords.scale.local")),t.keywords.add(h.t("jig.zoom.keywords.window.display"),h.t("jig.zoom.keywords.window.global"),h.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 ue(h.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 _h extends R{async execute(e){e.view.mode=fe.PAN,e.view.setCursor(Ie.Grab)}}class Lh{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}get context(){return this._context}setContext(e){this._context=e}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 y=p.default,g;if(!y){const v=c.replace(/\.(js|ts)$/,"");g=v.split(/[-_]/).map(w=>w.charAt(0).toUpperCase()+w.slice(1).toLowerCase()).join(""),y=p[g]||p.Plugin||p[v]}if(!y){const v=g||"Plugin";throw new Error(`No plugin export found in ${c}. Expected default export, or named export 'Plugin' or '${v}'.`)}let f;if(typeof y=="function"?y.prototype&&y.prototype.onLoad?f=new y:f=y():f=y,!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(u){const p=u instanceof Error?u:new Error(String(u));if(o.push({name:c,error:p}),!i)throw p}return{loaded:r,failed:o}}}const xb=new Set(["measuredistance","measurearea","measureangle","measurearc","measurepoint"]),Sb=new Set(["markuptext","markupline","markuparrow","markupcloud","markuprect","markupcircle","markuphighlight","markupcallout","markupstamp"]);let Eh,Vo=!1;const Go=new Set;function Th(s){const e=s==null?void 0:s.trim().toLowerCase();if(e){if(xb.has(e))return"measure";if(Sb.has(e))return"markup"}}function Ih(s){if(s.commandKind)return s.commandKind;if(!(s.markupSelected&&s.measurementSelected)){if(s.markupSelected)return"markup";if(s.measurementSelected)return"measure"}}function Ab(s){Eh=s}function Mh(){return Eh??pe.instance.isShowRibbon}function Dh(s,e=Mh()){return s!=null&&!e}function Cb(){return Vo}function Pb(s){return Go.add(s),()=>{Go.delete(s)}}function Ko(s){if(Vo!==s){Vo=s;for(const e of Go)e(s)}}const _b=[10,12,13,14,16,18,20,24,28,32],Oh="ml-draw-style-toolbar-styles",Lb=`
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 Nh(s){const e=new d.AcCmColor;return e.colorIndex=s,e}function Eb(s){return Nh(s).cssColor||"#ffffff"}function Bh(s){if(s.isByACI&&s.colorIndex!=null&&s.colorIndex>=1)return s.colorIndex}const Tb=Array.from({length:9},(s,e)=>e+1),Ib=Array.from({length:240},(s,e)=>e+10),Mb=Array.from({length:6},(s,e)=>e+250);function Db(){return Array.from(new Set(Object.values(d.AcGiLineWeight).filter(s=>typeof s=="number"&&s>0))).sort((s,e)=>s-e)}function Fh(s){return`${(s/100).toFixed(2)} mm`}function jh(s){return Math.max(1,Math.min(6,s/40))}function Ob(s,e){const t="ml-draw-style-toolbar",i=Db();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 u=document.createElement("div");u.className=`${t}__lineweight-menu`,u.setAttribute("role","listbox");const p=w=>{a.style.setProperty("--ml-lineweight-height",`${jh(w)}px`),l.textContent=Fh(w)},y=w=>{u.querySelectorAll(`.${t}__lineweight-item`).forEach(x=>{const S=x;S.classList.toggle("is-selected",S.dataset.value===String(w))})},g=()=>{n=!1,u.classList.remove("is-open"),o.setAttribute("aria-expanded","false")},f=()=>{e(),n=!0,u.classList.add("is-open"),o.setAttribute("aria-expanded","true")},v=w=>{const x=document.createElement("button");x.type="button",x.className=`${t}__lineweight-item`,x.dataset.value=String(w),x.setAttribute("role","option");const S=document.createElement("span");S.className=`${t}__lineweight-preview`,S.style.setProperty("--ml-lineweight-height",`${jh(w)}px`);const A=document.createElement("span");A.className=`${t}__lineweight-text`,A.textContent=Fh(w),x.append(S,A),x.addEventListener("click",C=>{C.preventDefault(),C.stopPropagation(),p(w),y(w),g(),s(w)}),u.appendChild(x)};for(const w of i)v(w);return o.addEventListener("click",w=>{w.preventDefault(),w.stopPropagation(),n?g():f()}),r.append(o,u),p(i[0]??25),y(i[0]??25),{root:r,setValue:w=>{w>0&&(u.querySelector(`[data-value="${w}"]`)||v(w),p(w),y(w))},setTitle:w=>{o.title=w},close:g,isOpen:()=>n,contains:w=>!!w&&r.contains(w)}}function Nb(){if(typeof document>"u")return;let s=document.getElementById(Oh);s||(s=document.createElement("style"),s.id=Oh,document.head.appendChild(s)),s.textContent=Lb}class zh{constructor(e){this.view=e,this.colorPanelOpen=!1,Nb(),this.root=document.createElement("div"),this.root.className="ml-draw-style-toolbar",this.root.setAttribute("role","toolbar"),Or(Nr(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(Ib,"ml-draw-style-toolbar__aci-large")),this.colorPanel.appendChild(this.createAciPalette(Tb,"ml-draw-style-toolbar__aci-small")),this.colorPanel.appendChild(this.createAciPalette(Mb,"ml-draw-style-toolbar__aci-gray")),this.colorWrap.appendChild(this.swatch),this.colorWrap.appendChild(this.colorPanel),this.root.appendChild(this.colorWrap),this.lineWeightPicker=Ob(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=Th(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()},pe.instance.events.modified.addEventListener(this.onSettingsModified),this.unsubscribeMarkupStore=H().subscribe(()=>{this.refreshKindAndVisibility()}),this.unsubscribeMeasurementSelection=Ua(()=>{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),pe.instance.events.modified.removeEventListener(this.onSettingsModified),this.unsubscribeMarkupStore(),this.unsubscribeMeasurementSelection(),this.root.remove(),Ko(!1)}refreshKindAndVisibility(){this.kind=Ih({commandKind:this.commandKind,markupSelected:H().selectedId!=null,measurementSelected:Ga()!=null}),this.refreshVisibility()}refreshVisibility(){const e=Dh(this.kind);this.root.classList.toggle("is-visible",e),Ko(e),e?(this.relabel(),this.syncFromSession()):(this.hideColorPanel(),this.lineWeightPicker.close())}relabel(){this.swatch.title=h.t("main.drawStyle.color"),this.lineWeightPicker.setTitle(h.t("main.drawStyle.lineWeight")),this.fontSizeSelect.title=h.t("main.drawStyle.fontSize")}syncFromSession(){if(this.kind==="measure"){const r=Ka(),o=d.acdbHostApplicationServices().workingDatabase,a=(r==null?void 0:r.color)??(o?Be(o):ur("#7b8794")),l=(r==null?void 0:r.lineWeight)??st(),c=(r==null?void 0:r.fontSize)??Fe();this.paint(a,l,c);return}const e=H().selectedId?H().get(H().selectedId):void 0,t=e?Bo(e.style.color):ee(),i=(e==null?void 0:e.style.lineWeight)??_e(),n=(e==null?void 0:e.style.fontSize)??Qe();this.paint(t,i,n)}paint(e,t,i){const n=Se(e);this.swatchFill.style.background=n,this.markSelectedAci(Bh(e)),this.lineWeightPicker.setValue(t);const r=new Set(_b);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=Se(e),this.markSelectedAci(Bh(e)),this.kind==="measure"){Ca(e),kn(this.view,{color:e});return}vu(e),Is(this.view,{color:Dt(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=Eb(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.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"){Pa(e),kn(this.view,{lineWeight:e});return}ku(e),Is(this.view,{lineWeight:e})}applyFontSize(e){if(this.kind==="measure"){_a(e),kn(this.view,{fontSize:e});return}xu(e),Is(this.view,{fontSize:e})}}function Uo(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 Rh(s){const e=s.trim().toUpperCase();return e==="QUIT"||e==="EXIT"}const dt=class dt{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},dt.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}setHost(e){return this.options.host===e?this:(this.options.host=e,getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(this.root),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=Xs({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 u=document.createElement("div");u.className="ml-ccl-wrapper",u.appendChild(n),u.appendChild(c),i.appendChild(u),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(dt.styleId)){dt.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=dt.styleId,t.textContent=e,document.head.appendChild(t),dt.stylesInjected=!0}};dt.styleId="ml-ccl-loader-styles",dt.stylesInjected=!1;let en=dt;class Bb{constructor(e){this._refCount=0,this._message="",this._progress=new en({host:e}),this._progress.hide()}setHost(e){this._progress.setHost(e)}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){ie.emit("busy-indicator",{visible:e,message:e&&this._message||void 0})}}class Fs{constructor(e,t){this.overlays=new Map,this.id=e,this.context=t}get doc(){return this.context.doc}}const js="Untitled";class zs{constructor(){this._fileName="",this._docTitle="",this._openMode=z.Write,this._hiddenObjects=new Set,this._database=new d.AcDbDatabase,this.docTitle=js,this._openMode=z.Write}async openUri(e,t){this._uri=e,this._openMode=(t==null?void 0:t.mode)??z.Read,this._fileName=this.getFileNameFromUri(e);const i=this._database.lastOpenError;let n=!0;try{const r={...t,readOnly:this._openMode===z.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)??z.Read;const r=this._database.lastOpenError;try{const a=(o=e.split(".").pop())==null?void 0:o.toLocaleLowerCase(),l={...i,readOnly:this._openMode===z.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=js}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}get isReusableUntitled(){if(this._uri||this._fileName||this._docTitle!==js)return!1;const e=this._database.tables.blockTable.modelSpace;return!(e&&e.newIterator().count>0)}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 ne(this._database)),this._layerService}get entityService(){return this._entityService||(this._entityService=new Jr(this._database)),this._entityService}get layerStore(){return this._layerStore||(this._layerStore=new Lc(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)&Gt)!==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?W(this._database,$,()=>ne.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;ie.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 tn=null;function Vh(){return tn?{...tn}:null}function Fb(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 Gh{constructor(){this.deferMeshFonts=!0,this._loadChain=Promise.resolve(),this._loader=new D.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(),u=await this._loader.getAvailableFonts();o=performance.now()-c;const p=new Map;for(const v of u)for(const w of v.name)p.set(w.toLowerCase(),v);for(const v of e){const w=v.toLowerCase(),x=p.get(w);this.deferMeshFonts&&x&&Fb(x)?r.push(v):n.push(v)}const y=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&&!y){const v=performance.now(),w=await this._loader.load(r);l=performance.now()-v,i=[...i,...w]}else y&&(l=null);const f={fontCount:e.length,criticalFonts:[...n],deferredFonts:[...r],metaMs:o,criticalLoadMs:a,deferredLoadMs:l,deferred:y,totalMs:performance.now()-t};if(tn=f,y&&r.length>0){const v=performance.now();this._loader.load(r).then(w=>{tn===f&&(f.deferredLoadMs=performance.now()-v),this.emitPartialFailures(w)},w=>{tn===f&&(f.deferredLoadMs=performance.now()-v),jb(w)})}}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&&ie.emit("fonts-not-found",{fonts:t}),i.length>0&&ie.emit("fonts-not-loaded",{fonts:i})}}function jb(s){console.warn("[AcApFontLoader] Deferred mesh font load failed; text may use SHX fallbacks.",s)}const Kh=[".dxf",".dwg"];let be,Rs=!1,Vs={};const zb=s=>{const e=s.toLowerCase();return Kh.some(t=>e.endsWith(t))},Rb=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)}),Vb=async s=>s?s():{minimumChunkSize:1e3},Uh=()=>{be||(be=document.createElement("input"),be.type="file",be.accept=Kh.join(","),be.style.display="none",be.addEventListener("change",Hh),document.body.appendChild(be)),be.click()},Hh=async s=>{var n;const e=s.target,t=(n=e.files)==null?void 0:n[0];if(e.value="",!t)return;if(!zb(t.name)){d.log.warn(`Unsupported file type: ${t.name}`);return}let i=null;try{i=await Rb(t);const{AcApDocManager:r}=await Promise.resolve().then(()=>iw),o=await Vb(Vs.getOpenDocumentDefaults);ie.emit("open-local-file-started",{mode:o.mode??z.Read}),await r.instance.openDocument(t.name,i,o)}catch(r){d.log.error("Failed to open selected file:",r)}finally{i=null}};function Wh(s={}){s.enabled!==!1&&(Vs=s,!Rs&&(ie.on("open-file",Uh),Rs=!0))}function $h(s){Vs=s}function Yh(){Rs&&(ie.off("open-file",Uh),be==null||be.removeEventListener("change",Hh),be==null||be.remove(),be=void 0,Rs=!1,Vs={})}const ci=class ci{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 ci._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=ci.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 A,C,L;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=((A=this._stages.get("PARSE"))==null?void 0:A.durationMs)??0,a=((C=this._stages.get("ENTITY"))==null?void 0:C.durationMs)??0,l={...d.AcDbRenderingCache.profileStats},c=l.topLevel,u=t.progressiveOpenStats,p=t.progressiveRendering,y=[...l.blockMisses].sort((_,N)=>N.buildMs+N.compactMs-(_.buildMs+_.compactMs)).slice(0,10).map(_=>({blockName:_.blockName,buildMs:_.buildMs,compactMs:_.compactMs})),g=[...this._stages.entries()].filter(([,_])=>_.durationMs>0).sort((_,N)=>N[1].durationMs-_[1].durationMs).map(([_,N])=>({name:_,durationMs:N.durationMs})),f={collectedAt:Date.now(),fileName:(L=this._database)==null?void 0:L.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:y,progressive:{enabled:p,paintCount:u.paintCount,yieldCount:u.yieldCount}};if(ci._lastSnapshot=f,!this._printToConsole)return;const v=(_,N)=>N<=0?"0%":`${(_/N*100).toFixed(1)}%`,w=["","========== 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=${u.paintCount}, yields=${u.yieldCount})`,`wall clock total: ${r.toFixed(0)} ms`,` db.read: ${i.toFixed(0)} ms (${v(i,r)})`,` PARSE: ${o.toFixed(0)} ms (${v(o,i)} of read)`,` ENTITY flush: ${a.toFixed(0)} ms (${v(a,i)} of read)`,` scene convert: ${n.toFixed(0)} ms (${v(n,r)})`],x=Vh();if(x&&w.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(",")}])`),w.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)}`),y.length>0){w.push("","--- Slowest block template misses (build+compact) ---");for(const _ of y){const N=_.blockName.length>40?`${_.blockName.slice(0,37)}...`:_.blockName;w.push(`${N.padEnd(40)} build=${_.buildMs.toFixed(0).padStart(7)}ms compact=${_.compactMs.toFixed(0).padStart(7)}ms total=${(_.buildMs+_.compactMs).toFixed(0).padStart(7)}ms`)}}const S=g.filter(_=>!["PARSE","FONT","ENTITY","START","END"].includes(_.name));if(S.length>0){w.push("","--- Other openProgress sub-stages ---");for(const _ of S)w.push(` ${_.name}: ${_.durationMs.toFixed(0)} ms`)}w.push("==================================================",""),console.log(w.join(`
983
+ `));try{const _=d.AcCmPerformanceCollector.getInstance();_.getAll().length>0&&(console.log("--- AcCmPerformanceCollector ---"),_.printAll())}catch{}}detachProgressListener(){this._progressListener&&this._database&&this._database.events.openProgress.removeEventListener(this._progressListener),this._progressListener=void 0}};ci._lastSnapshot=null;let Gs=ci;function Zh(s){return s.percentage<100?!1:s.subStageStatus==="ERROR"?!0:s.subStageStatus!=="END"?!1:s.stage==="FETCH_FILE"||s.subStage==="END"}const ut=class ut{constructor(e){this._peak=0,this._overlayVisible=!1,this._lastMessage="",this._seeThrough=!1,this._progress=new en({host:e,overlayColor:ut.OVERLAY_DEFAULT}),this._progress.hide()}setHost(e){this._progress.setHost(e)}setSeeThroughOverlay(e){this._seeThrough=e,this._progress.setOverlayColor(e?ut.OVERLAY_SEE_THROUGH:ut.OVERLAY_DEFAULT)}setSceneBusyGate(e){this._sceneBusyGate=e}setOnHidden(e){this._onHidden=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 ie.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 h.t(t)}return}if(e.stage==="FETCH_FILE")return h.t("main.message.fetchingDrawingFile")}updateOverlay(e){var i;if(Zh(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(ut.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(ut.OVERLAY_SEE_THROUGH);const e=h.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(){var e;this.clearHoldPoll(),this._progress.hide(),this.reset(),(e=this._onHidden)==null||e.call(this)}clearHoldPoll(){this._holdPollId!=null&&(clearTimeout(this._holdPollId),this._holdPollId=void 0)}};ut.OVERLAY_DEFAULT="rgba(0,0,0,0.45)",ut.OVERLAY_SEE_THROUGH="rgba(0,0,0,0.16)";let Ho=ut;const Gb="libredwg-parser-worker.js",Kb="libredwg-web.wasm",Xh="mtext-renderer-worker.js",Ub="dwg-parser-worker.js",Hb="dwg-parser-main.js",Wb="@mlightcad/libredwg-converter",$b="@mlightcad/mtext-renderer",Yb="@mlight-cad/dwg-converter",qh={mtextRender:`./assets/${Xh}`};function Zb(s){const e=[(s==null?void 0:s.mtextRender)??qh.mtextRender];return s!=null&&s.dwgParser&&e.push(s.dwgParser),e.map(t=>String(t))}let Wo,$o;function Xb(){Wo=void 0,$o=void 0}async function qb(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 Jh(s){const e=Zb(s),t=e.join("|");if(Wo===t&&$o===!0)return!0;try{const n=(await Promise.all(e.map(qb))).every(Boolean);return n&&(Wo=t,$o=!0),n}catch{return!1}}class St{constructor(){this._sessions=new Map,this._nextId=1}static get instance(){return this._instance||(this._instance=new St),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&&Jb(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 Jb(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 nn=(s=>(s.Extents="extents",s.Saved="saved",s))(nn||{});const Qb="https://cdn.jsdelivr.net/gh/mlightcad/cad-data",ew="templates/acadiso.dxf",tw={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"]},Qh="modern";class k{constructor(e={}){var c;this._sessions=[],this._nextSessionId=1,this._openFileProfiler=new Gs,this._workersReady=null,this._nextOverlayId=1,this.events={documentToBeOpened:new d.AcCmEventManager,documentCreated:new d.AcCmEventManager,documentActivated:new d.AcCmEventManager,documentToBeActivated:new d.AcCmEventManager,documentToBeDestroyed:new d.AcCmEventManager,documentDestroyed:new d.AcCmEventManager,workersReady:new d.AcCmEventManager},this._baseUrl=e.baseUrl??Qb,this._commandAliasOverrides=this.normalizeCommandAliasConfig(e.commandAliases),this._openDocumentDefaults=e.openDocumentDefaults,e.useMainThreadDraw?D.AcTrMTextRenderer.getInstance().setRenderMode("main"):D.AcTrMTextRenderer.getInstance().setRenderMode("worker"),O.FontManager.instance.setDefaultFonts(Qh),O.FontManager.instance.lazyFontLoading=!0,O.FontManager.instance.awaitFontsBeforeDraw=!0,D.AcTrMTextRenderer.getInstance().setLazyFontLoading(!0),D.AcTrMTextRenderer.getInstance().setAwaitFontsBeforeDraw(!0);const t=new zs,i=((c=e.container)==null?void 0:c.getBoundingClientRect())??{width:300,height:150},n=()=>{var u;if(e.autoResize){const p=e.container;if(p)return{width:Math.max(1,Math.floor(p.clientWidth)),height:Math.max(1,Math.floor(p.clientHeight))};const y=(u=e.container)==null?void 0:u.getBoundingClientRect();return{width:Math.max(1,Math.floor((y==null?void 0:y.width)??i.width)),height:Math.max(1,Math.floor((y==null?void 0:y.height)??i.height))}}else return{width:e.width??i.width,height:e.height??i.height}},r=new ai({container:e.container,calculateSizeCallback:n});this._mainView=r;const o=new Us(r,t);this._activeSession=new Fs(`doc-${this._nextSessionId++}`,o),this._sessions=[this._activeSession],yi(this._activeSession.id),this._drawStyleToolbar=new zh(r),this._fontLoader=new Gh;const a=this.resolveFontsBaseUrl();this._fontLoader.baseUrl=a,O.FontManager.instance.baseUrl=a,d.acdbHostApplicationServices().workingDatabase=t.database,this._commandManager=new he,this.registerCommands(),this._pluginManager=new Lh(this.context,this._commandManager);const l=e.busyIndicatorHost??r.container;this._busyIndicatorHost=l,this._openFileProgress=new Ho(l),this._openFileProgress.setSceneBusyGate(()=>this.openProgressView.isProcessingEntities),this._openFileProgress.setOnHidden(()=>this.onOpenProgressHidden()),this._busyIndicator=new Bb(l),Fl({showMessage:(u,p,y)=>this.editor.showMessage(u,p,y),showBusyIndicator:u=>this.showBusyIndicator(u),hideBusyIndicator:()=>this.hideBusyIndicator(),withBusyIndicator:(u,p)=>this.withBusyIndicator(u,p)}),this.events.documentToBeOpened.addEventListener(()=>{this._openFileProgress.reset()}),this.bindOpenProgress(t),this.events.documentCreated.dispatch({doc:t,mode:t.openMode}),e.preloadDefaultFonts&&this.loadDefaultFonts(),this._webworkerFileUrls=e.webworkerFileUrls,this.registerWorkers(e.webworkerFileUrls),e.checkWorkersOnInit&&this.areWorkersReady(),this.loadPlugins(e.plugins).catch(u=>{d.log.error("[AcApDocManager] Error loading plugins:",u)}),Wh({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 Jh(e)}static get instance(){if(!k._instance)throw new Error("AcApDocManager instance is not created yet!");return k._instance}async destroy(){var e;await this._pluginManager.unloadAllPlugins(),(e=this._splitView)==null||e.stopAnimationLoop(),this._splitView=void 0;for(const t of[...this._sessions])t.context.dispose(),t.doc.destroy(),t.viewState&&this.curView.disposeSessionState(t.viewState);this._sessions=[],Yh(),D.AcTrMTextRenderer.resetInstance(),Xb(),k._instance=void 0}get workersReady(){return this._workersReady}areWorkersReady(){return this._workersReady===!0?Promise.resolve(!0):(this._workersReadyCheckPromise||(this._workersReadyCheckPromise=Jh(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._activeSession.context}get documents(){return this._sessions.map(e=>e.doc)}get documentCount(){return this._sessions.length}get activeSessionId(){return this._activeSession.id}document(e){var t;return(t=this._sessions[e])==null?void 0:t.doc}sessionFor(e){return this._sessions.find(t=>t.doc===e)}get curDocument(){return this.context.doc}get mdiActiveDocument(){return this._activeSession.doc}async activateDocument(e){const t=this.sessionFor(e);if(!t)return!1;if(t===this._activeSession)return!0;const i=t.context.view,n=this._activeSession.context.view;return this._openingSession&&i===n?!1:(await this._commandManager.cancelActive(),this.events.documentToBeActivated.dispatch({doc:e,mode:e.openMode}),i===n?(this.parkActiveSession(),this._activeSession=t,t.context.resume(),t.viewState&&(this.curView.restoreSessionState(t.viewState),t.viewState=void 0)):(this._activeSession!==this._openingSession&&this._activeSession.context.suspend(),this._activeSession=t,t.context.resume()),yi(t.id),d.acdbHostApplicationServices().workingDatabase=e.database,this._pluginManager.setContext(t.context),this.curView.bindDrawDatabase(e.database),this.events.documentActivated.dispatch({doc:e,mode:e.openMode}),this.setActiveLayout(),this.curView.syncDisplaySysVars(e.database),this._openingSession||this.syncProgressOverlayHost(),!0)}get mainView(){return this._mainView}get splitView(){return this._splitView}ensureSplitView(e){return this._splitView?this._splitView.container!==e&&e.appendChild(this._splitView.container):this._splitView=new ai({container:e,calculateSizeCallback:()=>({width:Math.max(1,e.clientWidth),height:Math.max(1,e.clientHeight)})}),this._splitView}attachSatelliteView(e,t){return this.ensureSplitView(e),!0}detachSatelliteView(){}get satelliteDocument(){var e;if(this._splitView)return(e=this._sessions.find(t=>t.context.view===this._splitView))==null?void 0:e.doc}async closeDocument(e){const t=e??this.curDocument,i=this.sessionFor(t);if(!i)return!1;await this._commandManager.cancelActive(),this.events.documentToBeDestroyed.dispatch({doc:t,mode:t.openMode});const n=i===this._activeSession,r=this._sessions.indexOf(i);if(this._sessions.length===1)return this.resetActiveSessionToUntitled(i),this.events.documentDestroyed.dispatch({doc:t,mode:t.openMode}),this.events.documentCreated.dispatch({doc:this.curDocument,mode:this.curDocument.openMode}),this.events.documentActivated.dispatch({doc:this.curDocument,mode:this.curDocument.openMode}),!0;n&&this.parkActiveSession(),i.context.dispose(),t.destroy(),this.clearSessionOverlays(i),sr(i.id);const o=i.context.view;if(i.viewState?(o.disposeSessionState(i.viewState),i.viewState=void 0):o.clear(),this._sessions.splice(r,1),this.events.documentDestroyed.dispatch({doc:t,mode:t.openMode}),n){const a=this._sessions[Math.min(r,this._sessions.length-1)];await this.activateDocument(a.doc)}return!0}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([...O.FontManager.instance.getFontsToLoad()]):await this._fontLoader.load(e)}async openUrl(e,t){t=this.setOptions(t);const i=await this.ensureOpenSession();this.beginOpenProgress(),this.onBeforeOpenDocument(t,!i);try{await this._openFileProgress.beginOpen(this.context.doc.database);const n=await this.context.doc.openUri(e,t);return this.onAfterOpenDocument(n,t),!n&&i&&await this.closeFailedOpenSession(),n}catch(n){throw this._openFileProfiler.cancel(),i&&await this.closeFailedOpenSession(),n}}async openDocument(e,t,i,n){i=this.setOptions(i);const r=await this.ensureOpenSession(n);this.beginOpenProgress(),this.onBeforeOpenDocument(i,!r);try{await this._openFileProgress.beginOpen(this.context.doc.database);const o=await this.context.doc.openDocument(e,t,i);return this.onAfterOpenDocument(o,i),!o&&r&&await this.closeFailedOpenSession(),o}catch(o){throw this._openFileProfiler.cancel(),r&&await this.closeFailedOpenSession(),o}}async loadOverlay(e,t,i={}){var l;const{targetView:n,...r}=i,o=new d.AcDbDatabase,a=(l=e.split(".").pop())==null?void 0:l.toLocaleLowerCase();return await xo(o,async()=>{await o.read(t,{readOnly:!0,...r},a==="dwg"?d.AcDbFileType.DWG:d.AcDbFileType.DXF)}),this.registerOverlayDatabase(o,{targetView:n})}async registerOverlayDatabase(e,t){const i=(t==null?void 0:t.targetView)??this.curView,n=await i.addOverlayEntities(e),r=`overlay-${this._nextOverlayId++}`;return(this._sessions.find(a=>a.context.view===i)??this._activeSession).overlays.set(r,{db:e,layout:n}),i.isDirty=!0,r}removeOverlay(e){for(const t of this._sessions){const i=t.overlays.get(e);if(!i)continue;return this.sessionCadScene(t).internalScene.remove(i.layout.internalObject),i.layout.clear(),t.overlays.delete(e),t.viewState||(t.context.view.isDirty=!0),!0}return!1}setOverlayVisible(e,t){for(const i of this._sessions){const n=i.overlays.get(e);if(n)return n.layout.visible=t,i.context.view.isDirty=!0,!0}return!1}clearOverlays(e){const t=e?this._sessions.filter(i=>i.context.view===e):this._sessions;for(const i of t)for(const n of[...i.overlays.keys()])this.removeOverlay(n)}getOverlayIds(e){if(!e)return Array.from(this._activeSession.overlays.keys());const t=this._sessions.find(i=>i.context.view===e);return t?Array.from(t.overlays.keys()):[]}get overlayIds(){return this.getOverlayIds()}setCompareDisplay(e,t){(t??this.curView).setCompareDisplay(e)}setOverlayCompareDisplay(e,t,i){for(const n of this._sessions){const r=n.overlays.get(e);if(!r)continue;return(i??n.context.view??this.curView).setCompareDisplay(t,r.layout),!0}return!1}getOverlayLayout(e){for(const t of this._sessions){const i=t.overlays.get(e);if(i)return i.layout}}async newDocument(e){const i=`${this.baseUrl.endsWith("/")?this.baseUrl:`${this.baseUrl}/`}${ew}`,n=this.setOptions({...e,mode:z.Write}),r=await this.ensureOpenSession();this.beginOpenProgress(),this.onBeforeOpenDocument(n,!r),await this._openFileProgress.beginOpen(this.context.doc.database);const o=await this.context.doc.openUri(i,n);return o&&this.context.doc.resetNewDocumentIdentity(),this.onAfterOpenDocument(o,n),!o&&r&&await this.closeFailedOpenSession(),o}setOpenDocumentDefaults(e){this._openDocumentDefaults=e,$h({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=tw[n.toUpperCase()]??[];e.addCommand(he.SYSTEMT_COMMAND_GROUP_NAME,n,r,o,this.resolveCommandAliases(n,a))};t("about","about",new uh),t("arc","arc",new $c),t("cachefont","cachefont",new Qi),t("circle","circle",new Qc),t("close","close",new wh),t("cdxf","cdxf",new kc),t("pngout","pngout",new Ac),t("entout","entout",new _c),t("ellipse","ellipse",new rd),t("erase","erase",new sh),t("hideobjects","hideobjects",new rh),t("dimlinear","dimlinear",new td),t("measuredistance","measuredistance",new hu),t("measurearea","measurearea",new nu),t("measureangle","measureangle",new tu),t("measurearc","measurearc",new cu),t("measurepoint","measurepoint",new mu),t("clearmeasurements","clearmeasurements",new Vd),t("measurementvis","measurementvis",new Gd),t("measurementexport","measurementexport",new Jd),t("measurementimport","measurementimport",new Qd),t("-hatch","-hatch",new ls),t("imageattach","imageattach",new od),t("-insert","-insert",new ld),t("xattach","xattach",new jd),t("-layer","-layer",new Rc),t("laycur","laycur",new Mc),t("laydel","laydel",new Ic),t("layfrz","layfrz",new es),t("layiso","layiso",new ts),t("laylck","laylck",new Dc),t("layon","layon",new Oc),t("layoff","layoff",new is),t("laythw","laythw",new Bc),t("layuniso","layuniso",new Fc),t("layulk","layulk",new jc),t("layerp","layerp",new Nc),t("layerclose","layerclose",new zc),t("line","line",new Lt),t("mline","mline",new dd),t("mtext","mtext",new ud),t("copy","copy",new Ms),t("move","move",new ah),t("offset","offset",new qi),t("rotate","rotate",new Os),t("log","log",new hh),t("open","open",new bh),t("pan","pan",new _h),t("point","point",new hd),t("polygon","polygon",new us),t("pline","pline",new gd),t("qnew","qnew",new vh),t("ray","ray",new bd),t("rectang","rectang",new hs),t("regen","regen",new kh),t("revcloud","revcloud",new ps),t("markuptext","markuptext",new th),t("markupline","markupline",new qu),t("markuparrow","markuparrow",new Ru),t("markupcloud","markupcloud",new Ku),t("markuprect","markuprect",new Ju),t("markupcircle","markupcircle",new Gu),t("markuphighlight","markuphighlight",new Uu),t("markupcallout","markupcallout",new Vu),t("markupstamp","markupstamp",new eh),t("markupvis","markupvis",new nh),t("clearmarkups","clearmarkups",new zu),t("markupexport","markupexport",new Zu),t("markupimport","markupimport",new Xu),t("select","select",new xh),t("sketch","sketch",new fs),t("spline","spline",new Od),t("switchbg","switchbg",new Ah),t("unisolateobjects","unisolateobjects",new dh),t("xline","xline",new zd),t("undo","undo",new Ch),t("redo","redo",new Ph),t("zoom","zoom",new Nt),d.AcDbSysVarManager.instance().getAllDescriptors().forEach(n=>{e.addCommand(he.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=Uo(e);for(this.editor.clearScriptInputs(),this.editor.enqueueScriptInputs(t);this.editor.hasScriptInputs();){const i=this.consumeNextScriptCommandName();if(i==null)break;if(Rh(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 '${z[n.mode]}' but document is in mode '${z[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=Uo(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(e,t){const i=e??this.curView,n=t??this.curDocument.database;i.activeLayoutBtrId=n.currentSpaceId,i.modelSpaceBtrId=n.tables.blockTable.modelSpace.objectId}onBeforeOpenDocument(e,t=!0){this.events.documentToBeOpened.dispatch({doc:this.context.doc,mode:this.getDocumentEventMode(e)}),t&&(St.instance.clearAll(),this.clearOverlays(),mr(),jo(),this.openProgressView.clear()),this.openProgressView.bindDrawDatabase(this.context.doc.database),this.openProgressView.progressiveRendering=(e==null?void 0:e.progressiveRendering)??!1,this._openFileProgress.setSeeThroughOverlay((e==null?void 0:e.progressiveRendering)??!1),this._openFileProfiler.begin(this.context.doc.database)}onAfterOpenDocument(e,t){const i=!e&&this.hasRecoverablePartialContent();if(e||i){const n=this._openingSession??this._activeSession,r=n.context.view;n.doc.destroy();const o=n.doc;this.events.documentActivated.dispatch({doc:o,mode:this.getDocumentEventMode(t)}),this.setActiveLayout(r,o.database),r.syncDisplaySysVars(o.database);const a=o.database,l=a.tables.blockTable.modelSpace.objectId,c=a.currentSpaceId!==l,u=d.acdbHostApplicationServices().layoutManager.getActiveLayout(a),p=u==null?void 0:u.limits,y=this.resolveOpenViewMode(t),g=(t==null?void 0:t.progressiveRendering)??!1;if(c&&p&&!p.isEmpty())r.zoomTo(p);else if(y===nn.Extents)g&&r.beginProgressiveOpenFit(),r.zoomToFitDrawing();else if(c)g&&r.beginProgressiveOpenFit(),r.zoomToFitDrawing();else{const f=r.width/Math.max(r.height,1),v=a.tables.viewportTable.getActiveVport(),w=v==null?void 0:v.modelViewBox(f);w?r.zoomTo(w):this.hasUsableDrawingExtents(a)?r.zoomTo(new d.AcGeBox2d(a.extmin,a.extmax)):(g&&r.beginProgressiveOpenFit(),r.zoomToFitDrawing())}r.markLayoutAsInitialized(a.currentSpaceId),this._openFileProfiler.markReadCompleteAndScheduleReport(r)}else this._openFileProfiler.cancel(),this.openProgressView.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._openingSession??this._activeSession).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)??z.Read}resolveOpenViewMode(e){return(e==null?void 0:e.openViewMode)!=null?e.openViewMode:this.getDocumentEventMode(e)===z.Write?nn.Saved:nn.Extents}showBusyIndicator(e){this._busyIndicator.show(e)}setBusyIndicatorHost(e){this._busyIndicatorHost=e,this.syncProgressOverlayHost()}get openProgressView(){var e;return((e=this._openingSession)==null?void 0:e.context.view)??this.curView}beginOpenProgress(){this._openingSession=this._activeSession,this.syncProgressOverlayHost()}onOpenProgressHidden(){const e=this._openingSession;this._openingSession=void 0,e&&this._sessions.includes(e)&&e!==this._activeSession&&e.context.suspend(),this.syncProgressOverlayHost()}syncProgressOverlayHost(e=this.openProgressView){const t=this._splitView?e.container:this._busyIndicatorHost;this._openFileProgress.setHost(t),this._busyIndicator.setHost(t)}hideBusyIndicator(){this._busyIndicator.hide()}setBusyIndicatorMessage(e){this._busyIndicator.setMessage(e)}async withBusyIndicator(e,t){return this._busyIndicator.withBusyIndicator(e,t)}registerWorkers(e){const t=D.AcTrMTextRenderer.getInstance();t.initialize((e==null?void 0:e.mtextRender)??qh.mtextRender),t.setDefaultFonts(Qh)}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)}}}bindOpenProgress(e){e.database.events.openProgress.addEventListener(t=>{if(this._openFileProgress.handle({database:e.database,percentage:t.percentage,stage:t.stage,subStage:t.subStage,subStageStatus:t.subStageStatus,data:t.data}),t.subStage!=="HEADER")return;const i=this._sessions.find(r=>r.doc===e),n=(i==null?void 0:i.context.view)??this.curView;n.ltscale=e.database.ltscale,n.celtscale=e.database.celtscale,n.renderer.showLineWeight=e.database.lwdisplay})}parkActiveSession(){this._activeSession.context.suspend(),this._activeSession.viewState=this.curView.captureSessionState()}async ensureOpenSession(e){const t=e??this.curView;if(t===this.curView&&this.curDocument.isReusableUntitled)return!1;const i=this._sessions.find(a=>a.context.view===t);if(i!=null&&i.doc.isReusableUntitled)return i!==this._activeSession&&await this.activateDocument(i.doc),!1;await this._commandManager.cancelActive(),this._activeSession.context.suspend(),t===this.curView&&(this._activeSession.viewState=this.curView.beginNewSession());const n=new zs,r=new Us(t,n),o=new Fs(`doc-${this._nextSessionId++}`,r);return this._sessions.push(o),this._activeSession=o,yi(o.id),d.acdbHostApplicationServices().workingDatabase=n.database,this._pluginManager.setContext(r),this.bindOpenProgress(n),this.events.documentCreated.dispatch({doc:n,mode:n.openMode}),!0}async closeFailedOpenSession(){this._sessions.length<=1||await this.closeDocument(this.curDocument)}resetActiveSessionToUntitled(e){const t=e.doc,i=e.id;St.instance.clearAll(),this.clearOverlays(),mr(),jo(),this.curView.clear(),e.context.dispose(),t.destroy(),sr(i);const n=new zs,r=new Us(this.curView,n),o=new Fs(`doc-${this._nextSessionId++}`,r);this._sessions=[o],this._activeSession=o,yi(o.id),d.acdbHostApplicationServices().workingDatabase=n.database,this._pluginManager.setContext(r),this.bindOpenProgress(n),this.curView.bindDrawDatabase(n.database)}clearSessionOverlays(e){const t=this.sessionCadScene(e);for(const i of e.overlays.values())t.internalScene.remove(i.layout.internalObject),i.layout.clear();e.overlays.clear()}sessionCadScene(e){var t;return((t=e.viewState)==null?void 0:t.scene)??e.context.view.cadScene}}const iw=Object.freeze(Object.defineProperty({__proto__:null,AcApDocManager:k},Symbol.toStringTag,{value:"Module"}));class sn{static isFontLoaded(e){return O.FontManager.instance.isFontLoaded(e)}static getFontType(e){return O.FontManager.instance.getFontType(e)}static getReplacementFontName(e){return O.FontManager.instance.findAndReplaceFont(e)}static getShxCodePoints(e){var r;const t=O.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=O.FontManager.instance.getFontByName(e,!1);if(!(!t||t.type!=="shx"))return t.data}static createShxParserFont(e){return new O.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=sn.findFontInfoByName(e))==null?void 0:t.type}static async ensureDrawingFontLoaded(e){const t=k.instance;t&&(sn.isFontLoaded(e)||await t.loadFonts([e]))}static async cacheFont(e,t,i,n){return O.FontManager.instance.cacheFont(e,t,i,n)}}const ep=s=>new d.AcGeBox3d(s.min,s.max),tp=s=>new d.AcGeBox2d(s.min,s.max),ip=s=>new T.Box3(s.min,s.max),np=s=>new d.AcGeBox2d(s.min,s.max),sp=s=>new T.Box2(s.min,s.max),rp=s=>new d.AcGeBox2d(s.min,s.max),op=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},Yo={threeBo2dToGeBox2d:np,geBox2dToThreeBox2d:sp,threeBox3dToGeBox3d:ep,geBox3dToThreeBox3d:ip,goBox3dToGeBox2d:tp,threeBox3dToGeBox2d:rp,geBox2dToThreeBox3d:op};class nw{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:Wt.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 Ks=(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))(Ks||{});class sw 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 rw(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 y=c.measureText(s).width;c.fillStyle=`rgba(${a})`,c.fillText(s,n/2-y/2,r/2+i/2-2)}const u=new T.Texture(l);return u.minFilter=T.LinearFilter,u.needsUpdate=!0,u}function Zo(s){const e=rw(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)}Ks.RIGHT_TOP;const ow={pos:Ks.LEFT_BOTTOM,size:100,hasZAxis:!0};class aw extends sw{constructor(e,t,i){const n={...ow,...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=Zo("X"),this.xText.position.set(1.5,-1,-1),this.add(this.xText),this.yText=Zo("Y"),this.yText.position.set(-1,1.5,-1),this.add(this.yText),this.hasZAxis&&(this.zText=Zo("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 lw extends D.AcTrBaseView{constructor(e,t,i,n){super(e,i,n),this._layoutBtrId=t,this._mode=fe.SELECTION,this._axesGizmo=this.createAxesGizmo(),this._viewportViews=new Map}get layoutBtrId(){return this._layoutBtrId}get mode(){return this._mode}set mode(e){e==fe.SELECTION?this._cameraControls.mouseButtons={MIDDLE:T.MOUSE.PAN}:e==fe.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 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 aw(this._camera.internalCamera,this._renderer.internalRenderer,{hasZAxis:!1,pos:Ks.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 Xo{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 cw(s,e){return[...s].sort((t,i)=>dw(t,i,e))}function dw(s,e,t){const i=ap(s)-ap(e);if(Math.abs(i)>Number.EPSILON)return i;const n=lp(t,s)-lp(t,e);return Math.abs(n)>Number.EPSILON?n:0}function ap(s){return Math.max(s.maxX-s.minX,0)*Math.max(s.maxY-s.minY,0)}function lp(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 ht=class ht{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>=ht.SMALL_ENTITY_THRESHOLD||this.convertedCount>=ht.SMALL_ENTITY_THRESHOLD)&&(this.incrementalEnabled=!0)}maybeIncrementalFit(e){if(!this.active||!this.incrementalEnabled||this.userAdjusted)return;const t=performance.now();if(t-this.lastZoomAt<ht.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*ht.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})}};ht.SMALL_ENTITY_THRESHOLD=500,ht.BBOX_GROWTH_RATIO=1.5,ht.FIT_INTERVAL_MS=500;let qo=ht;const Jo={background:d.ACGI_MODEL_SPACE_BACKGROUND},di=class di extends bc{constructor(e=Jo){const t={...Jo,...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,v=f&&!this._progressiveRendering;if(!this._isDirty&&!this._htmlDirty&&!f||v||!this._isDirty&&!this._htmlDirty)return;let w=!1;this._isDirty&&(this._progressiveRendering&&f&&this._progressivePaintCount++,w=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=w,this._htmlDirty=!1},this._gripManager=new Zl(this),this._keyHandler=new Tn(this),e.calculateSizeCallback&&this.setCalculateSizeCallback(e.calculateSizeCallback),n.setPixelRatio(Math.min(window.devicePixelRatio,2)),n.setSize(this.width,this.height),this._renderer=new D.AcTrRenderer(n);const r=pe.instance.fontMapping;this._renderer.setFontMapping(r),this._renderer.events.fontNotFound.addEventListener(f=>{ie.emit("font-not-found",{fontName:f.fontName,count:f.count??0})}),this._scene=this.createScene(),this._layerAppearance=new Pr(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(pe.instance.isShowStats&&this.isActiveManagedView());const o=d.AcDbSysVarManager.instance(),a=d.AcDbSystemVariables.MODELBKCOLOR.toLowerCase(),l=d.AcDbSystemVariables.PAPERBKCOLOR.toLowerCase();o.events.sysVarChanged.addEventListener(f=>{const v=f.name.toLowerCase();if(v===a||v===l){const w=this.isModelSpaceLayout(f.database);if(!(v===a&&w||v===l&&!w))return;this.applyCanvasBackground(_n(f.database,w))}}),pe.instance.events.modified.addEventListener(f=>{f.key=="isShowStats"&&this.toggleStatsVisibility(this._stats,f.value)});let c=null,u=null,p=null;const y=()=>this.mode===fe.SELECTION&&!this.editor.isActive&&!$e.getActiveInputBox()&&!Nl()&&!this._gripManager.isDragging,g=()=>{p==null||p.remove(),p=null};this.canvas.addEventListener("mousedown",f=>{f.button===0&&y()&&(u=this.viewportToCanvas({x:f.clientX,y:f.clientY}),c=this.screenToWorld(u),p=document.createElement("div"),p.className="ml-jig-preview-rect",this.container.appendChild(p))}),this.canvas.addEventListener("mousemove",f=>{if(!c||!p||!u)return;const v=this.viewportToCanvas({x:f.clientX,y:f.clientY}),w=this.screenToWorld(v),x=this.worldToScreen(c),S=this.worldToScreen(w),A=Math.min(x.x,S.x),C=Math.min(x.y,S.y),L=Math.abs(x.x-S.x),_=Math.abs(x.y-S.y),N=this.getSelectionMode(u,v),F=this.getPointerSelectionAction(f),M=this.getSelectionPreviewStyle(N,F);Object.assign(p.style,{left:`${A}px`,top:`${C}px`,width:`${L}px`,height:`${_}px`,borderStyle:M.borderStyle,background:M.background}),p.style.setProperty("--line-color",M.lineColor)}),this.canvas.addEventListener("mouseup",f=>{if(this._gripManager.isDragging){c=null,u=null,g();return}if(!c||!u)return;const v=this.viewportToCanvas({x:f.clientX,y:f.clientY}),w=this.screenToWorld(v);g();const x=this.getPointerSelectionAction(f);if(this.isSelectionClick(u,v))if(il(this,v.x,v.y,x))x==="replace"&&this.selectionSet.clear();else if(this.entitySelectionEnabled){const S=this.pick(w);S.length>0?(x==="replace"&&this.htmlTransientManager.deselectAll(),this.applySelection([S[0].id],x)):x==="replace"&&this.selectionSet.clear()}else x==="replace"&&this.selectionSet.clear();else{const S=new d.AcGeBox2d().expandByPoint(c).expandByPoint(w),A=this.getSelectionMode(u,v);this.entitySelectionEnabled&&this.selectByBoxWithMode(S,A,x),nl(this,S,A,x)}c=null,u=null}),this.canvas.addEventListener("dblclick",f=>{f.button===0&&y()&&this.entitySelectionEnabled&&k.instance.curDocument.openMode===z.Write&&this.openPickedEntityEditor(f)}),document.addEventListener("keydown",f=>{this.isActiveManagedView()&&this._keyHandler.handleKeyDown(f)}),d.acdbHostApplicationServices().layoutManager.events.layoutSwitched.addEventListener(f=>{var A,C;if(!this.isActiveManagedView())return;const v=f.layout.database,w=(C=(A=k._instance)==null?void 0:A.curDocument)==null?void 0:C.database;if(v&&w&&v!==w)return;const x=f.layout.blockTableRecordId,S=!this._initializedLayouts.has(x);this._initializedLayouts.add(x),this.activeLayoutBtrId=x,this.createLayoutViewIfNeeded(x),this.loadLayoutEntitiesIfNeeded(x),this.refreshCanvasBackgroundForActiveLayout(),this._isDirty=!0,S&&this.applyInitialZoom(x,f.layout)}),this._css2dRenderer=new Ap.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 Xo,this._progressiveOpenFit=new qo((f,v)=>{this.activeLayoutView.zoomTo(f,v??1.1),this._isDirty=!0}),this._entityDisplay=new nw(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 fc(e)}initialize(){this.setCursor(Ie.Crosshair)}get mode(){const e=this.activeLayoutView;return e?e.mode:fe.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?bl(e):this.activeLayoutBtrId===this.modelSpaceBtrId}bindDrawDatabase(e){this._renderer.context.database=e}syncDisplaySysVars(e){this.bindDrawDatabase(e),this.applyCanvasBackground(_n(e,this.isModelSpaceLayout(e)))}async addOverlayEntities(e){const t=new Il;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 D.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(_n(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 u=c.blockTableRecordId;u&&this._scene.addEmptyLayout(u)}for(const[c]of this._scene.layouts){if(!i&&c!==this._scene.modelSpaceBtrId)continue;const u=n.tables.blockTable.getIdAt(c);u&&r.push(...this._entityDisplay.collectMissingEntitiesForExport(u,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 Dr(()=>!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=Yo.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!==$e.defaultLineSpacingFactor&&yt(t,"Edit MText",()=>{const r=t.openEntityForWrite(e);r instanceof d.AcDbMText&&(r.lineSpacingFactor=$e.defaultLineSpacingFactor)}),this._isDirty=!0;const i=new $e;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;yt(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),u=o.layoutBtrId!==this._scene.modelSpaceBtrId,p=(l.size.width+l.size.height)/2,y=[],g=new Set;if(u)for(const x of o.viewportViews)x.containsPaperPoint(e)&&!x.isNearPaperBorder(e,p)&&(y.push(x),g.add(x.viewport.id));const f=this._scene.search(l),v=o.resetRaycaster(e,c);f.forEach(x=>{g.has(x.id)||Mn(x)&&r.isIntersectWith(x.id,v)&&n.push(x)}),y.length>0&&this.pickThroughViewports(e,l,y,n);const w=cw(n,e);return i?w.slice(0,1):w}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 u=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(u).forEach(g=>{Mn(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);(Wt.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,D.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:D.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 Yo.threeBox3dToGeBox2d(e)}applyInitialZoom(e,t){new Dr(()=>!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._initializedLayouts.clear(),this._externallyFramedLayouts.clear(),this._loadingLayouts.clear(),this._renderer.dispose()}captureSessionState(){return{scene:this._scene,layoutViewManager:this._layoutViewManager,initializedLayouts:this._initializedLayouts,externallyFramedLayouts:this._externallyFramedLayouts,loadingLayouts:this._loadingLayouts,missedImages:this._missedImages,selectionIds:this.selectionSet.ids}}restoreSessionState(e){this._convertEpoch++,this._convertQueue.length=0,this._numOfEntitiesToProcess=0,this._pendingGeometryJobs=0,this._scene=e.scene,this._layoutViewManager=e.layoutViewManager,this._initializedLayouts=e.initializedLayouts,this._externallyFramedLayouts=e.externallyFramedLayouts,this._loadingLayouts=e.loadingLayouts,this._missedImages=e.missedImages,this.rebindLayerAppearance(),this._layoutViewManager.resize(this.width,this.height),this.selectionSet.clear(),e.selectionIds.length>0&&this.selectionSet.add(e.selectionIds),this._isDirty=!0}beginNewSession(){const e=this.captureSessionState();return this._convertEpoch++,this._convertQueue.length=0,this._numOfEntitiesToProcess=0,this._pendingGeometryJobs=0,this._scene=this.createScene(),this._layoutViewManager=new Xo,this._initializedLayouts=new Set,this._externallyFramedLayouts=new Set,this._loadingLayouts=new Set,this._missedImages=new Map,this.rebindLayerAppearance(),this.selectionSet.clear(),this._isDirty=!0,e}disposeSessionState(e){e.scene.clear(),e.layoutViewManager=new Xo,e.initializedLayouts.clear(),e.externallyFramedLayouts.clear(),e.loadingLayouts.clear(),e.missedImages.clear(),e.selectionIds=[]}rebindLayerAppearance(){this._layerAppearance=new Pr(this._scene,this._renderer)}isActiveManagedView(){var i;const t=(i=k._instance)==null?void 0:i.curView;return t==null||t===this}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>=di.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS)&&(this._isDirty=!0,this._lastProgressivePaintAt=t)}highlight(e){this.entitySelectionEnabled&&(this._isDirty=this._scene.select(e))}unhighlight(e){this._isDirty=this._scene.unselect(e)}setCompareDisplay(e,t){var r,o,a,l;const i=e.baseColor??((r=e.colors)==null?void 0:r.unchanged)??10265519,n={enabled:e.enabled,baseColor:i,colors:{deleted:(o=e.colors)==null?void 0:o.deleted,added:(a=e.colors)==null?void 0:a.added,modified:(l=e.colors)==null?void 0:l.modified},overrides:e.overrides};t?t.setCompareDisplay(n):this._scene.setCompareDisplay(n),this._isDirty=!0}stopAnimationLoop(){this._rafId!=null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}onHover(e){this.entitySelectionEnabled&&(this._isDirty=this._scene.hover([e]))}onUnhover(e){this._isDirty=this._scene.unhover([e])}createScene(){return new Ml}createStats(e){const t=new Sp;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 lw(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 D.AcTrGroup){if(e.getSourceEntities().length===0&&!this.groupHasPendingGlyphGeometry(e))return;await e.asyncDraw();return}e.hasDrawableGeometry()||await e.asyncDraw()}needsDeferredFontGeometry(e){return e instanceof D.AcTrGlyphEntity||e instanceof D.AcTrGroup}groupHasPendingGlyphGeometry(e){let t=!1;return e.traverse(i=>{i instanceof D.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)||D.AcTrViewportView.isDefaultPaperSpaceViewport(n))continue;const r=new D.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(di.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&&D.AcTrViewportView.isDefaultPaperSpaceViewport(l)||!(t.forExport?this._entityDisplay.shouldConvertForExport(l):this._entityDisplay.shouldConvert(l)))continue;const u=kl(l,this._renderer);if(u){let y=!1;try{y=this._scene.addDirectEntity(u,xl(l)),y&&(this.applySessionHiddenObjectState(l.objectId),n&&(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.resolveLayoutFitBox(),a)))}finally{u.geometry.dispose()}if(y)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 D.AcTrGroup&&p.isOnTheSameLayer&&(this._inheritedLayerMaterialMapper.remap(p.children,"0",p.layerName),p.userData.insertLayerName=p.layerName);const y=p instanceof D.AcTrGroup&&!p.isOnTheSameLayer,g=!t.forExport&&this.needsDeferredFontGeometry(p);if(y)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),v=async()=>{if(await this.finishEntityGeometry(p,n),i!==this._convertEpoch){p.dispose();return}p instanceof D.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(v,i):await v()}}if(i!==this._convertEpoch)continue;if(l instanceof d.AcDbViewport){if(!D.AcTrViewportView.isDefaultPaperSpaceViewport(l)){const y=this._layoutViewManager.getAt(l.ownerId);if(y){const g=new D.AcTrViewportView(y,l.toGiViewport(),this._renderer);y.addViewport(g)}}}else if(l instanceof d.AcDbRasterImage){const y=l.imageFileName;y&&!l.image&&this._missedImages.set(l.objectId,y)}}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=_r(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 y=p.userData.layerName;r.has(y)||r.set(y,[]),(g=r.get(y))==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"&&Mm(e);const c=e.wcsChildBoxes.map(p=>({minX:p.minX,minY:p.minY,maxX:p.maxX,maxY:p.maxY,id:p.id})),u=c.length>0?_r(e):e.wcsBbox.clone();c.length>0&&(e.wcsBbox=u.clone()),r.forEach((p,y)=>{const g=y==="0"?l:y,f=p.some(x=>(x.userData.authoredLayerName??y)==="0")?"0":y;this._inheritedLayerMaterialMapper.remap(p,f,g);const v=new D.AcTrEntity(o);v.applyMatrix4(e.matrix),v.objectId=a,v.ownerId=e.ownerId,v.layerName=g,v.userData.insertLayerName=l,v.wcsBbox=u.clone();const w=v.userData;w.spatialIndexChildBoxes=c;for(let x=0;x<p.length;x++)v.add(p[x]);this._layerAppearance.refreshTextMaterialsInObjectTree(v),this._scene.addEntity(v,!0),this.applySessionHiddenObjectState(a),v.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)}};di.PROGRESSIVE_OPEN_YIELD_BUDGET_MS=300,di.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS=1e3;let ai=di;function uw(s){if(!s)return!1;const e=Object.keys(s);return e.length>0&&e.every(t=>t==="visibility")}function hw(s,e,t){const{entity:i,changes:n}=s,r=i.objectId;if(!e(r))return!1;if(uw(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 cp(s){return Array.isArray(s)?s:[s]}class Us{constructor(e,t){this._active=!0,this._disposers=[],this._view=e,this._doc=t;const i=(n,r)=>{n.addEventListener(r),this._disposers.push(()=>n.removeEventListener(r))};i(t.database.events.entityAppended,n=>{if(!this._active)return;const r=cp(n.entity).filter(o=>!this.view.hasEntity(o.objectId));r.length!==0&&this.view.addEntity(r.length===1?r[0]:r)}),i(t.database.events.entityModified,n=>{if(!this._active)return;const r=n,o=this.view;o instanceof ai&&hw(r,a=>o.hasEntity(a),a=>o.getEntityVisible(a))&&o.updateEntityVisibility(r.entity)||this.view.updateEntity(r.entity)}),i(t.database.events.entityErased,n=>{if(!this._active)return;const r=cp(n.entity).filter(o=>this.view.hasEntity(o.objectId));r.length!==0&&this.view.removeEntity(r.length===1?r[0]:r)}),i(t.database.events.layerAppended,n=>{this._active&&this._view.addLayer(n.layer)}),i(t.database.events.layerModified,n=>{this._active&&this._view.updateLayer(n.layer,n.changes)}),i(d.AcDbSysVarManager.instance().events.sysVarChanged,n=>{if(!(!this._active||n.database!==this._doc.database)){if(n.name==d.AcDbSystemVariables.PDMODE.toLowerCase())this._view.rerenderPoints(n.database.pdmode);else if(n.name==d.AcDbSystemVariables.LWDISPLAY.toLowerCase()){const r=this._view,o=!!n.database.lwdisplay;r.renderer.showLineWeight!==o&&(r.renderer.showLineWeight=o,r.clear(),n.database.regen())}}}),i(t.database.events.dictObjetSet,n=>{this._active&&n.object instanceof d.AcDbLayout&&this._view.addLayout(n.object)}),i(e.selectionSet.events.selectionAdded,n=>{this._active&&e.highlight(n.ids)}),i(e.selectionSet.events.selectionRemoved,n=>{this._active&&e.unhighlight(n.ids)})}get view(){return this._view}get doc(){return this._doc}get isActive(){return this._active}suspend(){this._active=!1}resume(){this._active=!0}dispose(){this._active=!1;for(const e of this._disposers)e();this._disposers.length=0}}function Qo(s){return typeof s.hasEntity=="function"&&typeof s.setEntitySceneVisible=="function"}function pw(s,e,t){!s.isObjectHidden(t)||!Qo(e)||e.setEntitySceneVisible(t,!1)}function dp(s,e){const t=s.view;if(!Qo(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 up(s){const e=s.view;if(!Qo(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 mw extends R{async execute(e){d.log.info("Hello from ExamplePlugin!"),d.log.info("Current document:",e.doc),d.log.info("Current view:",e.view)}}class yw{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 mw),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`)}}function rn(...s){return`<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 1024 1024">${s.map(t=>`<path fill="currentColor" d="${t}"/>`).join("")}</svg>`}const gw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M10.4379 15.2979h.002l4.86-4.86-9.722-4.86 4.86 9.72Zm7.562-5.298-3.434 3.434 3.2 3.2-1.132 1.132-3.2-3.2-3.434 3.434-7.6-15.6 15.6 7.6Z"/></svg>',fw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M15.08 12.8537l.002-.002V5.5897c0-.422-.652-.414-.652 0v3.466c0 .938-1.482.95-1.482 0v-4.83c0-.414-.6381-.414-.6381 0h-.014v4.83c.014.95-1.482.95-1.482 0V3.4437c0-.42-.638-.414-.638 0v5.612c0 .95-1.494.95-1.494 0V4.2317c0-.408-.64-.42-.64 0v6.756c0 .802-1.094 1.088-1.494.388-.26-.446-.518-.892-.776-1.338-.338-.482-1.1-.15-.794.38.326.566.652 1.132.978 1.698.006.012.014.026.02.04.552.946 1.106 1.89 1.658 2.834.19.3.422.578.666.802h-.006c.672.61 1.528.964 2.418 1.052.888.06 1.7921-.124 2.5601-.612.3-.19.572-.416.816-.68.326-.368.57-.776.734-1.204.176-.482.258-.97.258-1.494Zm-.91-8.608-.004-.002c.958-.38 2.058.244 2.058 1.346v7.266c0 .652-.108 1.29-.332 1.894-.216.564-.53 1.114-.964 1.576-.318.34-.666.632-1.046.884-.978.612-2.1461.862-3.2601.774-1.128-.102-2.228-.564-3.098-1.352-.326-.292-.612-.646-.87-1.034-.558-.96-1.114-1.92-1.672-2.88l-.012-.028c-.326-.568-.652-1.138-.978-1.706-.59-1.018.068-2.186 1.156-2.336.536-.074 1.126.116 1.562.72.026.028.04.062.054.096.04.074.082.146.122.218V4.2337c0-1.176 1.244-1.788 2.202-1.278.42-1.278 2.378-1.264 2.792-.014.9721-.51 2.2221.102 2.2221 1.284v.06c.022-.014.046-.026.068-.04Z"/></svg>',bw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M9.3333 14.125 5.875 10.6667V14.125H9.3333Zm4.7917-3.4583-3.4583 3.4583H14.125V10.6667ZM10.6667 5.875 14.125 9.3333V5.875H10.6667ZM5.875 9.3333 9.3333 5.875H5.875V9.3333Zm9.2083 5.475c1.2333-1.3 1.9083-3.0333 1.9083-4.825-.0083-3.325-2.35-6.1833-5.6083-6.8417C8.125 2.4833 4.85 4.2 3.55 7.2583c-1.3 3.0583-.275 6.6083 2.4583 8.5 2.725 1.8917 6.4167 1.6 8.8167-.6917.0917-.0833.175-.175.2583-.2583Zm1.2583.5917 2.575 2.575c-.3167.3167-.625.625-.9417.9417-.8583-.8583-1.7167-1.7167-2.575-2.575-3.4083 2.9-8.4917 2.5917-11.525-.6917S.9417 7.275 4.1083 4.1083C7.2667.9417 12.3667.8417 15.65 3.875s3.5917 8.1167.6917 11.525Z"/></svg>',hp='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M15.0833 14.8083c1.2333-1.3 1.9083-3.0333 1.9083-4.825-.0083-3.325-2.35-6.1833-5.6083-6.8417C8.125 2.4833 4.85 4.2 3.55 7.2583c-1.3 3.0583-.275 6.6083 2.4583 8.5 2.725 1.8917 6.4167 1.6 8.8167-.6917.0917-.0833.175-.175.2583-.2583Zm1.2583.5917 2.575 2.575c-.3167.3167-.625.625-.9417.9417-.8583-.8583-1.7167-1.7167-2.575-2.575-3.4083 2.9-8.4917 2.5917-11.525-.6917C.8417 12.3667.9417 7.275 4.1083 4.1083 7.2667.9417 12.3667.8417 15.65 3.875s3.5917 8.1167.6917 11.525Zm-3.55-2.6083V7.2083H7.2083v5.5833h5.5833ZM5.875 5.875h8.25v8.25H5.875V5.875Z"/></svg>',ww='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 512 512"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="m434.8 137.65l-149.36-68.1c-16.19-7.4-42.69-7.4-58.88 0L77.3 137.65c-17.6 8-17.6 21.09 0 29.09l148 67.5c16.89 7.7 44.69 7.7 61.58 0l148-67.5c17.52-8 17.52-21.1-.08-29.09M160 308.52l-82.7 37.11c-17.6 8-17.6 21.1 0 29.1l148 67.5c16.89 7.69 44.69 7.69 61.58 0l148-67.5c17.6-8 17.6-21.1 0-29.1l-79.94-38.47"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="m160 204.48l-82.8 37.16c-17.6 8-17.6 21.1 0 29.1l148 67.49c16.89 7.7 44.69 7.7 61.58 0l148-67.49c17.7-8 17.7-21.1.1-29.1L352 204.48"/></svg>',vw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><rect x="2" y="2" width="8.2" height="5" rx="1.2" fill="currentColor"/><rect x="2" y="8.5" width="8.2" height="9.5" rx="1.2" fill="currentColor"/><rect x="11.7" y="2" width="6.3" height="10" rx="1.2" fill="currentColor"/><rect x="11.7" y="13.5" width="6.3" height="4.5" rx="1.2" fill="currentColor"/></svg>',kw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" fill-rule="evenodd" d="M1.5 7h17v6h-17ZM4.25 7h1v2.5h-1ZM7.5 7h.75v1.5H7.5ZM10.25 7h1v2.5h-1ZM13.5 7h.75v1.5H13.5ZM16.25 7h1v2.5h-1Z"/></svg>',xw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M3.75 9.25h12.5v1.5H3.75v-1.5ZM2.25 6.5h1.5v7h-1.5v-7ZM16.25 6.5h1.5v7h-1.5v-7Z"/></svg>',Sw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><polygon fill="currentColor" points="5.74 7.13 7 9.5 4.15 7.72 3.2 7.12 3 7 7 4.5 6.17 6.05 5.67 7 5.74 7.13"/><polygon fill="currentColor" points="16 12.5 13.5 16.5 12.66 15.15 11.92 13.97 11 12.5 12 13.03 12.98 13.55 13.5 13.83 16 12.5"/><rect fill="currentColor" x="2" y="2.5" width="1" height="15"/><rect fill="currentColor" x="3" y="16.5" width="15" height="1"/><path fill="currentColor" d="M14,13c0,.18,0,.37,0,.55v0a6.82,6.82,0,0,1-.32,1.57l-.74-1.18L13,13.5c0-.14,0-.31,0-.47v0a6,6,0,0,0-6-6,6.74,6.74,0,0,0-1.26.13l-.29.07a5.61,5.61,0,0,0-1.3.52l-1-.6a7.07,7.07,0,0,1,2-.88,6.78,6.78,0,0,1,1-.19A7.7,7.7,0,0,1,7,6a7,7,0,0,1,7,7Z"/></svg>',Aw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" fill-rule="evenodd" d="M4 4h12v12H4V4Zm1.5 1.5v9h9v-9h-9Z"/><circle fill="currentColor" cx="4" cy="4" r="1.5"/><circle fill="currentColor" cx="16" cy="4" r="1.5"/><circle fill="currentColor" cx="4" cy="16" r="1.5"/><circle fill="currentColor" cx="16" cy="16" r="1.5"/></svg>',Cw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M2 16A10 10 0 0 0 18 16h-1.5A8.5 8.5 0 0 1 3.5 16H2Z"/><circle fill="currentColor" cx="2" cy="16" r="1.5"/><circle fill="currentColor" cx="10" cy="12.2" r="1.5"/><circle fill="currentColor" cx="18" cy="16" r="1.5"/></svg>',pp='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M9.25 2h1.5v5.25H16v1.5h-5.25V16h-1.5v-7.25H4v-1.5h5.25V2Z"/><circle fill="currentColor" cx="10" cy="10" r="1.75"/></svg>',ea='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 512 512" fill="currentColor" aria-hidden="true"><path d="M 459.5 0 L 475.5 0 L 476.5 1 L 479.5 1 L 485.5 3 Q 487.8 6.2 492.5 7 L 501 14.5 L 505 19.5 L 511 32.5 Q 510.2 35.8 512 36.5 L 512 52.5 L 511 53.5 L 511 56.5 L 509 62.5 L 506 68.5 L 493 89.5 L 483 108.5 L 478 115.5 L 472 127.5 L 467 134.5 L 457 153.5 L 452 160.5 L 442 179.5 L 437 186.5 L 431 198.5 L 440 213.5 L 440 215.5 L 443 220.5 L 447 232.5 L 448 240.5 L 449 241.5 L 449 245.5 L 450 246.5 L 450 254.5 L 451 255.5 L 451 274.5 L 450 275.5 L 450 283.5 L 449 284.5 L 449 289.5 L 448 290.5 L 448 294.5 L 447 295.5 L 446 302.5 L 442 314.5 L 438 322.5 L 438 324.5 L 428 345.5 L 428 347.5 L 425 352.5 L 422 361.5 L 418 368.5 L 418 370.5 L 415 375.5 L 412 384.5 L 408 391.5 L 408 393.5 L 405 398.5 L 402 407.5 L 398 414.5 L 395 423.5 L 391 430.5 L 391 432.5 L 381 453.5 L 381 455.5 L 378 460.5 L 375 469.5 L 371 476.5 L 368 485.5 L 361.5 497 L 353.5 501 L 348.5 501 L 347.5 500 L 344.5 500 L 329.5 495 L 326.5 493 L 321.5 492 L 318.5 490 L 303.5 485 L 289.5 478 L 287.5 478 L 282 473.5 L 279 467.5 L 279 459.5 L 280 458.5 L 280 455.5 L 281 454.5 L 281 451.5 L 282 450.5 L 283 442.5 L 284 441.5 L 286 431.5 L 285.5 431 L 281.5 435 L 259.5 455 L 255.5 457 L 246.5 457 L 223.5 444 L 189.5 421 L 155.5 394 L 133 373.5 L 130 367.5 L 130 359.5 L 134 352.5 L 223 233.5 L 242 206.5 L 254.5 192 L 271.5 177 L 285.5 168 L 299.5 161 L 314.5 156 L 317.5 156 L 318.5 155 L 330.5 154 L 331.5 153 L 352.5 153 L 354 151.5 L 356 146.5 L 372 120.5 L 374 115.5 L 387 94.5 L 397 75.5 L 402 68.5 L 408 56.5 L 413 49.5 L 423 30.5 L 431 17.5 L 439.5 9 L 449.5 3 L 455.5 1 L 458.5 1 L 459.5 0 Z M 466 30 L 459 33 L 454 39 L 448 51 L 443 58 L 433 77 L 428 84 L 414 110 L 409 117 L 407 122 L 405 124 L 403 129 L 401 131 L 399 136 L 384 161 L 386 162 L 388 162 L 396 166 L 409 175 L 422 153 L 424 148 L 429 141 L 431 136 L 433 134 L 435 129 L 437 127 L 439 122 L 444 115 L 454 96 L 459 89 L 469 70 L 474 63 L 482 47 L 482 43 L 480 38 L 475 32 L 469 30 L 466 30 Z M 333 183 L 332 184 L 328 184 L 327 185 L 324 185 L 323 186 L 320 186 L 314 188 L 300 195 L 286 205 L 271 220 L 267 225 L 266 228 L 410 310 L 412 307 L 412 305 L 416 296 L 418 285 L 419 284 L 419 279 L 420 278 L 420 252 L 419 251 L 419 246 L 417 241 L 417 238 L 411 224 L 402 211 L 389 198 L 371 188 L 362 185 L 352 184 L 351 183 L 333 183 Z M 248 252 L 195 322 L 193 326 L 172 353 L 167 361 L 194 384 L 228 409 L 249 422 L 256 417 L 303 372 L 310 368 L 318 368 L 322 370 L 328 378 Q 327 381 329 382 L 329 386 L 326 395 L 326 399 L 323 408 L 323 411 L 322 412 L 322 416 L 319 425 L 319 428 L 318 429 L 318 432 L 317 433 L 317 437 L 314 446 L 314 449 L 313 450 L 313 453 L 312 454 L 316 456 L 318 456 L 331 462 L 343 466 L 351 448 L 351 446 L 354 441 L 354 439 L 357 434 L 357 432 L 364 418 L 364 416 L 367 411 L 367 409 L 370 404 L 370 402 L 377 388 L 377 386 L 380 381 L 380 379 L 383 374 L 383 372 L 387 365 L 390 356 L 393 351 L 393 349 L 396 344 L 397 339 L 375 326 L 373 324 L 368 322 L 366 320 L 361 318 L 354 313 L 349 311 L 347 309 L 342 307 L 340 305 L 335 303 L 321 294 L 316 292 L 314 290 L 309 288 L 307 286 L 302 284 L 295 279 L 276 269 L 248 252 Z "/><path d="M 170.5 100 L 179.5 100 Q 185 102 188 106.5 L 190 110.5 L 190 134.5 L 184.5 142 L 177.5 145 L 171.5 145 L 166.5 143 L 162 138.5 L 159 129.5 L 159 115.5 L 160 114.5 Q 159.2 109.7 161 107.5 L 166.5 102 L 170.5 100 Z "/><path d="M 131.5 140 L 151.5 140 L 156.5 142 L 162 147.5 L 164 151.5 L 164 159.5 L 163 162.5 L 158.5 168 L 152.5 171 L 130.5 171 L 124.5 168 L 122 165.5 L 119 159.5 L 119 151.5 Q 121.3 145.3 126.5 142 L 131.5 140 Z "/><path d="M 197.5 140 L 218.5 140 L 223.5 142 L 228 146.5 L 231 152.5 L 231 158.5 L 229 163.5 L 223.5 169 L 218.5 171 L 197.5 171 L 192.5 169 L 188 164.5 L 186 160.5 L 185 153.5 L 188 146.5 L 191.5 143 L 197.5 140 Z "/><path d="M 171.5 166 L 177.5 166 L 180.5 167 L 187 171.5 L 190 176.5 L 190 200.5 Q 188 206 183.5 209 L 179.5 211 L 173.5 212 L 167.5 210 L 161 203.5 Q 159.2 201.3 160 196.5 L 159 195.5 L 159 181.5 L 162 172.5 L 165.5 169 L 171.5 166 Z "/><path d="M 50.5 223 L 60.5 223 L 68 228.5 L 71 234.5 L 71 256.5 Q 69.1 262.6 64.5 266 L 59.5 268 L 51.5 268 Q 45.3 265.7 42 260.5 L 40 255.5 L 40 235.5 L 42 230.5 L 48.5 224 L 50.5 223 Z "/><path d="M 13.5 263 L 30.5 263 Q 31.5 265 35.5 264 L 43 270.5 L 45 274.5 L 45 282.5 Q 43.1 288.6 38.5 292 L 33.5 294 L 10.5 294 Q 5 292 2 287.5 L 0 283.5 L 0 274.5 Q 2.3 268.3 7.5 265 L 13.5 263 Z "/><path d="M 80.5 263 L 97.5 263 L 103.5 265 L 108 268.5 L 111 273.5 L 112 279.5 L 109 287.5 L 104.5 292 L 100.5 294 L 77.5 294 Q 71.3 291.7 68 286.5 L 66 281.5 L 66 276.5 L 69 269.5 L 72.5 266 L 80.5 263 Z "/><path d="M 54.5 289 L 61.5 290 L 69 296.5 L 71 301.5 L 71 322.5 L 69 327.5 L 63.5 333 L 58.5 335 L 53.5 335 L 46.5 332 L 43 328.5 L 40 321.5 L 40 302.5 Q 41.8 301.8 41 298.5 L 46.5 292 L 54.5 289 Z "/><path d="M 98.5 400 L 107.5 402 L 113 407.5 L 115 411.5 L 115 434.5 Q 112.7 440.7 107.5 444 L 101.5 446 L 96.5 446 L 90.5 443 L 87 439.5 L 84 430.5 L 84 415.5 L 85 414.5 Q 84.3 410.3 86 408.5 L 92.5 402 L 98.5 400 Z "/><path d="M 55.5 441 L 77.5 441 L 80.5 442 L 86 446.5 L 89 451.5 L 89 460.5 Q 86.7 466.7 81.5 470 L 76.5 472 L 56.5 472 L 51.5 470 L 46 464.5 L 44 460.5 L 44 452.5 L 45 449.5 L 49.5 444 L 55.5 441 Z "/><path d="M 121.5 441 L 144.5 441 Q 150.7 443.3 154 448.5 L 156 453.5 L 156 458.5 L 154 464.5 L 148.5 470 L 146.5 470 L 143.5 472 L 122.5 472 L 116.5 469 L 113 465.5 L 111 461.5 L 110 455.5 Q 112 454.5 111 450.5 L 117.5 443 L 121.5 441 Z "/><path d="M 96.5 467 L 103.5 467 L 106.5 468 L 113 473.5 L 115 478.5 L 115 501.5 Q 113 507 108.5 510 L 104.5 512 L 95.5 512 Q 89.3 509.7 86 504.5 Q 84.3 502.7 85 498.5 L 84 497.5 L 84 482.5 L 87 473.5 L 91.5 469 L 96.5 467 Z "/></svg>',Pw=ea,_w='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7" fill="currentColor"/><rect x="14" y="14" width="7" height="7" fill="none" stroke="currentColor" stroke-width="1"/><path d="M12 4a8 8 0 0 1 7.25 7.25" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round"/><path d="M20.75 10 L17.25 10 L19 12.5 Z" fill="currentColor"/><path d="M12 20a8 8 0 0 1-8-8" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round"/><path d="M6 14 L2.5 14 L4 11 Z" fill="currentColor"/></svg>',Lw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20" fill="none" style="fill:none"><g fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12.4 3.25H5.5A2.25 2.25 0 0 0 3.25 5.5v9A2.25 2.25 0 0 0 5.5 16.75h9A2.25 2.25 0 0 0 16.75 14.5V8.6"/><g transform="rotate(45 13.2 6.7)"><rect x="11.7" y="1.55" width="3" height="7.45" rx="1.45"/><path d="M11.7 3.2h3"/><path d="M11.7 9 13.2 12.15 14.7 9"/><rect x="12.8" y="7.05" width="0.8" height="1.2" rx="0.4"/></g></g></svg>',mp='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 40 40"><path d="M35.29108325386048,15C37.125226253860475,12.309847399999999,36.958467253860476,9.335468299999999,34.79083925386047,7.0296237C32.62321825386047,4.53162557,29.455148253860475,4.33947164,27.120786253860473,6.4531626C24.953160253860474,4.53162512,21.951835253860473,4.53162512,19.950952253860475,6.4531626C17.783325253860475,4.53162512,14.782001253860473,4.53162512,12.781115753860474,6.4531626C10.446751353860474,4.3394711,7.111944153860474,4.53162512,4.944319853860474,7.0296228C2.9434360238604738,9.335468299999999,2.7767065138604736,12.3098459,4.610849853860474,15C2.9434466638604735,17.497998000000003,2.9434466638604735,22.694155,4.610849853860474,25C2.7767063338604734,27.690151,2.9434360238604738,30.664532,5.111060153860474,32.970377C7.278683453860474,35.468374,10.446751353860474,35.660526000000004,12.781114853860474,33.546839C14.013456253860474,34.639273,15.515264253860474,35.110636,16.949504253860475,34.960924L17.384031253860474,33.278093Q15.695761253860473,33.903341,13.886703253860473,32.299662C13.250737453860474,31.735897,12.292436853860474,31.740944,11.662447253860474,32.311378000000005Q10.430524553860474,33.426844,9.001459353860474,33.325500000000005Q7.535682953860474,33.22155,6.369870153860473,31.878052C6.355376453860474,31.861349,6.3405518538604735,31.844936,6.325405153860474,31.828825Q3.8021785638604735,29.144703,5.9879074538604735,25.938877C6.383556653860474,25.358576,6.372957753860474,24.592518,5.961405753860474,24.023384Q5.026963953860474,22.731148,5.026963953860474,20.072058Q5.026963953860474,17.378647,5.997069853860474,15.925296C6.374311253860474,15.360136,6.3706860538604735,14.6225471,5.987907653860473,14.0611229Q3.8149851238604735,10.8740788,6.203129753860473,8.1219487Q7.366510153860474,6.7812542,8.914587753860474,6.6747454Q10.427746053860474,6.570639,11.662447253860474,7.6886220000000005C12.311335753860474,8.2761691,13.304180353860474,8.261601,13.935551253860474,7.655268899999999Q16.267856253860472,5.41545445,18.845364253860474,7.700341C19.495353253860472,8.2765367,20.478888253860475,8.2569213,21.105388253860475,7.6552677Q23.437688253860475,5.41545364,26.015201253860475,7.7003412C26.651166253860474,8.2641058,27.609466253860475,8.2590561,28.239455253860474,7.6886208Q29.471375253860472,6.5731552,30.900443253860473,6.6745013Q32.36622125386047,6.7784510000000004,33.532031253860474,8.1219487C33.546527253860475,8.1386516,33.56135125386047,8.1550651,33.576497253860474,8.1711793Q36.099740253860475,10.8553152,33.91402525386047,14.0611248C33.75512825386048,14.2941837,33.65797725386047,14.5637598,33.631677253860474,14.8446045Q33.79909825386048,14.8235569,33.975852253860474,14.8257475Q34.933356253860474,14.8375826,35.59989625386047,15.52399L35.66519325386047,15.591235C35.550366253860474,15.381103,35.425664253860475,15.183288,35.29108325386048,15ZM35.966336253860476,26.182783L34.676930253860476,27.463251Q35.393826253860475,29.732494,33.53202725386048,31.878052C33.517697253860476,31.894566,33.50369225386048,31.911364,33.490022253860474,31.928431Q32.454415253860475,33.221331,30.964744253860474,33.325373Q30.004237253860474,33.392458000000005,29.149894253860474,32.951971L27.929481253860473,34.163925C30.176993253860473,35.589745,33.01140925386048,35.191897999999995,34.790837253860474,32.970377C36.64204925386047,30.837021,37.033868253860476,28.496355,35.966336253860476,26.182783Z" fill="currentColor"></path><path d="M18.34860205776758,36.08124306176758L19.51047686176758,31.58106006176758C19.601237461767578,31.22952606176758,20.042625161767578,31.109528061767577,20.301013961767577,31.36614306176758L23.55426316176758,34.59704206176758C23.808096861767577,34.84913206176758,23.69668006176758,35.27922206176758,23.35186196176758,35.378357061767574L18.936737541767577,36.647640061767575C18.586058351767576,36.74845306176758,18.257926098767577,36.43245106176758,18.34860205776758,36.08124306176758ZM21.15253496176758,30.02545706176758L24.88609836176758,33.73337206176758C25.07032536176758,33.91633406176758,25.36901856176758,33.91633406176758,25.553247461767576,33.73337206176758L36.52849006176758,22.833516161767577C36.710360061767574,22.65290166176758,36.71303206176758,22.36089566176758,36.534500061767574,22.17702746176758L32.941582061767576,18.47663122176758C32.75926806176758,18.288860715767576,32.45763906176758,18.28513235576758,32.27067206176758,18.46833832176758L21.15478106176758,29.36067706176758C20.96843986176758,29.543269061767578,20.96743176176758,29.84162706176758,21.15253496176758,30.02545706176758Z" fill="currentColor"></path></svg>',yp='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path d="M1.666717529296875,15.833333L1.666717529296875,4.1666666C1.666717529296875,3.24619204,2.412909569296875,2.5,3.333384129296875,2.5L16.666717529296875,2.5C17.587192529296875,2.5,18.333383529296874,3.24619204,18.333383529296874,4.1666666L18.333383529296874,9.127090500000001L17.500050529296875,8.268899000000001L17.500050529296875,4.1666666Q17.500050529296875,3.33333331,16.666717529296875,3.33333331L3.333384129296875,3.33333331Q2.500050839296875,3.33333331,2.500050839296875,4.1666666L2.500050839296875,15.833333Q2.500050839296875,16.666666,3.333384129296875,16.666666L8.404951129296876,16.666666L8.189774029296874,17.5L3.333384129296875,17.5C2.412909569296875,17.5,1.666717529296875,16.753808,1.666717529296875,15.833333ZM13.575839529296875,17.5L16.666717529296875,17.5C17.587192529296875,17.5,18.333383529296874,16.753808,18.333383529296874,15.833333L18.333383529296874,12.775434L17.500050529296875,13.602991L17.500050529296875,15.833333Q17.500050529296875,16.666666,16.666717529296875,16.666666L14.414989529296875,16.666666L13.575839529296875,17.5Z" fill="currentColor"></path><path d="M9.174291491940625,18.04064271171875L9.755228874140625,15.79055121171875C9.800609174140625,15.61478421171875,10.021303054140626,15.55478481171875,10.150497434140625,15.683092611718749L11.777121994140625,17.29854201171875C11.904038894140625,17.42458721171875,11.848330494140626,17.639632211718748,11.675921394140625,17.68919941171875L9.468359234140625,18.32384111171875C9.293019634140625,18.37424751171875,9.128953513140624,18.216246611718752,9.174291491940625,18.04064271171875ZM10.576257894140625,15.012749711718751L12.443039694140625,16.86670681171875C12.535153194140625,16.95818801171875,12.684499694140625,16.95818801171875,12.776614194140624,16.86670681171875L18.264235494140625,11.41677901171875C18.355170294140628,11.32647181171875,18.356506394140624,11.18046881171875,18.267240494140623,11.08853471171875L16.470781294140625,9.23833659271875C16.379624394140624,9.14445133871875,16.228809794140624,9.14258715871875,16.135326394140627,9.23419014371875L10.577380994140626,14.68035941171875C10.484210394140625,14.77165551171875,10.483706394140626,14.92083451171875,10.576257894140625,15.012749711718751Z" fill="currentColor"></path></svg>',gp='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path d="M17.366041494140624,8.13321261171875C16.667592494140624,4.38473101171875,13.396319494140625,1.66668701171875,9.583322994140625,1.66668701171875C5.211068394140625,1.66668701171875,1.666656494140625,5.21109891171875,1.666656494140625,9.58335351171875C1.6666564941406257,13.42974001171875,4.431342794140625,16.71955701171875,8.220290194140624,17.381800011718752L8.429374694140625,16.57206001171875C5.009032494140625,16.00730701171875,2.499989804140625,13.05000701171875,2.499989804140625,9.58335351171875C2.499989804140625,5.67133621171875,5.671305694140625,2.50002032171875,9.583322994140625,2.50002032171875C12.822601494140624,2.50002032171875,15.649155494140626,4.69743511171875,16.447924494140626,7.83668611171875Q16.522337494140626,7.82859321171875,16.600395494140624,7.82956071171875Q17.046328494140624,7.83507251171875,17.366041494140624,8.13321261171875Z" fill="currentColor"></path><path d="M9.174291491940625,18.04064271171875L9.755228874140625,15.79055121171875C9.800609174140625,15.61478421171875,10.021303054140626,15.55478481171875,10.150497434140625,15.683092611718749L11.777121994140625,17.29854201171875C11.904038894140625,17.42458721171875,11.848330494140626,17.639632211718748,11.675921394140625,17.68919941171875L9.468359234140625,18.32384111171875C9.293019634140625,18.37424751171875,9.128953513140624,18.216246611718752,9.174291491940625,18.04064271171875ZM10.576257894140625,15.012749711718751L12.443039694140625,16.86670681171875C12.535153194140625,16.95818801171875,12.684499694140625,16.95818801171875,12.776614194140624,16.86670681171875L18.264235494140625,11.41677901171875C18.355170294140628,11.32647181171875,18.356506394140624,11.18046881171875,18.267240494140623,11.08853471171875L16.470781294140625,9.23833659271875C16.379624394140624,9.14445133871875,16.228809794140624,9.14258715871875,16.135326394140627,9.23419014371875L10.577380994140626,14.68035941171875C10.484210394140625,14.77165551171875,10.483706394140626,14.92083451171875,10.576257894140625,15.012749711718751Z" fill="currentColor"></path></svg>',Ew=rn("M160 826.88 273.536 736H800a64 64 0 0 0 64-64V256a64 64 0 0 0-64-64H224a64 64 0 0 0-64 64zM296 800 147.968 918.4A32 32 0 0 1 96 893.44V256a128 128 0 0 1 128-128h576a128 128 0 0 1 128 128v416a128 128 0 0 1-128 128z","M352 512h320q32 0 32 32t-32 32H352q-32 0-32-32t32-32m0-192h320q32 0 32 32t-32 32H352q-32 0-32-32t32-32"),Tw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" fill-rule="evenodd" d="M10 2.2 17.2 17.6h-2.8l-1.45-4.2H7.05L5.6 17.6H2.8L10 2.2Zm0 4.3L8.2 11.2h3.6L10 6.5Z"/></svg>',Iw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" d="M4 16 16 4"/><circle cx="4" cy="16" r="1.6" fill="currentColor"/><circle cx="16" cy="4" r="1.6" fill="currentColor"/></svg>',Mw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><rect x="3" y="5.5" width="14" height="9" rx="1.5" fill="currentColor" fill-opacity="0.28" stroke="currentColor" stroke-width="1.5"/></svg>',Dw=rn("M754.752 480H160a32 32 0 1 0 0 64h594.752L521.344 777.344a32 32 0 0 0 45.312 45.312l288-288a32 32 0 0 0 0-45.312l-288-288a32 32 0 1 0-45.312 45.312z"),Ow=rn("M624 475.968V640h144a128 128 0 0 1 128 128H128a128 128 0 0 1 128-128h144V475.968a192 192 0 1 1 224 0M128 896v-64h768v64z"),Nw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><rect x="3.5" y="3" width="13" height="14" rx="1.5" fill="none" stroke="currentColor" stroke-width="1.5" /><path fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" d="M3.5 6.5h13" /><path fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" d="M6.5 9.5h7M6.5 12h7M6.5 14.5h4.5" /></svg>',Bw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" d="M4.5 2h6.4L15.5 6.6V16.5A1.5 1.5 0 0 1 14 18H4.5A1.5 1.5 0 0 1 3 16.5V3.5A1.5 1.5 0 0 1 4.5 2z"/><path stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" d="M10.9 2v4.6h4.6"/><path stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" d="M10 5.8v6M7.2 9.6 10 12.5l2.8-2.9"/></svg>',fp='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" d="M15.5 2H9.1L4.5 6.6V16.5A1.5 1.5 0 0 0 6 18h9.5A1.5 1.5 0 0 0 17 16.5V3.5A1.5 1.5 0 0 0 15.5 2z"/><path stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" d="M9.1 2v4.6H4.5"/><path stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" d="M10 14.2V8M7.2 10.4 10 7.5l2.8 2.9"/></svg>',Fw=ea,bp=rn("M512 160c320 0 512 352 512 352S832 864 512 864 0 512 0 512s192-352 512-352m0 64c-225.28 0-384.128 208.064-436.8 288 52.608 79.872 211.456 288 436.8 288 225.28 0 384.128-208.064 436.8-288-52.608-79.872-211.456-288-436.8-288m0 64a224 224 0 1 1 0 448 224 224 0 0 1 0-448m0 64a160.19 160.19 0 0 0-160 160c0 88.192 71.744 160 160 160s160-71.808 160-160-71.744-160-160-160"),wp=rn("M876.8 156.8c0-9.6-3.2-16-9.6-22.4s-12.8-9.6-22.4-9.6-16 3.2-22.4 9.6L736 220.8c-64-32-137.6-51.2-224-60.8-160 16-288 73.6-377.6 176S0 496 0 512s48 73.6 134.4 176c22.4 25.6 44.8 48 73.6 67.2l-86.4 89.6c-6.4 6.4-9.6 12.8-9.6 22.4s3.2 16 9.6 22.4 12.8 9.6 22.4 9.6 16-3.2 22.4-9.6l704-710.4c3.2-6.4 6.4-12.8 6.4-22.4m-646.4 528Q115.2 579.2 76.8 512q43.2-72 153.6-172.8C304 272 400 230.4 512 224c64 3.2 124.8 19.2 176 44.8l-54.4 54.4C598.4 300.8 560 288 512 288c-64 0-115.2 22.4-160 64s-64 96-64 160c0 48 12.8 89.6 35.2 124.8L256 707.2c-9.6-6.4-19.2-16-25.6-22.4m140.8-96Q352 555.2 352 512c0-44.8 16-83.2 48-112s67.2-48 112-48c28.8 0 54.4 6.4 73.6 19.2zM889.599 336c-12.8-16-28.8-28.8-41.6-41.6l-48 48c73.6 67.2 124.8 124.8 150.4 169.6q-43.2 72-153.6 172.8c-73.6 67.2-172.8 108.8-284.8 115.2-51.2-3.2-99.2-12.8-140.8-28.8l-48 48c57.6 22.4 118.4 38.4 188.8 44.8 160-16 288-73.6 377.6-176S1024 528 1024 512s-48.001-73.6-134.401-176","M511.998 672c-12.8 0-25.6-3.2-38.4-6.4l-51.2 51.2c28.8 12.8 57.6 19.2 89.6 19.2 64 0 115.2-22.4 160-64 41.6-41.6 64-96 64-160 0-32-6.4-64-19.2-89.6l-51.2 51.2c3.2 12.8 6.4 25.6 6.4 38.4 0 44.8-16 83.2-48 112s-67.2 48-112 48"),jw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="currentColor" d="m18.5 10 4.4 11h-2.155l-1.201-3h-4.09l-1.199 3h-2.154L16.5 10h2zM10 2v2h6v2h-1.968a18.222 18.222 0 0 1-3.62 6.301 14.864 14.864 0 0 0 2.336 1.707l-.751 1.878A17.015 17.015 0 0 1 9 13.725 16.676 16.676 0 0 1 3.524 17.273l-.536-1.929a14.7 14.7 0 0 0 5.327-3.042A18.078 18.078 0 0 1 4.767 8h2.24A16.032 16.032 0 0 0 9 10.877 16.165 16.165 0 0 0 11.91 6.001L2 6V4h6V2h2zm7.5 10.885L16.253 16h2.492L17.5 12.885z"/></svg>',zw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><circle cx="10" cy="10" r="4" fill="currentColor"/><path fill="none" stroke="currentColor" stroke-width="1.5" d="M10 2v2M10 16v2M2 10h2M16 10h2M4.2 4.2l1.4 1.4M14.4 14.4l1.4 1.4M4.2 15.8l1.4-1.4M14.4 5.6l1.4-1.4"/></svg>',Rw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M10 3a7 7 0 1 0 0 14 9 9 0 0 1 0-14Z"/></svg>',Vw=fp,Gw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M4 3h12v14H4V3Zm2 2v2h8V5H6Zm0 4v6h8V9H6Z"/></svg>',Kw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M5 3h7l3 3v11H5V3Zm6 0v3h3"/><text x="6" y="16" fill="currentColor" font-size="5" font-family="Arial">PDF</text></svg>',Uw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="none" stroke="currentColor" stroke-width="1.5" d="M4 4h12v12H4z"/><circle cx="8" cy="10" r="2" fill="currentColor"/></svg>',Hw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><rect x="3" y="3" width="14" height="14" rx="1.5" fill="none" stroke="currentColor" stroke-width="1.5"/><rect x="15" y="5" width="1.5" height="10" rx=".5" fill="currentColor"/></svg>',Ww='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><rect x="3" y="3" width="14" height="3" rx=".5" fill="currentColor"/><rect x="5" y="8" width="10" height="9" rx="1" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>',$w='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><rect x="5" y="3" width="10" height="9" rx="1" fill="none" stroke="currentColor" stroke-width="1.5"/><rect x="3" y="14" width="14" height="3" rx=".5" fill="currentColor"/></svg>',Yw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><rect x="3" y="3" width="3" height="14" rx=".5" fill="currentColor"/><rect x="8" y="5" width="9" height="10" rx="1" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>',Zw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><rect x="5" y="5" width="9" height="10" rx="1" fill="none" stroke="currentColor" stroke-width="1.5"/><rect x="14" y="3" width="3" height="14" rx=".5" fill="currentColor"/></svg>',Xw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" d="M5 5l10 10M15 5 5 15"/></svg>',qw='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><circle cx="10" cy="4" r="1.5" fill="currentColor"/><circle cx="10" cy="10" r="1.5" fill="currentColor"/><circle cx="10" cy="16" r="1.5" fill="currentColor"/></svg>',Jw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" d="M10 6.5 5.5 11h9L10 6.5Z"/></svg>',Qw='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" d="M10 13.5 14.5 9h-9L10 13.5Z"/></svg>',ev='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" d="M13.5 10 9 14.5V5.5L13.5 10Z"/></svg>',tv='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" aria-hidden="true"><path fill="currentColor" d="M6.5 10 11 14.5V5.5L6.5 10Z"/></svg>',iv='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M10 2.6 18 9.8h-2.1V17h-4.4v-4.4H8.5V17H4.1V9.8H2L10 2.6Zm0 1.8L5.3 9.8V15.8h2V11.4h5.4v4.4h2V9.8L10 4.4Z"/></svg>',nv='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M10.09 3.53 16.09 6.97 10.09 10.29 4.18 7 10.09 3.56M10.09 2.4 2.17 7 3.31 7.65 10.09 11.45 17 7.62 18.17 7 10.08 2.37 10.09 2.4Z"/><path fill="currentColor" d="M10.25 14.83 18.17 10.22 17 9.57 10.22 13.57 3.32 9.59 2.17 10.22 10.25 14.83Z"/><path fill="currentColor" d="M10.25 17.63 18.17 13 17 12.37 10.22 16.37 3.32 12.38 2.17 13 10.25 17.63Z"/></svg>',sv='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" d="M10.09 5.15 16.09 8.59 10.09 11.91 4.18 8.59 10.09 5.15ZM10.09 4 2.17 8.61 3.31 9.25 10.09 13.06 17 9.24 18.16 8.61 10.08 4 10.09 4Z"/><path fill="currentColor" d="M10.25 16.46 18.17 11.85 17 11.2 10.22 15.2 3.32 11.21 2.17 11.85 10.25 16.46Z"/><path fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" d="M3.5 3.5 16.5 16.5"/></svg>',rv='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="currentColor" fill-rule="evenodd" d="M2.25 2.25h4.878v4.878H2.25V2.25Zm.978.978v2.924h2.924V3.228H3.228Z"/><path fill="currentColor" d="M5.175 20.773V7.128H4.204V21.75H21.75V4.204H7.128v.971H20.773v15.598H5.175Z"/></svg>',ov='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" fill-rule="evenodd" d="M3 2H2v16h16v-1H8v-5H3V2zm0 11v4h4v-4H3z"/></svg>',av='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20"><path fill="currentColor" fill-rule="evenodd" d="M16.98 11L18.5 11L18.5 10L16.98 10C16.86 8.13 16.05 6.44 14.8 5.2L16.88 2.83L16.12 2.17L14.05 4.54C12.79 3.57 11.21 3 9.5 3C5.36 3 2 6.36 2 10.5C2 14.64 5.36 18 9.5 18C13.47 18 16.73 14.91 16.98 11ZM15.98 10C15.86 8.43 15.18 7.01 14.14 5.95L10.6 10L15.98 10ZM13.39 5.29L8.4 11L15.98 11C15.73 14.36 12.92 17 9.5 17C5.91 17 3 14.09 3 10.5C3 6.91 5.91 4 9.5 4C10.96 4 12.31 4.48 13.39 5.29Z"/></svg>',lv='<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="#e75958" d="M22 12H12l5 8.66A10 10 0 0 0 22 12Z"/><path fill="#814dff" d="M17 20.66 12 12 7 20.66A10 10 0 0 0 17 20.66Z"/><path fill="#13b0ce" d="M7 20.66 12 12H2A10 10 0 0 0 7 20.66Z"/><path fill="#4ecd83" d="M2 12H12L7 3.34A10 10 0 0 0 2 12Z"/><path fill="#ffc33f" d="M7 3.34 12 12l5-8.66A10 10 0 0 0 7 3.34Z"/><path fill="#ff9543" d="M17 3.34 12 12H22A10 10 0 0 0 17 3.34Z"/></svg>',cv=hp,dv=pp,uv=mp,hv=yp,pv=gp,mv=bp,yv=wp;function gv(s,e="ml-ex-ui-icon"){if(typeof s=="function")return s();if(s instanceof HTMLElement)return s.cloneNode(!0);const t=document.createElement("span");return t.className=e,t.innerHTML=s,t}Object.defineProperty(m,"ACGI_DARK_THEME_FOREGROUND",{enumerable:!0,get:()=>d.ACGI_DARK_THEME_FOREGROUND}),Object.defineProperty(m,"ACGI_LIGHT_THEME_FOREGROUND",{enumerable:!0,get:()=>d.ACGI_LIGHT_THEME_FOREGROUND}),Object.defineProperty(m,"ACGI_MODEL_SPACE_BACKGROUND",{enumerable:!0,get:()=>d.ACGI_MODEL_SPACE_BACKGROUND}),Object.defineProperty(m,"ACGI_PAPER_SPACE_BACKGROUND",{enumerable:!0,get:()=>d.ACGI_PAPER_SPACE_BACKGROUND}),Object.defineProperty(m,"acgiContrastingForegroundColor",{enumerable:!0,get:()=>d.acgiContrastingForegroundColor}),Object.defineProperty(m,"acgiForegroundColorForBackground",{enumerable:!0,get:()=>d.acgiForegroundColorForBackground}),Object.defineProperty(m,"acgiIsLightBackground",{enumerable:!0,get:()=>d.acgiIsLightBackground}),Object.defineProperty(m,"AcGiTextParagraphAlignment",{enumerable:!0,get:()=>O.MTextParagraphAlignment}),Object.defineProperty(m,"MTextColor",{enumerable:!0,get:()=>O.MTextColor}),Object.defineProperty(m,"MTextParagraphAlignment",{enumerable:!0,get:()=>O.MTextParagraphAlignment}),Object.defineProperty(m,"ShxParserFont",{enumerable:!0,get:()=>O.ShxParserFont}),m.ACAP_DEFAULT_COMPARE_COLORS=Ep,m.ACAP_UNTITLED_DOC_TITLE=js,m.AcApAboutCmd=uh,m.AcApArcCmd=$c,m.AcApBlockInsertSession=cs,m.AcApBlockPreviewConvertor=qr,m.AcApCacheFontCmd=Qi,m.AcApCircleCmd=Qc,m.AcApCircleJig=ro,m.AcApClearMarkupsCmd=zu,m.AcApClearMeasurementsCmd=Vd,m.AcApCloseCmd=wh,m.AcApContext=Us,m.AcApConvertToDxfCmd=kc,m.AcApConvertToPngCmd=Ac,m.AcApCopyCmd=Ms,m.AcApDimJig=ed,m.AcApDimLinearCmd=td,m.AcApDocManager=k,m.AcApDocSession=Fs,m.AcApDocument=zs,m.AcApDrawStyleToolbar=zh,m.AcApDxfConvertor=vc,m.AcApEllipseCmd=rd,m.AcApEntityPreviewCmd=_c,m.AcApEntityPreviewConvertor=Cc,m.AcApEntityService=Jr,m.AcApEraseCmd=sh,m.AcApExamplePlugin=yw,m.AcApFontLoader=Gh,m.AcApFontUtil=sn,m.AcApHatchCmd=ls,m.AcApHideObjectsCmd=rh,m.AcApI18n=h,m.AcApImageAttachCmd=od,m.AcApInsertCmd=ld,m.AcApLayerCloseCmd=zc,m.AcApLayerCmd=Rc,m.AcApLayerCurCmd=Mc,m.AcApLayerDelCmd=Ic,m.AcApLayerFreezeCmd=es,m.AcApLayerIsoCmd=ts,m.AcApLayerLockCmd=Dc,m.AcApLayerOnCmd=Oc,m.AcApLayerPCmd=Nc,m.AcApLayerService=ne,m.AcApLayerStore=Lc,m.AcApLayerThawCmd=Bc,m.AcApLayerUnisoCmd=Fc,m.AcApLayerUnlockCmd=jc,m.AcApLayoffCmd=is,m.AcApLineCmd=Lt,m.AcApLineJig=ss,m.AcApLogCmd=hh,m.AcApMLineCmd=dd,m.AcApMLineJig=cd,m.AcApMTextCmd=ud,m.AcApMarkupArrowCmd=Ru,m.AcApMarkupCalloutCmd=Vu,m.AcApMarkupCalloutEntity=Iu,m.AcApMarkupCircleCmd=Gu,m.AcApMarkupCloudCmd=Ku,m.AcApMarkupEntity=Ot,m.AcApMarkupExportCmd=Zu,m.AcApMarkupHighlightCmd=Uu,m.AcApMarkupHighlightEntity=Mu,m.AcApMarkupHistory=Ea,m.AcApMarkupImportCmd=Xu,m.AcApMarkupLineCmd=qu,m.AcApMarkupPresenter=Fu,m.AcApMarkupRectCmd=Ju,m.AcApMarkupSegmentEntity=Du,m.AcApMarkupShapeEntity=Ou,m.AcApMarkupStampCmd=eh,m.AcApMarkupStampEntity=Nu,m.AcApMarkupStore=ba,m.AcApMarkupTextCmd=th,m.AcApMarkupTextEntity=Bu,m.AcApMarkupVisibilityCmd=nh,m.AcApMeasureAngleCmd=tu,m.AcApMeasureAngleEntity=Vi,m.AcApMeasureArcCmd=cu,m.AcApMeasureArcEntity=Gi,m.AcApMeasureAreaCmd=nu,m.AcApMeasureAreaEntity=Ki,m.AcApMeasureDistanceCmd=hu,m.AcApMeasureDistanceEntity=Ui,m.AcApMeasureDistanceJig=uu,m.AcApMeasureEntity=ii,m.AcApMeasurePointCmd=mu,m.AcApMeasurePointEntity=Hi,m.AcApMeasurementExportCmd=Jd,m.AcApMeasurementHistory=Ma,m.AcApMeasurementImportCmd=Qd,m.AcApMeasurementVisibilityCmd=Gd,m.AcApMemoryProfiler=kb,m.AcApMoveCmd=ah,m.AcApOffsetCmd=qi,m.AcApOpenCmd=bh,m.AcApOpenFileProfiler=Gs,m.AcApOpenViewMode=nn,m.AcApOverlayEntity=Po,m.AcApPanCmd=_h,m.AcApPluginManager=Lh,m.AcApPngConvertor=xc,m.AcApPointCmd=hd,m.AcApPolygonCmd=us,m.AcApPolylineCmd=gd,m.AcApPolylineJig=yd,m.AcApProgress=en,m.AcApQNewCmd=vh,m.AcApRayCmd=bd,m.AcApRectCmd=hs,m.AcApRectJig=vd,m.AcApRedoCmd=Ph,m.AcApRegenCmd=kh,m.AcApRevCloudCmd=ps,m.AcApRevCloudJig=Ed,m.AcApRotateCmd=Os,m.AcApSelectCmd=xh,m.AcApSessionUndo=Ta,m.AcApSettingManager=pe,m.AcApSketchCmd=fs,m.AcApSketchJig=Md,m.AcApSplineCmd=Od,m.AcApSplineJig=Dd,m.AcApSwitchBgCmd=Ah,m.AcApSysVarCmd=Sh,m.AcApUndoCmd=Ch,m.AcApUnisolateObjectsCmd=dh,m.AcApXAttachCmd=jd,m.AcApXLineCmd=zd,m.AcApXrefManager=St,m.AcApZoomCmd=Nt,m.AcEdBaseView=bc,m.AcEdBatchedPreview=$r,m.AcEdCommand=R,m.AcEdCommandLine=dc,m.AcEdCommandStack=he,m.AcEdConditionWaiter=Dr,m.AcEdCorsorType=Ie,m.AcEdCursorManager=Xl,m.AcEdGripEditSession=Wl,m.AcEdGripHandle=Vn,m.AcEdGripManager=Zl,m.AcEdGripPreviewJig=Hl,m.AcEdHoverController=gc,m.AcEdInputManager=qn,m.AcEdKeyword=Rr,m.AcEdKeywordCollection=oc,m.AcEdMTextEditor=$e,m.AcEdMarker=Rn,m.AcEdMarkerManager=zr,m.AcEdOpenMode=z,m.AcEdOsnapResolver=wt,m.AcEdPreviewJig=G,m.AcEdPromptAngleOptions=Ce,m.AcEdPromptBoxOptions=Un,m.AcEdPromptBoxResult=Hn,m.AcEdPromptDistanceOptions=ke,m.AcEdPromptDoubleOptions=se,m.AcEdPromptDoubleResult=Pe,m.AcEdPromptEntityOptions=Ze,m.AcEdPromptEntityResult=$n,m.AcEdPromptIntegerOptions=Gr,m.AcEdPromptIntegerResult=Yn,m.AcEdPromptKeywordOptions=re,m.AcEdPromptNumericalOptions=Wn,m.AcEdPromptNumericalResult=Vr,m.AcEdPromptOptions=Ye,m.AcEdPromptPointOptions=I,m.AcEdPromptPointResult=Zn,m.AcEdPromptResult=ze,m.AcEdPromptSelectionOptions=_t,m.AcEdPromptSelectionResult=Ti,m.AcEdPromptStateMachine=Xe,m.AcEdPromptStatus=b,m.AcEdPromptStringOptions=ue,m.AcEdSelectionFilter=Uy,m.AcEdSelectionSet=Kn,m.AcEdSelectionStaticPreviewJig=yc,m.AcEdSelectionTransformPreviewJig=Zt,m.AcEdViewKeyHandler=Tn,m.AcEdViewMode=fe,m.AcEditor=mc,m.AcTrGeometryUtil=Yo,m.AcTrInheritedLayerMaterialMapper=Sl,m.AcTrLayerAppearanceController=Pr,m.AcTrScene=Ml,m.AcTrView2d=ai,m.AcUiAboutDialog=Bs,m.AcUiDialog=Ns,m.DEFAULT_VIEW_2D_OPTIONS=Jo,m.DWG_CONVERTER_PACKAGE=Yb,m.DWG_PARSER_MAIN_FILE=Hb,m.DWG_PARSER_WORKER_FILE=Ub,m.ENTITY_EDIT_LABEL=Cl,m.ICON_ANNOTATION=Lw,m.ICON_ANNOTATION_HIDE=wp,m.ICON_ANNOTATION_SHOW=bp,m.ICON_CHEVRON_DOWN=Qw,m.ICON_CHEVRON_LEFT=tv,m.ICON_CHEVRON_RIGHT=ev,m.ICON_CHEVRON_UP=Jw,m.ICON_CLEAR=ea,m.ICON_CLEAR_MARKUPS=Fw,m.ICON_CLEAR_MEASUREMENTS=Pw,m.ICON_COLOR=lv,m.ICON_DOCK_CLOSE=Xw,m.ICON_DOCK_SIDE_MENU=qw,m.ICON_EXPORT=Vw,m.ICON_EXPORT_HTML=Gw,m.ICON_EXPORT_PDF=Kw,m.ICON_EXPORT_SVG=Uw,m.ICON_LANGUAGE=jw,m.ICON_LAYER=ww,m.ICON_LAYER_OFF=sv,m.ICON_LAYER_ON=nv,m.ICON_LAYOUT=vw,m.ICON_MARKUP_ARROW=Dw,m.ICON_MARKUP_CALLOUT=Ew,m.ICON_MARKUP_CIRCLE=pv,m.ICON_MARKUP_CLOUD=uv,m.ICON_MARKUP_EXPORT=fp,m.ICON_MARKUP_HIDE=yv,m.ICON_MARKUP_HIGHLIGHT=Mw,m.ICON_MARKUP_IMPORT=Bw,m.ICON_MARKUP_LINE=Iw,m.ICON_MARKUP_PANEL=Nw,m.ICON_MARKUP_RECT=hv,m.ICON_MARKUP_SHOW=mv,m.ICON_MARKUP_STAMP=Ow,m.ICON_MARKUP_TEXT=Tw,m.ICON_MEASURE=kw,m.ICON_MEASURE_ANGLE=Sw,m.ICON_MEASURE_ARC=Cw,m.ICON_MEASURE_AREA=Aw,m.ICON_MEASURE_COORDINATE=dv,m.ICON_MEASURE_DISTANCE=xw,m.ICON_MEASURE_POINT=pp,m.ICON_ORTHO_MODE=ov,m.ICON_OSNAP=rv,m.ICON_PAN=fw,m.ICON_PLACEMENT_BOTTOM=$w,m.ICON_PLACEMENT_LEFT=Yw,m.ICON_PLACEMENT_RIGHT=Zw,m.ICON_PLACEMENT_TOP=Ww,m.ICON_POLAR_TRACKING=av,m.ICON_REV_CIRCLE=gp,m.ICON_REV_CLOUD=mp,m.ICON_REV_RECT=yp,m.ICON_SELECT=gw,m.ICON_SWITCH_BG=_w,m.ICON_THEME_DARK=Rw,m.ICON_THEME_LIGHT=zw,m.ICON_TOOLBAR_PLACEMENT=Hw,m.ICON_ZOOM_BOX=cv,m.ICON_ZOOM_EXTENT=bw,m.ICON_ZOOM_ORIGINAL=iv,m.ICON_ZOOM_WINDOW=hp,m.LAYER_EDIT_LABEL=$,m.LAYER_FROZEN_FLAG=Ar,m.LAYER_LOCKED_FLAG=Gt,m.LIBREDWG_CONVERTER_PACKAGE=Wb,m.LIBREDWG_PARSER_WASM_FILE=Kb,m.LIBREDWG_PARSER_WORKER_FILE=Gb,m.MARKUP_FONT_SIZE=gu,m.MARKUP_LAYER=fn,m.MARKUP_LINE_WEIGHT=As,m.MARKUP_LIVE_LAYER=de,m.MARKUP_OPEN_MODE=_u,m.MARKUP_STATUSES=wa,m.MEASUREMENT_ANGLE_FORMAT_OPTIONS=xa,m.MEASUREMENT_FONT_SIZE=jt,m.MEASUREMENT_LAYER=Y,m.MEASUREMENT_LENGTH_FORMAT_OPTIONS=ka,m.MEASUREMENT_LINE_WEIGHT=Ft,m.MEASUREMENT_LIVE_LAYER=le,m.MLIGHTCAD_BRAND_NAME=hn,m.MLIGHTCAD_DOCS_URL=aa,m.MLIGHTCAD_ICON_SVG=ra,m.MLIGHTCAD_REPO_URL=la,m.MLIGHTCAD_WEBSITE_URL=oa,m.ML_UI_COMPACT_MAX_WIDTH=Rl,m.ML_UI_COMPACT_MEDIA_QUERY=Vl,m.ML_UI_MOBILE_MAX_WIDTH=jl,m.ML_UI_MOBILE_MEDIA_QUERY=zl,m.MTEXT_RENDERER_PACKAGE=$b,m.MTEXT_RENDERER_WORKER_FILE=Xh,m.POLARMODE_ADDITIONAL_ANGLES=Ql,m.POLARMODE_POLAR_TRACKING=Yt,m.REVCLOUD_BULGE=fo,m.REVIEW_OVERLAY_HIT_THRESHOLD_PX=qa,m.acapActiveMarkupSessionId=Ip,m.acapBindCommandServices=Fl,m.acapBindMarkupSession=yi,m.acapBindOverlayCalloutGrips=ks,m.acapBindOverlayPointerDrag=Mt,m.acapCloneMeasurementStyle=fi,m.acapColorToCssAlpha=dr,m.acapCommandServices=Li,m.acapCreateMlightcadBrandMark=ca,m.acapCreateMlightcadIcon=Xs,m.acapCssColor=Se,m.acapCssToMeasurementColor=ur,m.acapDisposeMarkupSession=sr,m.acapDrawOverlayArrowHead=vs,m.acapDrawOverlayHighlight=Co,m.acapDrawOverlayLeader=Ao,m.acapDrawStyleKindForCommand=Th,m.acapFitOverlayCanvas=It,m.acapGetCurrentMeasurementStyle=pt,m.acapGetMeasurementColor=Be,m.acapGetMeasurementFontSize=Fe,m.acapGetMeasurementLineWeight=st,m.acapInstallOpenFileDialog=Wh,m.acapIsDrawStyleHostRibbonVisible=Mh,m.acapIsDrawStyleToolbarVisible=Cb,m.acapMeasurementCanvasLineWidth=Te,m.acapNotifyUndoStackChanged=mt,m.acapPlaceOverlayHtml=Je,m.acapPointerEventToOverlayWorld=_o,m.acapResetMeasurementDrawStyle=jp,m.acapResolveDrawStyleKind=Ih,m.acapRunDatabaseEdit=yt,m.acapRunServiceEdit=W,m.acapSetDrawStyleHostHasRibbon=Ab,m.acapSetDrawStyleToolbarVisible=Ko,m.acapSetMarkupBagFactory=ga,m.acapSetMeasurementDrawColor=Ca,m.acapSetMeasurementDrawFontSize=_a,m.acapSetMeasurementDrawLineWeight=Pa,m.acapShouldShowDrawStyleToolbar=Dh,m.acapSubscribeDrawStyleToolbarVisibility=Pb,m.acapUninstallOpenFileDialog=Yh,m.acapUpdateOpenFileDialogOptions=$h,m.acapWithSecondaryDatabase=xo,m.accumulateSketchPoint=Td,m.acedAlert=Zm,m.acedApplyUiTheme=Or,m.acedIsCompactUiLayout=Jm,m.acedIsMobileUiLayout=qm,m.applyMarkupStyleToSelection=Is,m.applyMeasurementStyle=fr,m.applyMeasurementStyleToSelection=kn,m.applySessionHiddenObjectState=pw,m.attachCalloutToMarkup=ju,m.bindMarkupCalloutGrips=eb,m.bindMarkupCenterMove=Xi,m.bindMarkupInlineTextEdit=Fn,m.bindMarkupPointerDrag=Qf,m.bindMeasurementOverlayHistory=Na,m.bindOverlayHistory=La,m.buildMarkupCloud=Vf,m.buildMarkupRect=Gf,m.buildRevCloud=Pd,m.canvasBackgroundFromColor=wl,m.clearLayoutMeasurements=Rd,m.cmdDescription=Kr,m.collectMeasurementRecords=Wa,m.collectMemorySnapshot=fh,m.collectReviewOverlayIdsByBox=tl,m.commitMarkup=Ue,m.commitMeasurementGroup=Ya,m.computeLeaderTipOnShape=ri,m.configureMarkupCommand=Ge,m.constrainToOrtho=Jl,m.constrainToTracking=rc,m.createDefaultMarkupColor=Do,m.createIconElement=gv,m.createMarkupEntity=Yf,m.createMarkupEntityFromRecord=Ts,m.createMarkupId=Su,m.createMarkupMeta=Ke,m.createMeasureEntityFromRecord=Xd,m.createRotationMatrix=Xt,m.cssToMarkupColor=Bo,m.cursorColorForBackground=Ln,m.defaultMarkupColor=ee,m.defaultMarkupStyle=Ps,m.defaultRevCloudArcLength=xd,m.deserializeMeasurementStyle=Ba,m.distPointToArcPx=Qs,m.distPointToCirclePx=Js,m.distPointToPolylinePx=qs,m.distPointToRectOutlinePx=pn,m.distPointToSegmentPx=At,m.distance2d=Et,m.drawMeasureAngleArcOnCanvas=Ud,m.drawMeasureArcOnCanvas=Wd,m.drawMeasureAreaOnCanvas=Hd,m.drawMeasureSegmentOnCanvas=Kd,m.editMarkupHtmlText=Ir,m.ensureCounterClockwise=Ad,m.eventBus=ie,m.foregroundColorFromColorTheme=Pm,m.formatMeasurementAngle=bn,m.formatMeasurementLength=Ee,m.formatMeasurementValue=ar,m.formatMemoryBytes=ph,m.geBox2dToThreeBox2d=sp,m.geBox2dToThreeBox3d=op,m.geBox3dToGeBox2d=tp,m.geBox3dToThreeBox3d=ip,m.getActiveMarkupBag=mi,m.getActiveMeasurementStyle=Ka,m.getDrawingExportBaseName=wc,m.getEffectiveMeasurementUnits=or,m.getLastFontLoadStats=Vh,m.getLayerIsoState=Cr,m.getMarkupAuthor=Cu,m.getMarkupFontSize=Qe,m.getMarkupHistory=we,m.getMarkupLineWeight=_e,m.getMarkupPresenter=tt,m.getMarkupStore=H,m.getMarkupStoreForSession=Dp,m.getMeasurementGeometry=br,m.getMeasurementHistory=rt,m.getMeasurementStyle=Pt,m.getMeasurementUnitOverride=Np,m.getPolaraddang=ic,m.getPolarang=tc,m.getPolarmode=Gn,m.getSelectedMeasurementId=Ga,m.getSessionUndo=Ct,m.hideObjects=dp,m.hitTestMarkupGeometry=ir,m.hitTestMarkupShapeOutline=tr,m.hitTestMeasurementGeometry=rr,m.isAttachableShapeMarkup=ui,m.isDirectBatchCandidate=Em,m.isEffectiveSpatialQueryHit=Mn,m.isInsertableBlockName=ad,m.isLightColorTheme=_m,m.isMarkupDoublePointer=Bl,m.isMarkupHtmlTextEditing=Nl,m.isMarkupShapeCalloutEnabled=Kf,m.isMarkupVisible=pb,m.isMeasurementVisible=yr,m.isModelSpaceDatabase=bl,m.isOpenFileProgressComplete=Zh,m.isOrthoModeEnabled=ql,m.isPolarTrackingEnabled=nc,m.isRevCloudCloseToStart=wo,m.isSameLayerIsoState=Al,m.isScriptQuitCommand=Rh,m.layoutBackgroundSysVar=Sr,m.listMarkupsForSession=Mp,m.markupCanvasLineWidth=Ve,m.markupCloudVertices=$i,m.markupColorToCss=Dt,m.markupDrawStyleFromRecord=Pu,m.markupGeometryBounds=ma,m.markupGeometryCenter=yn,m.markupNow=Au,m.markupRectCorners=Lu,m.markupShapeOutlineFromGeometry=ya,m.markupSidecarFileName=Yu,m.measureAngleDeg=Yd,m.measureCentroid=So,m.measureShoelaceArea=$d,m.measurementGeometryBounds=va,m.measurementSidecarFileName=za,m.migrateStoredSettings=Gl,m.parseMarkupSidecar=Wu,m.parseMeasurementSidecar=Fa,m.parseScriptLines=Uo,m.pickAttachableShapeMarkupAt=el,m.pickMeasurementAt=Za,m.placeAngleMeasurement=eu,m.placeArcMeasurement=Mo,m.placeAreaMeasurement=iu,m.placeDistanceMeasurement=du,m.placeMarkupHtml=Jf,m.placeMeasurementRecord=qd,m.placePointMeasurement=pu,m.pointInPolygonPx=ua,m.pointInRectPx=da,m.pointerEventToMarkupWorld=qf,m.preferExactAciColor=gi,m.promptAttachedCallout=Yi,m.promptMarkupCapsuleText=_s,m.promptMarkupText=Fo,m.promptShapeFirstCorner=Es,m.publishAttachedCallout=Tu,m.readLayoutBackgroundColor=_n,m.rectanglePath=bo,m.refreshMeasurementValueLabels=Yp,m.registerMarkupPublish=yu,m.republishMarkup=Wi,m.resetExportDownloadNamesForTests=Hy,m.resetMarkupSession=jo,m.resetMeasurementSession=mr,m.resetMeasurementStyleState=$a,m.resetMeasurementUnitOverride=Sa,m.resetMeasurementVisibility=Ra,m.resolveExportDownloadName=Xr,m.resolvePointerSelectionAction=fc,m.resolveSelectedEntities=Qn,m.resolveSelectedIds=Tc,m.resolveSelectionActionFromEvent=Yr,m.resolveUiTheme=Nr,m.runMarkupEdit=ve,m.runMeasurementEdit=zt,m.sampleEntityPath=Ld,m.scaleCopyDisplacement=Jn,m.selectMarkupGroup=Zi,m.serializeMeasurementStyle=gt,m.setMarkupDrawColor=vu,m.setMarkupDrawFontSize=xu,m.setMarkupDrawLineWeight=ku,m.setMarkupShapeCalloutEnabled=Uf,m.setMarkupVisible=ih,m.setMeasurementUnitOverride=Bp,m.setMeasurementVisible=Va,m.shouldExtendBboxForDirectEntity=xl,m.signedArea=Sd,m.simplifySketchPoints=Id,m.stringifyMarkupSidecar=$u,m.stringifyMeasurementSidecar=ja,m.strokeMarkupCloud=Eu,m.strokeMeasureArcOnContext=ws,m.subscribeMarkupDrawStyle=Cs,m.subscribeMeasurementSelection=Ua,m.sysCmdDescription=Oy,m.tessellateMarkupCloud=Ls,m.threeBox2dToGeBox2d=np,m.threeBox3dToGeBox2d=rp,m.threeBox3dToGeBox3d=ep,m.toggleBlackWhiteBackgroundColor=vl,m.togglePolarTracking=vy,m.translateAttachedCallout=mn,m.translateMarkupGeometry=er,m.translateMarkupPoint=ce,m.tryBuildDirectEntityMeta=kl,m.trySelectReviewOverlay=il,m.trySelectReviewOverlaysByBox=nl,m.unionSpatialQueryItems=In,m.uniquifySpatialItemIds=Pl,m.unisolateObjects=up,m.userCmdDescription=Ny,m.viewDiagonalLength=kd,m.withMarkupInput=et,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));