@mlightcad/cad-simple-viewer 1.7.8-preview.4 → 1.7.8-preview.5

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.
@@ -2656,7 +2656,7 @@
2656
2656
  .${H}__group-body .${H}__item {
2657
2657
  padding-left: 20px;
2658
2658
  }
2659
- `,document.head.appendChild(e)}class OE{constructor(){this._center=new Ca,this._defaultStore=this._center,this._showDefaultUi=!0,this._isCustom=!1}install(e,t={}){var i;this._docManager=e,this._host=t.host,this._showDefaultUi=t.showDefaultUi!==!1,this._placement=t.placement,t.enableBridge!==!1?((i=this._bridge)==null||i.uninstall(),this._bridge=new Gv(e,()=>this.center),this._bridge.install()):this._center.setActiveSession(e.activeSessionId),!this._isCustom&&this._showDefaultUi&&this.mountDefaultUi()}get placement(){return this._placement}setPlacement(e){var t;this._placement=e,(t=this._defaultUi)==null||t.setPlacement(e)}get center(){return this._center}get isCustom(){return this._isCustom}setCenter(e){var t,i;if(e==null){this.restoreDefault();return}this._center!==e&&(this.disposeDefaultUi(),this._isCustom?(i=(t=this._center).dispose)==null||i.call(t):this._defaultStore.dispose(),this._center=e,this._isCustom=!0,this._docManager&&this._center.setActiveSession(this._docManager.activeSessionId))}restoreDefault(){var e,t;if(!this._isCustom){this._showDefaultUi&&!this._defaultUi&&this.mountDefaultUi();return}(t=(e=this._center).dispose)==null||t.call(e),this._defaultStore=new Ca,this._center=this._defaultStore,this._isCustom=!1,this._docManager&&this._center.setActiveSession(this._docManager.activeSessionId),this._showDefaultUi&&this.mountDefaultUi()}resolveHost(){var t,i;if(this._host)return this._host;const e=(i=(t=this._docManager)==null?void 0:t.curView)==null?void 0:i.container;return e||document.body}mountDefaultUi(){this.disposeDefaultUi(),!(typeof document>"u")&&(this._defaultUi=new Wv(this._center,this.resolveHost(),{placement:this._placement}))}disposeDefaultUi(){var e;(e=this._defaultUi)==null||e.dispose(),this._defaultUi=void 0}dispose(){var e,t,i;(e=this._bridge)==null||e.uninstall(),this._bridge=void 0,this.disposeDefaultUi(),(i=(t=this._center).dispose)==null||i.call(t),this._defaultStore=new Ca,this._center=this._defaultStore,this._isCustom=!1,this._docManager=void 0,this._host=void 0,this._showDefaultUi=!0,this._placement=void 0}}const Wi=new OE;function DE(){return Wi.center}function NE(s){Wi.setCenter(s)}function BE(){return Wi.placement}function FE(s){Wi.setPlacement(s??void 0)}function Xv(s,e){Wi.install(s,e)}function qv(){Wi.dispose()}function zE(s){var r;const e=s.tables.blockTable,t=e.getAt(p.AcDbBlockTableRecord.PAPER_SPACE_NAME_PREFIX);if(t)return t.objectId;const i=(r=s.objects)==null?void 0:r.layout;if(!(i!=null&&i.newIterator))return;const n=e.modelSpace.objectId;let o;for(const a of i.newIterator()){const l=a.blockTableRecordId;if(!l||l===n)continue;const c=e.getIdAt(l);if(!(!c||!p.AcDbBlockTableRecord.isPaperSapceName(c.name))){if(a.tabSelected)return l;o||(o=l)}}return o}function RE(s){const e=s.tables.blockTable.modelSpace.objectId;if(s.tilemode){s.currentSpaceId!==e&&(s.currentSpaceId=e);return}const t=zE(s);t&&t!==s.currentSpaceId&&(s.currentSpaceId=t)}const jE="https://cdn.jsdelivr.net/gh/mlightcad/cad-data",VE="templates/acadiso.dxf",GE={ARC:["A"],CIRCLE:["C"],ELLIPSE:["EL"],ERASE:["E"],DIMLINEAR:["DLI"],DIMALIGNED:["DAL","DIMALI"],DIMRADIUS:["DRA","DIMRAD"],DIMDIAMETER:["DDI","DIMDIA"],DIMANGULAR:["DAN","DIMANG"],DIMARC:["DAR"],DIMORDINATE:["DOR"],DIMCONTINUE:["DCO"],DIMBASELINE:["DBA"],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"],READINGMODE:["RM"]},HE="modern";class k{constructor(e={}){var c;this._sessions=[],this._nextSessionId=1,this._openFileProfiler=new ka,this._workersReady=null,this._nextOverlayId=1,this._presetFontsForOpenPromise=null,this._lastPresetFontsForOpen=[],this.events={documentToBeOpened:new p.AcCmEventManager,documentCreated:new p.AcCmEventManager,documentActivated:new p.AcCmEventManager,documentToBeActivated:new p.AcCmEventManager,documentToBeDestroyed:new p.AcCmEventManager,documentDestroyed:new p.AcCmEventManager,workersReady:new p.AcCmEventManager},this._baseUrl=e.baseUrl??jE,Gu(e.docsBaseUrl??ao),this._commandAliasOverrides=this.normalizeCommandAliasConfig(e.commandAliases),this._openDocumentDefaults=e.openDocumentDefaults,this._disableExport=e.disableExport===!0,e.useMainThreadDraw?D.AcTrMTextRenderer.getInstance().setRenderMode("main"):D.AcTrMTextRenderer.getInstance().setRenderMode("worker"),$.FontManager.instance.setDefaultFonts(HE),$.FontManager.instance.lazyFontLoading=!0,$.FontManager.instance.awaitFontsBeforeDraw=!0,D.AcTrMTextRenderer.getInstance().setLazyFontLoading(!0),D.AcTrMTextRenderer.getInstance().setAwaitFontsBeforeDraw(!0);const t=new ba,i=((c=e.container)==null?void 0:c.getBoundingClientRect())??{width:300,height:150},n=()=>{var d;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 f=(d=e.container)==null?void 0:d.getBoundingClientRect();return{width:Math.max(1,Math.floor((f==null?void 0:f.width)??i.width)),height:Math.max(1,Math.floor((f==null?void 0:f.height)??i.height))}}else return{width:e.width??i.width,height:e.height??i.height}},o=new Mn({container:e.container,calculateSizeCallback:n});this._mainView=o;const r=new Ea(o,t);this._activeSession=new ya(`doc-${this._nextSessionId++}`,r),this._sessions=[this._activeSession],Hn(this._activeSession.id),this._fontLoader=new dv,$.FontManager.instance.setFontLoader(this._fontLoader.fontLoader);const a=this.resolveFontsBaseUrl();this._fontLoader.baseUrl=a,$.FontManager.instance.baseUrl=a,D.AcTrMTextRenderer.getInstance().setFontUrl(a),this.installFontFileLoadTimeout(),p.acdbHostApplicationServices().workingDatabase=t.database,this._commandManager=new Me,this.registerCommands(),p.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(d=>{const h=d.name.toUpperCase();(h===p.AcDbSystemVariables.CANNOSCALE||h===p.AcDbSystemVariables.ANNOALLVISIBLE)&&this.regen()}),this._pluginManager=new av(this.context,this._commandManager),this._dataSourceManager=new xv,this._dataSourceManager.register(new hv),this._dataSourceManager.register(new kv);const l=e.busyIndicatorHost??o.container;if(this._busyIndicatorHost=l,this._openFileProgress=new Qd(l),this._openFileProgress.setSceneBusyGate(()=>this.openProgressView.isProcessingEntities),this._openFileProgress.setOnHidden(()=>this.onOpenProgressHidden()),this._busyIndicator=new X1(l),Pp({showMessage:(d,h,f)=>this.editor.showMessage(d,h,f),showBusyIndicator:d=>this.showBusyIndicator(d),hideBusyIndicator:()=>this.hideBusyIndicator(),withBusyIndicator:(d,h)=>this.withBusyIndicator(d,h)}),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(d=>{p.log.error("[AcApDocManager] Error loading plugins:",d)}),mv({enabled:e.builtinOpenFileDialog!==!1,getOpenDocumentDefaults:()=>this.resolveOpenDocumentDefaults()}),e.notificationCenter!==!1){const d=typeof e.notificationCenter=="object"?e.notificationCenter:{};Xv(this,{host:d.host,showDefaultUi:d.showDefaultUi!==!1,placement:d.placement,enableBridge:!0})}}static createInstance(e={}){return k._instance==null&&(k._instance=new k(e)),this._instance}static checkWebworkerReadiness(e){return vv(e)}static get instance(){if(!k._instance)throw new Error("AcApDocManager instance is not created yet!");return k._instance}static tryGetInstance(){return k._instance}async destroy(){var e,t;this._mainView.abortConversion(),(e=this._splitView)==null||e.abortConversion(),await this._pluginManager.unloadAllPlugins();for(const i of[...this._sessions])i.context.dispose(),i.doc.destroy(),i.viewState&&this.curView.disposeSessionState(i.viewState);this._sessions=[],(t=this._splitView)==null||t.dispose(),this._splitView=void 0,this._mainView.dispose(),yv(),qv(),D.AcTrMTextRenderer.resetInstance(),uE(),k._instance=void 0}get workersReady(){return this._workersReady}areWorkersReady(){return this._workersReady===!0?Promise.resolve(!0):(this._workersReadyCheckPromise||(this._workersReadyCheckPromise=vv(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()),Hn(t.id),p.acdbHostApplicationServices().workingDatabase=e.database,this._pluginManager.setContext(t.context),this.curView.bindDrawDatabase(e.database),this.setActiveLayout(),this.curView.syncDisplaySysVars(e.database),this.events.documentActivated.dispatch({doc:e,mode:e.openMode}),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 Mn({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,o=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),tl(i.id);const r=i.context.view;if(i.viewState?(r.disposeSessionState(i.viewState),i.viewState=void 0):r.clear(),this._sessions.splice(o,1),this.events.documentDestroyed.dispatch({doc:t,mode:t.openMode}),n){const a=this._sessions[Math.min(o,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 dataSourceManager(){return this._dataSourceManager}get drawStyleSessionAccessory(){return Vy(this._mainView)}get baseUrl(){return this._baseUrl}get disableExport(){return this._disableExport}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 getAvaiableFonts(){try{return await this._fontLoader.getAvaiableFonts()}catch{return Q.emit("failed-to-get-avaiable-fonts",{url:this._fontLoader.baseUrl}),[]}}async loadFonts(e){await this._fontLoader.load(e)}async loadDefaultFonts(e){e==null?await this._fontLoader.load([...$.FontManager.instance.getFontsToLoad()]):await this._fontLoader.load(e)}ensurePresetFontsForOpen(){if(this._presetFontsForOpenPromise)return this._presetFontsForOpenPromise;const e=[...$.FontManager.instance.getFontsToLoad()];if(this._lastPresetFontsForOpen=e,e.length===0)return this._presetFontsForOpenPromise=Promise.resolve(),this._presetFontsForOpenPromise;const t=D.AcTrMTextRenderer.getInstance(),i=t.getRenderMode()==="worker"?"worker":"main",n=3e4,o=i==="worker"?t.loadFonts(e,{scope:"all"}).then(()=>{}):$.FontManager.instance.requestFonts(e).then(()=>{});return this._presetFontsForOpenPromise=new Promise(r=>{const a=setTimeout(()=>{r()},n);o.then(()=>{clearTimeout(a),r()},()=>{clearTimeout(a),r()})}),this._presetFontsForOpenPromise}async awaitPresetFontsReady(){await this.ensurePresetFontsForOpen()}get lastPresetFontsForOpen(){return this._lastPresetFontsForOpen}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 o=await this.ensureOpenSession(n);this.beginOpenProgress(),this.onBeforeOpenDocument(i,!o);try{await this._openFileProgress.beginOpen(this.context.doc.database);const r=await this.context.doc.openDocument(e,t,i);return this.onAfterOpenDocument(r,i),!r&&o&&await this.closeFailedOpenSession(),r}catch(r){throw this._openFileProfiler.cancel(),o&&await this.closeFailedOpenSession(),r}}async loadOverlay(e,t,i={}){var l;const{targetView:n,...o}=i,r=new p.AcDbDatabase,a=(l=e.split(".").pop())==null?void 0:l.toLocaleLowerCase();return await Fd(r,async()=>{await r.read(t,{readOnly:!0,...o},a==="dwg"?p.AcDbFileType.DWG:p.AcDbFileType.DXF)}),this.registerOverlayDatabase(r,{targetView:n})}async registerOverlayDatabase(e,t){const i=(t==null?void 0:t.targetView)??this.curView,n=await i.addOverlayEntities(e),o=`overlay-${this._nextOverlayId++}`;return(this._sessions.find(a=>a.context.view===i)??this._activeSession).overlays.set(o,{db:e,layout:n}),i.isDirty=!0,o}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)}isReadingModeEnabled(e){return(e??this.curView).readingModeEnabled}setReadingMode(e,t){(t??this.curView).setReadingMode(e)}toggleReadingMode(e){(e??this.curView).toggleReadingMode()}setOverlayCompareDisplay(e,t,i){for(const n of this._sessions){const o=n.overlays.get(e);if(!o)continue;return(i??n.context.view??this.curView).setCompareDisplay(t,o.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}/`}${VE}`,n=this.setOptions({...e,mode:U.Write}),o=await this.ensureOpenSession();this.beginOpenProgress(),this.onBeforeOpenDocument(n,!o),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&&o&&await this.closeFailedOpenSession(),r}setOpenDocumentDefaults(e){this._openDocumentDefaults=e,fv({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()}installFontFileLoadTimeout(){const t=$.FontManager.instance.loader;if(!t||t.__cadFontLoadTimeout)return;const i=t.loadAsync.bind(t),n=3e4;t.loadAsync=o=>new Promise((r,a)=>{const l=setTimeout(()=>{a(new Error(`Font load timed out after ${n}ms`))},n);i(o).then(c=>{clearTimeout(l),r(c)},c=>{clearTimeout(l),a(c)})}),t.__cadFontLoadTimeout=!0}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,o,r)=>{const a=GE[n.toUpperCase()]??[];e.addCommand(Me.SYSTEMT_COMMAND_GROUP_NAME,n,o,r,this.resolveCommandAliases(n,a))};t("about","about",new Gw),t("arc","arc",new gg),t("cachefont","cachefont",new Us),t("circle","circle",new Sg),t("close","close",new qw),this._disableExport||(t("bmpout","bmpout",new Wy),t("cdxf","cdxf",new Ky),t("jpgout","jpgout",new Yy),t("pngout","pngout",new Zy)),t("entout","entout",new Jy),t("ellipse","ellipse",new sb),t("erase","erase",new Nw),t("hideobjects","hideobjects",new Bw),t("dimlinear","dimlinear",new Xg),t("dimaligned","dimaligned",new Og),t("dimradius","dimradius",new eb),t("dimdiameter","dimdiameter",new Yg),t("dimangular","dimangular",new Ng),t("dimarc","dimarc",new zg),t("dimordinate","dimordinate",new Jg),t("dimcontinue","dimcontinue",new Wg),t("dimbaseline","dimbaseline",new $g),pw(t,{view:this._mainView,commandManager:this._commandManager}),t("-hatch","-hatch",new Zr),t("imageattach","imageattach",new ob),t("-insert","-insert",new ab),t("xattach","xattach",new Fb),t("-layer","-layer",new dg),t("laycur","laycur",new ig),t("laydel","laydel",new tg),t("layfrz","layfrz",new Fr),t("layiso","layiso",new zr),t("laylck","laylck",new ng),t("layon","layon",new sg),t("layoff","layoff",new Rr),t("laythw","laythw",new rg),t("layuniso","layuniso",new ag),t("layulk","layulk",new lg),t("layerp","layerp",new og),t("layerclose","layerclose",new cg),t("line","line",new ji),t("mline","mline",new cb),t("mtext","mtext",new db),t("copy","copy",new ha),t("move","move",new zw),t("offset","offset",new Gs),t("rotate","rotate",new ma),t("log","log",new Hw),t("objectscale","objectscale",new Xw),t("open","open",new Zw),t("pan","pan",new rv),t("point","point",new ub),t("polygon","polygon",new Jr),t("pline","pline",new fb),t("qnew","qnew",new Jw),t("ray","ray",new gb),t("rectang","rectang",new Qr),t("regen","regen",new Qw),t("revcloud","revcloud",new ea),Dw(t,{view:this._mainView,commandManager:this._commandManager}),t("select","select",new ev),t("sketch","sketch",new sa),t("spline","spline",new Ob),t("switchbg","switchbg",new iv),t("readingmode","readingmode",new nv),t("unisolateobjects","unisolateobjects",new Vw),t("xline","xline",new zb),t("undo","undo",new sv),t("redo","redo",new ov),t("zoom","zoom",new yi),p.AcDbSysVarManager.instance().getAllDescriptors().forEach(n=>{e.addCommand(Me.SYSTEMT_COMMAND_GROUP_NAME,n.name,n.name,new tv,this.resolveCommandAliases(n.name,[]))})}normalizeCommandAliasConfig(e){const t=new Map;return e&&Object.entries(e).forEach(([i,n])=>{const o=i.trim().toUpperCase();if(!o)return;const r=Array.isArray(n)?n:[n],a=new Set;r.forEach(l=>{const c=l.trim().toUpperCase();c&&c!==o&&a.add(c)}),t.set(o,[...a])}),t}resolveCommandAliases(e,t){const i=e.trim().toUpperCase(),n=this._commandAliasOverrides.get(i);if(n)return[...n];const o=new Set;return t.forEach(r=>{const a=r.trim().toUpperCase();a&&a!==i&&o.add(a)}),[...o]}sendStringToExecute(e){this.executeCommandString(e).catch(t=>{const i=t instanceof Error?t.message:String(t);this.editor.showMessage(i,"error"),p.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=Xd(e);for(this.editor.clearScriptInputs(),this.editor.enqueueScriptInputs(t);this.editor.hasScriptInputs();){const i=this.consumeNextScriptCommandName();if(i==null)break;if(lv(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 '${U[n.mode]}' but document is in mode '${U[i]}'!`);await this._commandManager.cancelActive(),await this._commandManager.runActive(n,this.curView,async()=>{try{await n.trigger(this.context)}finally{t.preserveScriptInputs||this.editor.clearScriptInputs()}})}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=Xd(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&&(Si.instance.clearAll(),this.clearOverlays(),vl(),Jc(),yi.clearOriginalViews(),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.openProgressView.convertInvisibleLayers=(e==null?void 0:e.convertInvisibleLayers)===!0,this.openProgressView.cooperativeYield=(e==null?void 0:e.cooperativeYield)!==!1;const i=this.openProgressView.cadScene;i&&(i.skipSpatialIndex=(e==null?void 0:e.skipSpatialIndex)===!0),this.ensurePresetFontsForOpen(),this._openFileProfiler.begin(this.context.doc.database)}onAfterOpenDocument(e,t){const i=!e&&this.hasRecoverablePartialContent();if(e||i){const n=this._openingSession??this._activeSession,o=n.context.view;n.doc.destroy();const r=n.doc,a=r.database;RE(a),this.setActiveLayout(o,a),o.syncDisplaySysVars(a),this.events.documentActivated.dispatch({doc:r,mode:this.getDocumentEventMode(t)});const l=a.tables.blockTable.modelSpace.objectId,c=a.currentSpaceId!==l,d=p.acdbHostApplicationServices().layoutManager.getActiveLayout(a),h=d==null?void 0:d.limits,f=this.resolveOpenViewMode(t);o.setOpenViewMode(f);const y=(t==null?void 0:t.progressiveRendering)??!1;let g=!1;const b=()=>{y&&o.beginProgressiveOpenFit(),o.zoomToFitDrawing(),o.requestOpenLineworkFrame()};if(c&&f===_t.Saved){const w=d==null?void 0:d.extents,S=kr({limits:h,viewportsBox:Ff(a,a.currentSpaceId),layoutExtents:w&&!w.isEmpty()?{min:{x:w.min.x,y:w.min.y},max:{x:w.max.x,y:w.max.y}}:void 0});S?(o.zoomTo(S.box),g=!0):b()}else if(!c&&f===_t.Saved){const w=o.width/Math.max(o.height,1),S=a.tables.viewportTable.getActiveVportBox(w);S?(o.zoomTo(S),g=!0):b()}else b();o.markLayoutAsInitialized(a.currentSpaceId),g&&yi.rememberOriginalView(o,a.currentSpaceId),t!=null&&t.convertAllLayouts&&o.ensureEntitiesConvertedForExport({includeInvisibleLayers:t.convertInvisibleLayers!==!1,includeLayouts:!0}).catch(w=>{p.log.error("[AcApDocManager] convertAllLayouts export convert failed",w)}),this._openFileProfiler.markReadCompleteAndScheduleReport(o)}else this._openFileProfiler.cancel(),this.openProgressView.endProgressiveOpenFit(),this.regen()}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),this.stripDeprecatedWaitForTextGeometry(e),e.drawNoPlotLayers==null&&(e.drawNoPlotLayers=!1),e.progressiveRendering==null&&(e.progressiveRendering=!1)),e}stripDeprecatedWaitForTextGeometry(e){e.waitForTextGeometry!=null&&(delete e.waitForTextGeometry,console.warn("[AcApDocManager] Ignoring deprecated open option waitForTextGeometry; both stages of progressive rendering are controlled by progressiveRendering."))}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)??U.Read}resolveOpenViewMode(e){return(e==null?void 0:e.openViewMode)!=null?e.openViewMode:this.getDocumentEventMode(e)===U.Write?_t.Saved:_t.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)??wv.mtextRender),t.setDefaultFonts([...$.FontManager.instance.defaultFonts])}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&&p.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from config:`,t.loaded),t.failed.length>0&&p.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s):`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){p.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&&p.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from folder:`,t.loaded),t.failed.length>0&&p.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s) from folder:`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){p.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==="STYLE"&&t.subStageStatus==="END"){const o=this._sessions.find(a=>a.doc===e),r=(o==null?void 0:o.context.view)??this.curView;r&&r.startTextStyleFontPreload(e.database)}if(t.subStage!=="HEADER")return;const i=this._sessions.find(o=>o.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 ba,o=new Ea(t,n),r=new ya(`doc-${this._nextSessionId++}`,o);return this._sessions.push(r),this._activeSession=r,Hn(r.id),p.acdbHostApplicationServices().workingDatabase=n.database,this._pluginManager.setContext(o),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;Si.instance.clearAll(),this.clearOverlays(),vl(),Jc(),this.curView.clear(),e.context.dispose(),t.destroy(),tl(i);const n=new ba,o=new Ea(this.curView,n),r=new ya(`doc-${this._nextSessionId++}`,o);this._sessions=[r],this._activeSession=r,Hn(r.id),p.acdbHostApplicationServices().workingDatabase=n.database,this._pluginManager.setContext(o),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 UE=Object.freeze(Object.defineProperty({__proto__:null,AcApDocManager:k},Symbol.toStringTag,{value:"Module"}));class Wt{static isFontLoaded(e){return $.FontManager.instance.isFontLoaded(e)}static getFontType(e){return $.FontManager.instance.getFontType(e)}static getReplacementFontName(e){return $.FontManager.instance.findAndReplaceFont(e)}static getShxCodePoints(e){var o;const t=$.FontManager.instance.getFontByName(e,!1);if(!t||t.type!=="shx")return[];const i=t.data;return Object.keys(((o=i.content)==null?void 0:o.data)??{}).map(r=>Number(r)).filter(r=>Number.isFinite(r)).sort((r,a)=>r-a)}static getLoadedShxFontData(e){const t=$.FontManager.instance.getFontByName(e,!1);if(!(!t||t.type!=="shx"))return t.data}static createShxParserFont(e){return new $.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(o=>o.name.some(r=>r.trim().toLowerCase()===i))}static getCatalogFontType(e){var t;return(t=Wt.findFontInfoByName(e))==null?void 0:t.type}static async ensureDrawingFontLoaded(e){const t=k.instance;t&&(Wt.isFontLoaded(e)||await t.loadFonts([e]))}static async cacheFont(e,t,i,n){return $.FontManager.instance.cacheFont(e,t,i,n)}static async getCachedMeshFontProgram(e){const t=[e],i=Wt.findFontInfoByName(e);i!=null&&i.file&&t.push(i.file);for(const r of(i==null?void 0:i.name)??[])t.push(r);const n=Wt.getReplacementFontName(e);if(n&&n!==e){t.push(n);const r=Wt.findFontInfoByName(n);r!=null&&r.file&&t.push(r.file);for(const a of(r==null?void 0:r.name)??[])t.push(a)}const o=new Set;for(const r of t){const a=r.trim().toLowerCase();if(!a||o.has(a))continue;o.add(a);const l=await $.FontManager.instance.getCachedMeshFontProgram(r);if(l&&l.byteLength>0)return new Uint8Array(l)}}static async persistMeshFontProgram(e,t,i){await $.FontManager.instance.persistMeshFontProgram(e,t,i)}}function Jv(s){const e=[];try{const t=s.tables.textStyleTable;if(e.push(...t.fonts??[]),t.newIterator)for(const i of t.newIterator()){const n=i.textStyle;n!=null&&n.font&&e.push(n.font),n!=null&&n.bigFont&&e.push(n.bigFont),n!=null&&n.extendedFont&&e.push(n.extendedFont)}}catch{return[]}return Zs(e)}function Qv(s,e,t){const i=Zs([...s]);i.length===0&&(t!=null&&t.firstDefaultFont)&&i.push(t.firstDefaultFont);const n=new Set(i.map($i)),o=new Set(e.map($i)),r=Zs(e.filter(l=>!n.has($i(l))));let a=Zs(i.filter(l=>o.has($i(l))));if(a.length===0&&(t!=null&&t.firstDefaultFont)){const l=$i(t.firstDefaultFont);l&&n.has(l)&&(a=[t.firstDefaultFont])}return a.length>3&&(a=a.slice(0,3)),{critical:i,workerWarm:a,background:r}}function Zs(s){const e=new Set,t=[];for(const i of s){if(!i)continue;const n=$i(i);!n||e.has(n)||(e.add(n),t.push(i))}return t}function $i(s){if(s==null)return"";let e=String(s).trim();if(!e)return"";const t=e.lastIndexOf(".");return t>0&&(t===e.length-4||t===e.length-5)&&(e=e.substring(0,t)),e.toLowerCase()}const lu=13,cu=14,du=1,WE=cu*2+du*2,ex=.5,tx=.5;let In;function $E(){if(In!==void 0)return In;if(typeof document>"u")return In=null,null;try{In=document.createElement("canvas").getContext("2d")}catch{In=null}return In}function ix(s){return(s==null?void 0:s.padXEm)??cu/lu}function nx(s){const e=(s==null?void 0:s.borderEm)??du/lu;return e>0?e:0}function uu(s,e){return s>0?2*(ix(e)+nx(e))*s:0}function sx(s,e,t){const i=uu(e,t);if(!(e>0))return i;const n=$E();if(!n)return s.length*e*.6+i;const o=(t==null?void 0:t.fontWeight)??"500",r=(t==null?void 0:t.fontFamily)??"sans-serif";return n.font=`${o} ${e}px ${r}`,n.measureText(s).width+i}function ox(s,e,t,i){if(!(e>0)||!(t>0))return e;const n=(i==null?void 0:i.maxLineFraction)??ex,o=t*n,r=sx(s,e,i);if(r<=o)return e;if(!(o>0))return 1;const l=Math.max(0,r-uu(e,i))/e,c=2*(ix(i)+nx(i)),d=l+c;return d>0?Math.max(1,o/d):e}function xt(s,e,t,i){return e.textHeightMode==="custom"?e.fontSize:ox(s,e.fontSize,t,i)}function Ci(s,e,t){const i=s(e),n=s(t);return Math.hypot(n.x-i.x,n.y-i.y)}function Aa(s,e,t){return!(s>0)||!(e>0)||!(t>0)||t>=e?s:Math.max(1,s*(t/e))}function hu(s,e,t,i){return Math.min(Ci(s,e,t),Ci(s,e,i))*tx}function _a(s,e,t,i){if(!(t>0)||!(i>0))return 0;const n=s(e),o=s({x:e.x+t,y:e.y});return Math.hypot(o.x-n.x,o.y-n.y)/t*i}function KE(s,e,t){const i=t.x-e.x,n=t.y-e.y,o=i*i+n*n;if(!(o>0))return Math.hypot(s.x-e.x,s.y-e.y);let r=((s.x-e.x)*i+(s.y-e.y)*n)/o;return r=Math.max(0,Math.min(1,r)),Math.hypot(s.x-(e.x+r*i),s.y-(e.y+r*n))}function pu(s,e){const t=e.length;if(t<3)return 0;let i=1/0;for(let l=0;l<t;l++){const c=e[l],d=e[(l+1)%t];i=Math.min(i,Ci(s,c,d))}let n=0,o=0;for(const l of e)n+=l.x,o+=l.y;n/=t,o/=t;const r=s({x:n,y:o});let a=1/0;for(let l=0;l<t;l++){const c=s(e[l]),d=s(e[(l+1)%t]);a=Math.min(a,KE(r,c,d))}return Math.min(i,2*a)}const rx=s=>new p.AcGeBox3d(s.min,s.max),ax=s=>new p.AcGeBox2d(s.min,s.max),lx=s=>new V.Box3(s.min,s.max),cx=s=>new p.AcGeBox2d(s.min,s.max),dx=s=>new V.Box2(s.min,s.max),ux=s=>new p.AcGeBox2d(s.min,s.max),hx=s=>{const e=new V.Box3;return e.min.set(s.min.x,s.min.y,0),e.max.set(s.max.x,s.max.y,0),e},mu={threeBo2dToGeBox2d:cx,geBox2dToThreeBox2d:dx,threeBox3dToGeBox3d:rx,geBox3dToThreeBox3d:lx,goBox3dToGeBox2d:ax,threeBox3dToGeBox2d:ux,geBox2dToThreeBox3d:hx};function px(s,e){if(!e||s.length<2)return s;let t=-1,i=-1;for(let r=0;r<s.length&&(s[r].ownerId===e?t<0&&(t=r):i<0&&(i=r),!(t>=0&&i>=0));r++);if(t<0||i<0||t<i)return s;const n=[],o=[];for(let r=0;r<s.length;r++){const a=s[r];a.ownerId===e?n.push(a):o.push(a)}return n.concat(o)}function YE(s,e){return{pending:px(s,e),cursor:0,activeOwnerId:e}}function ZE(s,e,t){if(e.length===0&&t===s.activeOwnerId)return s;const i=s.cursor===0?s.pending:s.pending.slice(s.cursor);if(t!==s.activeOwnerId)return{pending:px(e.length>0?e.concat(i):i,t),cursor:0,activeOwnerId:t};let n=!1;const o=[],r=[];for(let a=0;a<e.length;a++)t&&e[a].ownerId===t?(n=!0,o.push(e[a])):r.push(e[a]);if(n)return{pending:o.concat(i,r),cursor:0,activeOwnerId:t};for(let a=0;a<r.length;a++)s.pending.push(r[a]);return s}function XE(s){const{pending:e,cursor:t,activeOwnerId:i}=s;if(!i)return!1;for(let n=t;n<e.length;n++)if(e[n].ownerId===i)return!0;return!1}function qE(s){const{tookMs:e,budgetMs:t,maxSlice:i,activeLayoutPending:n}=s,o=Math.max(1,s.slice),r=n?2:4;return e<t/2?Math.min(o*r,i):e>t*2?Math.max(1,o>>1):o}class JE{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:on.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 p.AcDbBlockReference}collectMissingEntities(e,t,i){const n=[],o=e.newIterator();for(const r of o)i(r)&&(t(r.objectId)||n.push(r));return n}}var Pa=(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))(Pa||{});class QE extends V.Object3D{constructor(e,t,i=150,n=2){super(),this.camera=e,this.renderer=t,this.gizmoCamera=new V.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 V.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,o=-((t-i.min.y)/this.gizmoDim)*2+1;return{x:n,y:o}}calculateViewportPos(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,o=this.gizmoDim;let r=t-o,a=i-o;switch(n){case 0:r=0,a=0;break;case 1:r=0;break;case 4:a=0;break}return{x:r,y:a}}calculateViewportBbox(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,o=this.gizmoDim,r=new V.Box2(new V.Vector2(t-o,0),new V.Vector2(t,o));switch(n){case 0:r.set(new V.Vector2(0,i-o),new V.Vector2(o,i));break;case 1:r.set(new V.Vector2(0,0),new V.Vector2(o,o));break;case 4:r.set(new V.Vector2(t-o,i-o),new V.Vector2(t,i));break}return r}}function eL(s,e){const t=e.font||"Helvetica",i=e.fontSize||30,n=e.width||200,o=e.height||200,r=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=o;const c=l.getContext("2d");if(c){c.font=`bold ${i}px ${t}`,c.fillStyle=`rgba(${r})`,c.fillRect(0,0,n,o);const f=c.measureText(s).width;c.fillStyle=`rgba(${a})`,c.fillText(s,n/2-f/2,o/2+i/2-2)}const d=new V.Texture(l);return d.minFilter=V.LinearFilter,d.needsUpdate=!0,d}function fu(s){const e=eL(s,{fontSize:100,font:"Arial Narrow, sans-serif",color:[255,255,255,1],bgColor:[0,0,0,0]}),t=new V.SpriteMaterial({map:e,transparent:!0});return new V.Sprite(t)}Pa.RIGHT_TOP;const tL={pos:Pa.LEFT_BOTTOM,size:100,hasZAxis:!0};class iL extends QE{constructor(e,t,i){const n={...tL,...i};super(e,t,n.size,i.pos),this.hasZAxis=n.hasZAxis;const o=[0,0,0,2,0,0,0,0,0,0,2,0],r=[1,0,0,1,.6,0,0,1,0,.6,1,0];this.hasZAxis&&(o.push(0,0,0,0,0,2),r.push(0,0,1,0,.6,1));const a=new V.BufferGeometry;a.setAttribute("position",new V.Float32BufferAttribute(o,3)),a.setAttribute("color",new V.Float32BufferAttribute(r,3));const l=new V.LineBasicMaterial({vertexColors:!0,toneMapped:!1});this.axes=new V.LineSegments(a,l),this.axes.position.set(-1,-1,-1),this.add(this.axes),this.xText=fu("X"),this.xText.position.set(1.5,-1,-1),this.add(this.xText),this.yText=fu("Y"),this.yText.position.set(-1,1.5,-1),this.add(this.yText),this.hasZAxis&&(this.zText=fu("Z"),this.zText.position.set(-1,-1,1.5),this.add(this.zText))}setLineColors(e,t){const i=new V.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 nL extends D.AcTrBaseView{constructor(e,t,i,n){super(e,i,n),this._layoutBtrId=t,this._mode=qe.SELECTION,this._axesGizmo=this.createAxesGizmo(),this._viewportViews=new Map,this._overlayViewport=new D.AcTrOverlayViewport(e)}get layoutBtrId(){return this._layoutBtrId}get mode(){return this._mode}set mode(e){e==qe.SELECTION?this._cameraControls.mouseButtons={MIDDLE:V.MOUSE.PAN}:e==qe.PAN&&(this._cameraControls.mouseButtons={LEFT:V.MOUSE.PAN}),this._cameraControls.update(),this._mode=e}get viewportCount(){return this._viewportViews.size}get viewportViews(){return this._viewportViews.values()}get overlayViewport(){return this._overlayViewport}get internalCamera(){return this._camera.internalCamera}get viewportsBoundingBox(){if(this._viewportViews.size===0)return;const e=new p.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),this.drawOverlay(e),(n=this._axesGizmo)==null||n.update(),t}createAxesGizmo(){return new iL(this._camera.internalCamera,this._renderer.internalRenderer,{hasZAxis:!1,pos:Pa.LEFT_BOTTOM})}drawViewports(e){if(this._viewportViews.size>0){const t=this._renderer.autoClear;this._renderer.autoClear=!1;const i=new V.Vector4;this._renderer.getViewport(i),this._renderer.clearDepth();const n=e.visible;e.visible=!0,this._viewportViews.forEach(o=>{o.render(e)}),e.visible=n,this._renderer.setViewport(i.x,i.y,i.z,i.w),this._renderer.autoClear=t}}drawOverlay(e){const t=this._overlayViewport;if(!t.visible)return;t.render(e.internalScene,this._height);const i=e.modelSpaceLayout;!i||this._viewportViews.size===0||this.drawOverlayViewports(i.internalObject,t)}drawOverlayViewports(e,t){const i=t.screenRect,n=t.viewBox,o=e.visible;e.visible=!0,this._viewportViews.forEach(r=>{const a=D.acTrWcsBoxToCssRect(r.viewport.box,n,i),l=D.acTrIntersectCssRects(a,i);if(!l)return;const c=D.acTrCssRectToWcsBox(l,n,i),d=new p.AcGeBox2d;d.expandByPoint(r.paperPointToModel({x:c.minX,y:c.minY})),d.expandByPoint(r.paperPointToModel({x:c.maxX,y:c.minY})),d.expandByPoint(r.paperPointToModel({x:c.maxX,y:c.maxY})),d.expandByPoint(r.paperPointToModel({x:c.minX,y:c.maxY})),!d.isEmpty()&&r.withFrozenLayersHidden(e,()=>{t.renderNested(e,d,l,l,this._height,r.viewport.viewTwistAngle)})}),e.visible=o}}class yu{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 sL(s,e){return[...s].sort((t,i)=>oL(t,i,e))}function oL(s,e,t){const i=mx(s)-mx(e);if(Math.abs(i)>Number.EPSILON)return i;const n=fx(t,s)-fx(t,e);return Math.abs(n)>Number.EPSILON?n:0}function mx(s){return Math.max(s.maxX-s.minX,0)*Math.max(s.maxY-s.minY,0)}function fx(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 ai=class ai{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)}frameProgrammatically(e){this.userAdjusted||this.applyZoom(e)}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>=ai.SMALL_ENTITY_THRESHOLD||this.convertedCount>=ai.SMALL_ENTITY_THRESHOLD)&&(this.incrementalEnabled=!0)}maybeIncrementalFit(e){if(!this.active||!this.incrementalEnabled||this.userAdjusted)return;const t=performance.now();if(t-this.lastZoomAt<ai.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*ai.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 p.AcGeVector2d;return e.getSize(t),Math.abs(t.x)*Math.abs(t.y)}snapshotFitBox(e){return new p.AcGeBox2d({x:e.min.x,y:e.min.y},{x:e.max.x,y:e.max.y})}};ai.SMALL_ENTITY_THRESHOLD=500,ai.BBOX_GROWTH_RATIO=1.5,ai.FIT_INTERVAL_MS=2500;let gu=ai;const rL=1e3;function aL(s,e,t){return s||e>0?!1:t==null?!0:t>=rL}const bu={background:p.ACGI_MODEL_SPACE_BACKGROUND},de=class de extends Cf{constructor(e=bu){const t={...bu,...e},i=t.container??document.createElement("div");t.container=i,i.style.overflow="hidden",i.hasAttribute("tabindex")||(i.tabIndex=-1);const n=new V.WebGLRenderer({antialias:!0,alpha:!0});i.appendChild(n.domElement),n.domElement.style.display="block",n.domElement.style.maxWidth="100%",n.domElement.style.maxHeight="100%";const o=wm(n.domElement,i);super(n.domElement,i),this._rafId=null,this._loadingLayouts=new Set,this._initializedLayouts=new Set,this._externallyFramedLayouts=new Set,this._openViewMode=_t.Extents,this._convertingLayers=new Set,this._claimedConvertObjectIds=new Set,this._entityConvertGeneration=new Map,this._progressiveRendering=!1,this._convertInvisibleLayers=!1,this._cooperativeYield=!0,this._convertQueue=[],this._viewportRepairOwnerIds=new Set,this._convertDrainPromise=null,this._convertEpoch=0,this._transientDrawGeneration=new Map,this._transientSkipMeshGlyphDepth=0,this._lastProgressivePaintAt=0,this._progressivePaintUrgent=!1,this._progressiveInputPauseUntil=0,this._progressivePaintCount=0,this._progressiveYieldCount=0,this._openLineworkFramePending=!1,this._openLineworkFrameTimer=null,this._pendingGeometryJobs=0,this._deferredGeometryQueue=[],this._deferredGeometryActive=0,this._fontLoadedRedrawTimer=null,this._fontLoadedRedrawEpoch=0,this._entityProcessingIdleAt=0,this._textStyleFontPreloadEpoch=-1,this._textStyleFontPreloadPromise=null,this._viewDomAbort=new AbortController,this._viewDisposed=!1,this._readingMode=new Wu({getCurrentBackgroundColor:()=>this._renderer.currentBackgroundColor,applyViewClearColor:A=>this.applyViewClearColor(A),setCompareDisplay:A=>this.setCompareDisplay(A),markDirty:()=>{this._isDirty=!0}}),this._deferredFontsReady=null,this._convertPhaseMs={finishGeometry:0,finishGeometryAsyncDraw:0,finishGeometryQueueWait:0,handleGroup:0,addEntity:0,awaitFonts:0,glyphEntityCount:0,mtextCount:0,shapeCount:0,sharedGlyphDrawCount:0},this._fontPreloadDiag=null,this.animate=()=>{var G;this._rafId=requestAnimationFrame(this.animate),this.events.renderFrame.dispatch({render:this._renderer,camera:this.internalCamera});const A=this._numOfEntitiesToProcess>0,O=A||this._pendingGeometryJobs>0,P=!this._progressiveRendering&&!this._cooperativeYield&&O;if(!this._isDirty&&!this._htmlDirty&&!O||P||!this._isDirty&&!this._htmlDirty)return;const E=this.shouldCountMidOpenPaint(A,O);if(this._isDirty&&!this._progressivePaintUrgent&&E){const Y=this._progressiveRendering?de.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS:de.NON_PROGRESSIVE_OPEN_PAINT_INTERVAL_MS;if(performance.now()-this._lastProgressivePaintAt<Y)return}let j=!1;this._isDirty&&(E&&(this._progressivePaintCount++,this._lastProgressivePaintAt=performance.now(),this._progressivePaintUrgent=!1),j=this._layoutViewManager.render(this._scene)),this.internalCamera&&(this._isDirty||this._htmlDirty)&&this._css2dRenderer.render(this._scene.internalScene,this.internalCamera),(G=this._stats)==null||G.update(),this._isDirty=j,this._htmlDirty=!1},this._meshGlyphFlushTimer=null,this._disposeCanvasTouchCallout=o;const r=()=>this.noteProgressiveUserInput(),a=()=>{r(),this.focusViewerForShortcuts()},l=()=>{r(),this.focusViewerForShortcuts()};n.domElement.addEventListener("pointerdown",a,{capture:!0}),n.domElement.addEventListener("wheel",l,{capture:!0,passive:!0}),this._disposeProgressiveInputWatch=()=>{n.domElement.removeEventListener("pointerdown",a,{capture:!0}),n.domElement.removeEventListener("wheel",l,{capture:!0})},this._gripManager=new nm(this),this._keyHandler=new No(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),D.setAcTrDrawOrderZAllocator(()=>this._renderer.allocateDrawOrderZ());const c=le.instance.fontMapping;this._renderer.setFontMapping(c),this._onFontNotFound=A=>{Q.emit("font-not-found",{fontName:A.fontName,count:A.count??0})},this._onFontLoaded=A=>{Q.emit("missed-data-changed",{}),this.scheduleGlyphRedrawAfterFontLoad(A==null?void 0:A.fontName)},this._renderer.events.fontNotFound.addEventListener(this._onFontNotFound),this._renderer.events.fontLoaded.addEventListener(this._onFontLoaded),this._scene=this.createScene(),this._layerAppearance=new Gl(this._scene,this._renderer),this._inheritedLayerMaterialMapper=new yp(A=>this._layerAppearance.getEffectiveLayerTraits(A),this._renderer),this.backgroundColor=t.background??p.ACGI_MODEL_SPACE_BACKGROUND,this._stats=this.createStats(le.instance.isShowStats&&(k.tryGetInstance()==null||this.isActiveManagedView()));const d=p.AcDbSysVarManager.instance(),h=p.AcDbSystemVariables.MODELBKCOLOR.toLowerCase(),f=p.AcDbSystemVariables.PAPERBKCOLOR.toLowerCase();this._onSysVarChanged=A=>{const O=A.name.toLowerCase();if(O===h||O===f){const P=A.database;if(!P)return;const E=this.isModelSpaceLayout(P);if(!(O===h&&E||O===f&&!E))return;this.applyCanvasBackground(Mo(P,E))}},d.events.sysVarChanged.addEventListener(this._onSysVarChanged),this._onSettingsModified=A=>{A.key=="isShowStats"&&this.toggleStatsVisibility(this._stats,A.value)},le.instance.events.modified.addEventListener(this._onSettingsModified);let y=null,g=null,b=null;const w=()=>!this.editor.isActive&&!qt.getActiveInputBox()&&!If()&&!this._gripManager.isDragging,S=()=>this.mode===qe.SELECTION&&w(),x=()=>w()&&Ve().canIdleTouchBox(this.mode),_=()=>{b==null||b.remove(),b=null},C=()=>{y=null,g=null,_()},T=(A,O)=>{g=this.viewportToCanvas({x:A,y:O}),y=this.screenToWorld(g),_(),b=document.createElement("div"),b.className="ml-jig-preview-rect",this.container.appendChild(b)},L=(A,O,P="replace")=>{if(!y||!b||!g)return;const E=this.viewportToCanvas({x:A,y:O}),I=this.screenToWorld(E),j=this.worldToScreen(y),G=this.worldToScreen(I),Y=Math.min(j.x,G.x),ee=Math.min(j.y,G.y),Z=Math.abs(j.x-G.x),re=Math.abs(j.y-G.y),Se=this.getSelectionMode(g,E),Ke=this.getSelectionPreviewStyle(Se,P);Object.assign(b.style,{left:`${Y}px`,top:`${ee}px`,width:`${Z}px`,height:`${re}px`,borderStyle:Ke.borderStyle,background:Ke.background}),b.style.setProperty("--line-color",Ke.lineColor)},N=(A,O,P,E)=>{if(!y||!g)return;const I=this.viewportToCanvas({x:A,y:O}),j=this.screenToWorld(I);if(_(),E)if(Yh(this,I.x,I.y,P))P==="replace"&&this.selectionSet.clear();else if(this.entitySelectionEnabled){const G=this.pick(j);G.length>0?(P==="replace"&&this.htmlTransientManager.deselectAll(),this.applySelection([G[0].id],P)):P==="replace"&&this.selectionSet.clear()}else P==="replace"&&this.selectionSet.clear();else{const G=new p.AcGeBox2d().expandByPoint(y).expandByPoint(j),Y=this.getSelectionMode(g,I);this.entitySelectionEnabled&&this.selectByBoxWithMode(G,Y,P),Zh(this,G,Y,P)}y=null,g=null},B=this._viewDomAbort.signal;this.canvas.addEventListener("mousedown",A=>{A.button===0&&S()&&(yt(A)||He()||T(A.clientX,A.clientY))},{signal:B}),this.canvas.addEventListener("mousemove",A=>{!y||!b||!g||yt(A)||He()||L(A.clientX,A.clientY,this.getPointerSelectionAction(A))},{signal:B}),this.canvas.addEventListener("mouseup",A=>{if(this._gripManager.isDragging){C();return}if(!y||!g||yt(A)||He())return;const O=this.viewportToCanvas({x:A.clientX,y:A.clientY}),P=this.getPointerSelectionAction(A);N(A.clientX,A.clientY,P,this.isSelectionClick(g,O))},{signal:B}),this._disposeMobileBoxGesture=cr({element:this.canvas,shouldStart:()=>x(),setNavigationEnabled:A=>{this.setNavigationEnabled(A)},onActivate:(A,O)=>{T(A,O),L(A,O)},onMove:(A,O)=>{L(A,O)},onBoxEnd:(A,O,P)=>{N(A,O,"replace",!P)},onTap:(A,O)=>{g=this.viewportToCanvas({x:A,y:O}),y=this.screenToWorld(g),N(A,O,"replace",!0)},onAbort:()=>{C()}}),this.canvas.addEventListener("dblclick",A=>{A.button===0&&S()&&this.entitySelectionEnabled&&k.instance.curDocument.openMode===U.Write&&this.openPickedEntityEditor(A)},{signal:B}),document.addEventListener("keydown",A=>{this.isActiveManagedView()&&this.isShortcutEventInsideViewer(A)&&this._keyHandler.handleKeyDown(A)},{signal:B}),this._onLayoutSwitched=A=>{var j,G;if(!this.isActiveManagedView())return;const O=A.layout.database,P=(G=(j=k._instance)==null?void 0:j.curDocument)==null?void 0:G.database;if(O&&P&&O!==P)return;const E=A.layout.blockTableRecordId,I=!this._initializedLayouts.has(E);this._initializedLayouts.add(E),this.activeLayoutBtrId=E,this.createLayoutViewIfNeeded(E),this.loadLayoutEntitiesIfNeeded(E),this.refreshCanvasBackgroundForActiveLayout(),this._isDirty=!0,I&&this.applyInitialZoom(E,A.layout)},p.acdbHostApplicationServices().layoutManager.events.layoutSwitched.addEventListener(this._onLayoutSwitched),this._css2dRenderer=new jx.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=String(Tp),this._css2dRenderer.domElement.style.maxWidth="100%",this._css2dRenderer.domElement.style.maxHeight="100%",i.appendChild(this._css2dRenderer.domElement),this._missedImages=new Map,this._layoutViewManager=new yu,this._progressiveOpenFit=new gu((A,O)=>{this.activeLayoutView.zoomTo(A,O??1.1),this._isDirty=!0}),this._entityDisplay=new JE(A=>this.resolveLayerInfo(A)),this.initialize(),this.onWindowResize(),this._isDirty=!0,this._htmlDirty=!1,this.startAnimationLoop(),this._numOfEntitiesToProcess=0,this.resetDeferredGeometryQueue()}ensureDeferredFontsReady(){if(!this._deferredFontsReady){const e=performance.now(),t=Promise.all([this.awaitPresetFontsReadySafe(),this.awaitTextStyleFontsReady()]).then(()=>{},()=>{});this._deferredFontsReady=t.then(()=>{this._convertPhaseMs.awaitFonts+=performance.now()-e})}return this._deferredFontsReady}async awaitPresetFontsReadySafe(){const e=k;e._instance&&await e._instance.awaitPresetFontsReady()}takeConvertPhaseTimings(){const e={...this._convertPhaseMs,fontPreload:this._fontPreloadDiag?{...this._fontPreloadDiag}:void 0};return this._convertPhaseMs={finishGeometry:0,finishGeometryAsyncDraw:0,finishGeometryQueueWait:0,handleGroup:0,addEntity:0,awaitFonts:0,glyphEntityCount:0,mtextCount:0,shapeCount:0,sharedGlyphDrawCount:0},this._fontPreloadDiag=null,e}getPointerSelectionAction(e){return Sf(e)}initialize(){this.setCursor(Ti.Crosshair),this._onCommandWillStartHitTest=()=>{this.htmlTransientManager.setHitTestEnabled(!1)},this._onCommandEndedHitTest=()=>{this.htmlTransientManager.setHitTestEnabled(!0)},this.editor.events.commandWillStart.addEventListener(this._onCommandWillStartHitTest),this.editor.events.commandEnded.addEventListener(this._onCommandEndedHitTest)}get mode(){const e=this.activeLayoutView;return e?e.mode:qe.SELECTION}set mode(e){this.activeLayoutView.mode=e}setNavigationEnabled(e){const t=this.activeLayoutView;t&&(t.enabled=e)}setSnapLoupe(e){var i;const t=(i=this.activeLayoutView)==null?void 0:i.overlayViewport;if(t){if(!e){t.visible=!1,this._isDirty=!0;return}t.setScreenRect(e.x,e.y,e.size,e.size),t.setViewBox(e.viewBox),t.visible=!0,this._isDirty=!0}}get renderer(){return this._renderer}get gripManager(){return this._gripManager}get isDirty(){return this._isDirty}get isProcessingEntities(){return this._numOfEntitiesToProcess>0||this._pendingGeometryJobs>0}get isConvertingEntities(){return this._numOfEntitiesToProcess>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 convertInvisibleLayers(){return this._convertInvisibleLayers}set convertInvisibleLayers(e){this._convertInvisibleLayers=e}get cooperativeYield(){return this._cooperativeYield}set cooperativeYield(e){this._cooperativeYield=e}get progressiveOpenStats(){return{paintCount:this._progressivePaintCount,yieldCount:this._progressiveYieldCount}}resetProgressiveOpenStats(){this._progressivePaintCount=0,this._progressiveYieldCount=0,this._lastProgressivePaintAt=0,this._progressivePaintUrgent=!1,this._progressiveInputPauseUntil=0}isProgressiveGesturePauseActive(){return performance.now()<this._progressiveInputPauseUntil}isProgressiveDiscreteInputPending(){var t;const e=navigator.scheduling;return((t=e==null?void 0:e.isInputPending)==null?void 0:t.call(e))===!0}noteProgressiveUserInput(){!this._progressiveRendering||this._numOfEntitiesToProcess<=0||(this._progressivePaintUrgent=!0,this._isDirty=!0,this._progressiveInputPauseUntil=performance.now()+de.PROGRESSIVE_INPUT_PAUSE_MS)}async progressiveYieldForInput(e,t){if(this.isProgressiveGesturePauseActive()){for(await t();performance.now()<this._progressiveInputPauseUntil;)await new Promise(n=>setTimeout(n,16));this._progressiveYieldCount++;return}if(this.isProgressiveDiscreteInputPending()){await t(),this._progressiveYieldCount++;return}if(!e)return;await e.maybeYield(t)&&this._progressiveYieldCount++}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(o=>({name:o.name,pathName:o.pathName,isOverlay:o.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){if(this._renderer.currentBackgroundColor=e,this._layerAppearance.refreshTextMaterialsInObjectTree(this._scene.internalScene),this._scene.repaintForegroundMaterials(p.acgiForegroundColorForBackground(e)),this._scene.repaintBackgroundMaterials(e),this.resyncForegroundLayersForBackground(),this._readingMode.isEnabled){this._readingMode.noteLayoutBackground(e),this.applyViewClearColor($a);return}this.applyViewClearColor(e)}applyViewClearColor(e){this._renderer.setClearColor(e),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?cp(e):this.activeLayoutBtrId===this.modelSpaceBtrId}bindDrawDatabase(e){this._renderer.context.database=e}syncDisplaySysVars(e){this.bindDrawDatabase(e),this.applyCanvasBackground(Mo(e,this.isModelSpaceLayout(e))),this._readingMode.reapplyIfEnabled()}get readingModeEnabled(){return this._readingMode.isEnabled}toggleReadingMode(){this._readingMode.toggle()}setReadingMode(e){this._readingMode.setEnabled(e)}async addOverlayEntities(e){const t=new Ap;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 o of n.newIterator())if(!(o instanceof p.AcDbViewport))try{const r=this.drawEntity(o,!1);if(!r)continue;r.objectId=o.objectId,r.ownerId=o.ownerId,r.layerName=o.layer,r.visible=o.visibility!==!1,r instanceof D.AcTrGroup&&r.isOnTheSameLayer&&(r.userData.insertLayerName=r.layerName),await this.finishEntityGeometry(r,!1),r instanceof D.AcTrGroup&&r.isOnTheSameLayer&&this._inheritedLayerMaterialMapper.remap(r.children,"0",r.layerName),t.addEntity(r),r.dispose()}catch(r){p.log.error(`[AcTrView2d] Failed to convert overlay entity ${o.objectId} (${o.type}):`,r)}}finally{this._renderer.context.database=i}return t}refreshCanvasBackgroundForActiveLayout(){var n,o;const t=(o=(n=k._instance)==null?void 0:n.curDocument)==null?void 0:o.database;if(!t)return;const i=this.activeLayoutBtrId===this.modelSpaceBtrId;this.applyCanvasBackground(Mo(t,i))}get modelSpaceBtrId(){return this._scene.modelSpaceBtrId}set modelSpaceBtrId(e){this._scene.modelSpaceBtrId=e}get activeLayoutBtrId(){return this._scene.activeLayoutBtrId}set activeLayoutBtrId(e){const t=this._scene.activeLayoutBtrId;this._layoutViewManager.activeLayoutBtrId=e,this._scene.activeLayoutBtrId=e,this.htmlTransientManager.setActiveLayoutId(e),this._isDirty=!0,t!==e&&zh()}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,o=[];await this.drainConvertQueue();const r=(l=n.objects)==null?void 0:l.layout;if(i&&(r!=null&&r.newIterator))for(const c of r.newIterator()){const d=c.blockTableRecordId;d&&this._scene.addEmptyLayout(d)}for(const[c]of this._scene.layouts){if(!i&&c!==this._scene.modelSpaceBtrId)continue;const d=n.tables.blockTable.getIdAt(c);d&&o.push(...this._entityDisplay.collectMissingEntitiesForExport(d,h=>this.isEntityConvertScheduled(h),t))}o.length>0&&(this._numOfEntitiesToProcess+=o.length,await this.batchConvert(o,{forExport:!0})),await this.waitUntilIdle(12e4)||p.log.warn("[AcTrView2d] Timed out waiting for deferred geometry before export"),this.flushMeshGlyphWorldBatch()}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 p.AcGePoint2d(e)}worldToScreen(e){const t=this.activeLayoutView;return t?t.worldToScreen(e):new p.AcGePoint2d(e)}zoomTo(e,t=1.1){this.activeLayoutView.zoomTo(e,t),this._isDirty=!0}rerenderPoints(e,t=0){const i=this._scene.activeLayout;i&&(i.rerenderPoints(e,t),this._isDirty=!0)}requestOpenLineworkFrame(){this._openLineworkFramePending=!0,this.scheduleOpenLineworkFrame()}cancelOpenLineworkFrame(){this._openLineworkFramePending=!1,this._openLineworkFrameTimer!=null&&(clearTimeout(this._openLineworkFrameTimer),this._openLineworkFrameTimer=null)}scheduleOpenLineworkFrame(){if(this._openLineworkFrameTimer!=null||!this._openLineworkFramePending)return;const e=this.isConvertingEntities?50:0;this._openLineworkFrameTimer=setTimeout(()=>{if(this._openLineworkFrameTimer=null,!!this._openLineworkFramePending){if(this.isConvertingEntities){this.scheduleOpenLineworkFrame();return}this.frameOpenLineworkIfReady()}},e)}zoomToFitDrawing(e=0,t){new jo(()=>!this.isProcessingEntities,()=>{if(t&&this._externallyFramedLayouts.delete(t)){this.endProgressiveOpenFit();return}this._progressiveOpenFit.applyFinalFit(()=>this.getDrawingExtents()),this.endProgressiveOpenFit();const n=t??this.activeLayoutBtrId;n&&yi.rememberOriginalView(this,n)},300,e).start()}zoomToFitLayer(e){const t=this._scene.activeLayout;if(t){const i=t.getLayer(e);if(i&&!i.box.isEmpty()){const n=mu.threeBox3dToGeBox2d(i.box);return this.zoomTo(n),this._isDirty=!0,!0}}return!1}zoomToSmartExtents(e=0){return new Promise((t,i)=>{new jo(()=>!this.isProcessingEntities,()=>{(async()=>{try{const o=await this.resolveSmartFitBox();if(o){this.zoomTo(o),this._isDirty=!0,this.endProgressiveOpenFit(),t();return}this._progressiveOpenFit.applyFinalFit(()=>this.getDrawingExtents()),this.endProgressiveOpenFit(),t()}catch(o){this.endProgressiveOpenFit(),i(o)}})()},300,e).start()})}async resolveSmartFitBox(){const e=this._scene.activeLayout;if(!e)return;const t=e.cachedSmartExtents;if(t)return t;const i=e.smartExtentsGeneration,n=new gp,o=await e.collectSpatialExtentBoxesAsync(n),r=await bp(o,n);return e.smartExtentsGeneration!==i?e.cachedSmartExtents:(r&&(e.cachedSmartExtents=r),r)}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 o=k.instance.curDocument.database.tables.blockTable.getEntityById(n[0].id);if(!o)return;const r=this.resolveAttributedBlockReference(o);if(r){e.preventDefault(),this.selectionSet.clear(),this.selectionSet.add(r.objectId),k.instance.sendStringToExecute("attedit");return}if(o instanceof p.AcDbMText){e.preventDefault(),await this.editMTextEntity(o);return}o instanceof p.AcDbText&&(e.preventDefault(),await this.editTextEntity(o))}resolveAttributedBlockReference(e){if(e instanceof p.AcDbBlockReference)return e.attributeIterator().count>0?e:void 0;if(e instanceof p.AcDbAttribute||e.type==="Attrib"||e.type==="Attribute"){const t=k.instance.curDocument.database.tables.blockTable.getEntityById(e.ownerId);if(t instanceof p.AcDbBlockReference&&t.attributeIterator().count>0)return t}}async editMTextEntity(e){const t=e.database;this.setEntitySceneVisible(e.objectId,!1),this._isDirty=!0;const i=e.resolveAnnotativePresentation,n=typeof i=="function"?i.call(e):null,o=(n==null?void 0:n.position)??e.location,r={x:o.x,y:o.y,z:o.z??0},a=(n==null?void 0:n.direction)??e.direction,l=(n==null?void 0:n.attachmentPoint)??e.attachmentPoint,c=n&&Number.isFinite(n.width)&&n.width>0?n.width:this.resolveMTextEditorWidth(e),d=n&&Number.isFinite(n.height)&&n.height>0?n.height:this.resolveMTextEditorTextHeight(e),h=new qt;let f=!1;try{const y=await h.open({view:this,location:r,width:c,textHeight:d,initialText:e.contents,initialAttachmentPoint:l,initialDrawingDirection:e.drawingDirection,rotation:e.rotation,directionVector:{x:a.x,y:a.y,z:a.z},textStyleName:e.styleName,initialLineSpaceFactor:e.lineSpacingFactor,toolbarFontFamilies:await this.getMTextToolbarFontFamilies()});if(!y)return;ui(t,"Edit MText",()=>{const g=t.openEntityForWrite(e);g instanceof p.AcDbMText&&(g.location=y.location,g.contents=y.contents,g.width=y.width,g.height=y.height,g.lineSpacingFactor=y.lineSpacingFactor,g.attachmentPoint=y.attachmentPoint)}),f=!0}finally{this.setEntitySceneVisible(e.objectId,!0),f||this.updateEntity(e),this._isDirty=!0}}async editTextEntity(e){const t=e.database;this.setEntitySceneVisible(e.objectId,!1),this._isDirty=!0;const i=Number(e.height),n=Number.isFinite(i)&&i>0?i:this.pixelsToWorldY(24),o=e.textString??"",r=Math.max(n*Math.max(o.length,1)*.6,n),a=Number(e.rotation),l=new qt;let c=!1;try{const d=await l.open({view:this,location:e.position,width:r,textHeight:n,initialText:o,initialAttachmentPoint:p.AcGiMTextAttachmentPoint.BaselineLeft,...Number.isFinite(a)?{rotation:a}:{},toolbarFontFamilies:await this.getMTextToolbarFontFamilies()});if(!d)return;ui(t,"Edit Text",()=>{const h=t.openEntityForWrite(e);h instanceof p.AcDbText&&(h.position=new p.AcGePoint3d(d.location),h.textString=d.contents,Number.isFinite(d.height)&&d.height>0&&(h.height=d.height))}),c=!0}finally{this.setEntitySceneVisible(e.objectId,!0),c||this.updateEntity(e),this._isDirty=!0}}resolveMTextEditorWidth(e){const t=Number(e.width);return Number.isFinite(t)&&t>0?t:0}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)}async getMTextToolbarFontFamilies(){const e=await k.instance.getAvaiableFonts()??[];return Array.from(new Set(e.flatMap(t=>t.name).map(t=>t.trim()).filter(t=>t.length>0)))}pick(e,t,i){e==null&&(e=this.curPos);const n=[],o=this._scene.activeLayout;if(!o)return n;const r=this.activeLayoutView,a=t??this.selectionBoxSize,l=r.pointToBox(e,a),c=Math.max(l.size.width/2,l.size.height/2),d=r.layoutBtrId!==this._scene.modelSpaceBtrId,h=(l.size.width+l.size.height)/2,f=[],y=new Set;if(d)for(const C of r.viewportViews)C.containsPaperPoint(e)&&!C.isNearPaperBorder(e,h)&&(f.push(C),y.add(C.viewport.id));const g=this._scene.search(l),b=r.resetRaycaster(e,c),w=D.AcTrMTextRenderer.getInstance(),S=new Set;g.forEach(C=>{if(y.has(C.id))return;const T=w.intersectMeshGlyphObjectId(C.id,b);!ts(C)&&!T||(o.isIntersectWith(C.id,b)||T)&&(n.push(C),S.add(C.id))});const x=w.queryMeshGlyphObjectIdsIntersectingBox({minX:l.min.x,minY:l.min.y,maxX:l.max.x,maxY:l.max.y});for(const C of x){if(S.has(C)||y.has(C)||!w.intersectMeshGlyphObjectId(C,b))continue;const T=w.getMeshGlyphWorldPickBoxes().get(C);n.push({id:C,minX:(T==null?void 0:T.min.x)??l.min.x,minY:(T==null?void 0:T.min.y)??l.min.y,maxX:(T==null?void 0:T.max.x)??l.max.x,maxY:(T==null?void 0:T.max.y)??l.max.y}),S.add(C)}f.length>0&&this.pickThroughViewports(e,l,f,n);const _=sL(n,e);return i?_.slice(0,1):_}getViewportCoordinateMapper(e){var i;let t;for(const n of((i=this.activeLayoutView)==null?void 0:i.viewportViews)??[])if(n.viewport.id===e){t=n;break}if(t)return{paperToModel:n=>t.paperPointToModel(n),modelToPaper:n=>t.modelPointToPaper(n),containsPaperPoint:n=>t.containsPaperPoint(n)}}pickThroughViewports(e,t,i,n){const o=this._scene.modelSpaceLayout;if(!o)return;const r=(t.size.width+t.size.height)/4;for(const a of i){const l=a.paperPointToModel(e),c=r*a.paperToModelScale;if(c<=0)continue;const d=new p.AcGeBox2d().setFromPoints([new p.AcGePoint2d(l.x-c,l.y-c),new p.AcGePoint2d(l.x+c,l.y+c)]),h=a.resetRaycaster(l,c);o.search(d).forEach(y=>{ts(y)&&o.isIntersectWith(y.id,h)&&n.push({...y,viewportId:a.viewport.id})})}}search(e,t){return this._scene.search(e,t)}select(e){const t=[];this.pick(e).forEach(o=>t.push(o.id));const n=this.selectableIds(t,"add");n.length>0&&this.selectionSet.add(n)}selectByBox(e){this.selectByBoxWithMode(e,"crossing","add")}refineCrossingSelectionHits(e,t){var o;const i=(o=k.instance.curDocument)==null?void 0:o.database;if(!i)return t.map(r=>r.id);const n=[];for(const r of t){if(!Ef(r)){n.push(r.id);continue}const a=new p.AcGeBox2d({x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY});if(e.containsBox(a)){n.push(r.id);continue}const l=i.tables.blockTable.getEntityById(r.id);(!l||Pf(l,e))&&n.push(r.id)}return n}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);(on.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;const o=this._renderer.context;this._transientSkipMeshGlyphDepth++,o.skipMeshGlyphInstancing=!0;const r=()=>{this._transientSkipMeshGlyphDepth=Math.max(0,this._transientSkipMeshGlyphDepth-1),this._transientSkipMeshGlyphDepth===0&&(o.skipMeshGlyphInstancing=!1)};try{for(let a=0;a<t.length;++a){const l=t[a],c=String(l.objectId??""),d=c?(this._transientDrawGeneration.get(c)??0)+1:0;c&&(this._transientDrawGeneration.set(c,d),D.AcTrMTextRenderer.getInstance().removeMeshGlyphInstances(c));const h=this.drawEntity(l,!0);if(h){h.objectId=l.objectId,h.userData.skipMeshGlyphInstancing=!0;try{h.syncDraw()}catch(f){p.log.error("[AcTrView2d] Transient entity geometry failed:",f),h.dispose();continue}if(i!==this._convertEpoch){h.dispose();continue}if(c&&this._transientDrawGeneration.get(c)!==d){h.dispose();continue}this._scene.addTransientEntity(h),this._isDirty=!0}}}finally{this._renderer.forceShowLineWeight=n,r()}}removeTransientEntity(e){const t=String(e??"");t&&this._transientDrawGeneration.set(t,(this._transientDrawGeneration.get(t)??0)+1),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){var i;const t=Array.isArray(e)?e:[e];for(let n=0;n<t.length;n++){const o=(i=t[n])==null?void 0:i.ownerId;if(!o)continue;let r=this._scene.layouts.get(o);r||(this._scene.addEmptyLayout(o),r=this._scene.layouts.get(o)),r&&!r.isLoaded&&(r.isLoaded=!0)}this._numOfEntitiesToProcess+=t.length,this._convertQueue.push(...t),this.drainConvertQueue()}removeEntity(e){(Array.isArray(e)?e:[e]).forEach(i=>{this.releaseConvertClaim(i.objectId),this._scene.removeEntity(i.objectId)}),this._isDirty=!0}releaseConvertClaim(e){const t=String(e??"");t&&(this._claimedConvertObjectIds.delete(t),this._entityConvertGeneration.set(t,(this._entityConvertGeneration.get(t)??0)+1))}hasEntity(e){return this._scene.hasEntity(e)}isEntityConvertScheduled(e){const t=String(e??"");return t?this.hasEntity(e)||this._claimedConvertObjectIds.has(t):!1}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 o=t[n],r=String(o.objectId??"");r&&(this._entityConvertGeneration.set(r,(this._entityConvertGeneration.get(r)??0)+1),this._claimedConvertObjectIds.delete(r),D.AcTrMTextRenderer.getInstance().removeMeshGlyphInstances(r)),this._scene.hasEntity(o.objectId)&&this._scene.removeEntity(o.objectId)}(async()=>(await this.batchConvert(t),await this.waitUntilDeferredGeometryIdle(),i.length>0&&this.highlight(i),this._gripManager.refresh(),this._isDirty=!0))(),this._isDirty=!0,setTimeout(()=>{this._isDirty=!0},100)}resolveSceneUpdateEntities(e){var o;const t=(o=k.instance.curDocument)==null?void 0:o.database,i=[],n=new Set;for(const r of e){let a=r;if(r instanceof p.AcDbAttribute){const l=t==null?void 0:t.tables.blockTable.getEntityById(r.ownerId);if(!(l instanceof p.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)}setOpenViewMode(e){this._openViewMode=e}isLayoutInitialized(e){return this._initializedLayouts.has(e)}getDrawingExtents(){const e=this._scene.box;if(e&&!e.isEmpty())return mu.threeBox3dToGeBox2d(e)}applyInitialZoom(e,t){new jo(()=>!this.isProcessingEntities,()=>{if(this._externallyFramedLayouts.delete(e))return;const n=this.resolveFirstVisitFrameBox(e,t);n&&this.zoomTo(n),this._isDirty=!0,yi.rememberOriginalView(this,e)},300,0).start()}resolveFirstVisitFrameBox(e,t){var d,h;const i=e===this.modelSpaceBtrId,n=this._openViewMode===_t.Saved;if(n&&i){const f=k.instance.curDocument.database,y=this.width/Math.max(this.height,1),g=f.tables.viewportTable.getActiveVportBox(y);if(g)return g}const o=this._layoutViewManager.getAt(e),r=t.extents,a=r&&!r.isEmpty()?{min:{x:r.min.x,y:r.min.y},max:{x:r.max.x,y:r.max.y}}:void 0,l=this.getDrawingExtents(),c=o==null?void 0:o.viewportsBoundingBox;return n&&!i?(d=kr({limits:t.limits,viewportsBox:c,layoutExtents:a,entityBox:l}))==null?void 0:d.box:(h=kr({limits:void 0,viewportsBox:i?void 0:c,layoutExtents:a,entityBox:l}))==null?void 0:h.box}abortConversion(){this._convertEpoch++,this.clearFontLoadedRedrawTimer(),this.clearMeshGlyphFlushTimer(),this._convertQueue.length=0,this._viewportRepairOwnerIds.clear(),this._numOfEntitiesToProcess=0,this._claimedConvertObjectIds.clear(),this._entityConvertGeneration.clear(),this.cancelOpenLineworkFrame(),this.resetDeferredGeometryQueue(),this._entityProcessingIdleAt=0}clear(){this.abortConversion(),this._scene.clear(),D.AcTrMTextRenderer.getInstance().resetMeshGlyphBatch(),this._renderer.resetDrawOrderZ(),this._isDirty=!0,this._missedImages.clear(),this._initializedLayouts.clear(),this._externallyFramedLayouts.clear(),this._openViewMode=_t.Extents,this._loadingLayouts.clear(),this._renderer.dispose(),p.AcDbRenderingCache.instance.clear(),Q.emit("missed-data-changed",{})}captureSessionState(){return this.clearMeshGlyphFlushTimer(),{scene:this._scene,layoutViewManager:this._layoutViewManager,initializedLayouts:this._initializedLayouts,externallyFramedLayouts:this._externallyFramedLayouts,openViewMode:this._openViewMode,loadingLayouts:this._loadingLayouts,missedImages:this._missedImages,missedFonts:this._renderer.snapshotMissedFonts(),selectionIds:this.selectionSet.ids,meshGlyphBatch:D.AcTrMTextRenderer.getInstance().detachMeshGlyphBatch()}}restoreSessionState(e){this._convertEpoch++,this.clearFontLoadedRedrawTimer(),this.clearMeshGlyphFlushTimer(),this.cancelOpenLineworkFrame(),this._convertQueue.length=0,this._viewportRepairOwnerIds.clear(),this._numOfEntitiesToProcess=0,this._claimedConvertObjectIds.clear(),this._entityConvertGeneration.clear(),this.resetDeferredGeometryQueue(),this._entityProcessingIdleAt=0,this._scene=e.scene,this._layoutViewManager=e.layoutViewManager,this._initializedLayouts=e.initializedLayouts,this._externallyFramedLayouts=e.externallyFramedLayouts,this._openViewMode=e.openViewMode??_t.Extents,this._loadingLayouts=e.loadingLayouts,this._missedImages=e.missedImages,this._renderer.replaceMissedFonts(e.missedFonts??{}),D.AcTrMTextRenderer.getInstance().attachMeshGlyphBatch(e.meshGlyphBatch),this.rebindLayerAppearance(),this._layoutViewManager.resize(this.width,this.height),this.selectionSet.clear(),e.selectionIds.length>0&&this.selectionSet.add(e.selectionIds),this._isDirty=!0,Q.emit("missed-data-changed",{})}beginNewSession(){const e=this.captureSessionState();return this._convertEpoch++,this.clearFontLoadedRedrawTimer(),this.cancelOpenLineworkFrame(),this._convertQueue.length=0,this._viewportRepairOwnerIds.clear(),this._numOfEntitiesToProcess=0,this._claimedConvertObjectIds.clear(),this._entityConvertGeneration.clear(),this.resetDeferredGeometryQueue(),this._entityProcessingIdleAt=0,this._scene=this.createScene(),this._layoutViewManager=new yu,this._initializedLayouts=new Set,this._externallyFramedLayouts=new Set,this._openViewMode=_t.Extents,this._loadingLayouts=new Set,this._missedImages=new Map,this._renderer.clearMissedFonts(),this.rebindLayerAppearance(),this.selectionSet.clear(),this._isDirty=!0,Q.emit("missed-data-changed",{}),e}disposeSessionState(e){e.meshGlyphBatch.dispose(),e.scene.clear(),e.layoutViewManager=new yu,e.initializedLayouts.clear(),e.externallyFramedLayouts.clear(),e.loadingLayouts.clear(),e.missedImages.clear(),e.missedFonts={},e.selectionIds=[]}rebindLayerAppearance(){this._layerAppearance=new Gl(this._scene,this._renderer)}isActiveManagedView(){var i;const t=(i=k._instance)==null?void 0:i.curView;return t!=null&&t===this}focusViewerForShortcuts(){const e=document.activeElement;e instanceof Node&&this.container.contains(e)||e instanceof HTMLElement&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable)||this.container.focus({preventScroll:!0})}isShortcutEventInsideViewer(e){const t=e.target;if(t instanceof Node&&this.container.contains(t))return!0;const i=document.activeElement;return i instanceof Node&&this.container.contains(i)}async drainConvertQueue(){if(this._convertDrainPromise){await this._convertDrainPromise,this._convertQueue.length>0&&await this.drainConvertQueue();return}this._convertDrainPromise=this.runConvertDrain().finally(()=>{this._convertDrainPromise=null}),await this._convertDrainPromise}async runConvertDrain(){const e=this._convertEpoch,t=this._cooperativeYield;let i=t?this.activeLayoutBtrId===this.modelSpaceBtrId?de.CONVERT_SLICE_MAX:1:Number.POSITIVE_INFINITY,n=performance.now(),o=YE(this._convertQueue.splice(0,this._convertQueue.length),this.activeLayoutBtrId);for(this.repairViewportViewsFor(o.activeOwnerId);o.cursor<o.pending.length||this._convertQueue.length>0;){if(this._convertEpoch!==e)return;const r=this._convertQueue.splice(0,this._convertQueue.length),a=this.activeLayoutBtrId,l=a!==o.activeOwnerId;if(o=ZE(o,r,a),l&&(this.repairViewportViewsFor(a),t&&(i=1)),this.flushViewportViewRepairs(),o.cursor>=o.pending.length)break;const c=Math.min(o.pending.length,o.cursor+i),d=performance.now();if(await this.batchConvert(o.pending.slice(o.cursor,c)),o.cursor=c,this._convertEpoch!==e)return;if(!t)continue;const h=performance.now()-d,f=o.activeOwnerId===this.modelSpaceBtrId,y=this._progressiveRendering?de.PROGRESSIVE_OPEN_YIELD_BUDGET_MS:de.OPEN_CONVERT_YIELD_BUDGET_MS,g=f?y:de.CONVERT_SLICE_BUDGET_MS;if(i=qE({slice:i,tookMs:h,budgetMs:g,maxSlice:de.CONVERT_SLICE_MAX,activeLayoutPending:!f&&XE(o)}),this._progressiveRendering&&this.isProgressiveGesturePauseActive()){for(await new Promise(b=>setTimeout(b,0));performance.now()<this._progressiveInputPauseUntil;)await new Promise(b=>setTimeout(b,16));if(n=performance.now(),this._convertEpoch!==e)return}else if(this._progressiveRendering&&this.isProgressiveDiscreteInputPending()){if(await new Promise(b=>setTimeout(b,0)),n=performance.now(),this._convertEpoch!==e)return}else if(performance.now()-n>=g&&(await new Promise(b=>setTimeout(b,0)),n=performance.now(),this._convertEpoch!==e))return}this.repairViewportViewsFor(this.activeLayoutBtrId),this.flushViewportViewRepairs()}repairViewportViewsFor(e){var i;if(!e||e===this.modelSpaceBtrId)return;const t=this._layoutViewManager.getAt(e);if(!t||t.viewportCount>0){t&&t.viewportCount>0&&this._viewportRepairOwnerIds.delete(e);return}try{const n=(i=k.instance.curDocument)==null?void 0:i.database,o=n==null?void 0:n.tables.blockTable.getIdAt(e);if(!o)return;const r=t.viewportCount;this.ensureViewportViews(o,t),t.viewportCount>r&&(this._isDirty=!0),this._viewportRepairOwnerIds.delete(e)}catch(n){p.log.error("[AcTrView2d] Error repairing viewport views:",n)}}flushViewportViewRepairs(){if(this._viewportRepairOwnerIds.size===0)return;const e=Array.from(this._viewportRepairOwnerIds);for(let t=0;t<e.length;t++)this.repairViewportViewsFor(e[t])}markProgressiveDirty(e=!1){const t=performance.now();(e||t-this._lastProgressivePaintAt>=de.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS)&&(this._isDirty=!0)}markInteractiveOpenDirty(){this._progressiveRendering||!this._cooperativeYield||(this._isDirty=!0)}shouldCountMidOpenPaint(e,t){return this._progressiveRendering&&e||!this._progressiveRendering&&this._cooperativeYield&&t}highlight(e){this.entitySelectionEnabled&&(this._isDirty=this._scene.select(e))}unhighlight(e){this._isDirty=this._scene.unselect(e)}setCompareDisplay(e,t){var o,r,a,l;const i=e.baseColor??((o=e.colors)==null?void 0:o.unchanged)??10265519,n={enabled:e.enabled,baseColor:i,colors:{deleted:(r=e.colors)==null?void 0:r.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)}dispose(){var t,i,n;if(this._viewDisposed)return;this._viewDisposed=!0,this.abortConversion(),(t=this._disposeCanvasTouchCallout)==null||t.call(this),this._disposeCanvasTouchCallout=void 0,(i=this._disposeProgressiveInputWatch)==null||i.call(this),this._disposeProgressiveInputWatch=void 0,(n=this._disposeMobileBoxGesture)==null||n.call(this),this._disposeMobileBoxGesture=void 0,this._viewDomAbort.abort(),this._onFontNotFound&&this._renderer.events.fontNotFound.removeEventListener(this._onFontNotFound),this._onFontLoaded&&this._renderer.events.fontLoaded.removeEventListener(this._onFontLoaded),this._onSysVarChanged&&p.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this._onSysVarChanged),this._onSettingsModified&&le.instance.events.modified.removeEventListener(this._onSettingsModified),this._onLayoutSwitched&&p.acdbHostApplicationServices().layoutManager.events.layoutSwitched.removeEventListener(this._onLayoutSwitched),this._onCommandWillStartHitTest&&this.editor.events.commandWillStart.removeEventListener(this._onCommandWillStartHitTest),this._onCommandEndedHitTest&&this.editor.events.commandEnded.removeEventListener(this._onCommandEndedHitTest),this._gripManager.dispose(),this.clearFontLoadedRedrawTimer(),this.cancelOpenLineworkFrame(),this.stopAnimationLoop(),this.selectionSet.clear(),this.htmlTransientManager.dispose(),this._scene.clear(),this._renderer.dispose(),p.AcDbRenderingCache.instance.clear();const e=this._renderer.internalRenderer;e.dispose(),e.forceContextLoss(),this.canvas.remove(),this._css2dRenderer.domElement.remove(),this._stats.dom.remove(),super.dispose()}onHover(e){this.entitySelectionEnabled&&(this._isDirty=this._scene.hover([e]))}onUnhover(e){this._isDirty=this._scene.unhover([e])}createScene(){return new _p}createStats(e){const t=new Rx;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(){this.refreshViewSize(),this._renderer.setSize(this.width,this.height),this._css2dRenderer.setSize(this.width,this.height),this._layoutViewManager.resize(this.width,this.height),this._isDirty=!0,this.events.viewResize.dispatch({width:this.width,height:this.height}),this.events.viewChanged.dispatch()}startAnimationLoop(){this._rafId==null&&(this._rafId=requestAnimationFrame(this.animate))}createLayoutViewIfNeeded(e){let t=this._layoutViewManager.getAt(e);return t==null&&(t=new nL(this._renderer,e,this.width,this.height),t.events.viewChanged.addEventListener(()=>{this._progressiveOpenFit.onLayoutViewChanged(),this._isDirty=!0,this._progressiveRendering&&this._numOfEntitiesToProcess>0&&(this._progressivePaintUrgent=!0),this.events.viewChanged.dispatch(),this.clearHover()}),this._layoutViewManager.add(t)),this.flushViewportViewRepairs(),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.repairViewportViewsFor(e);return}if(this._loadingLayouts.has(e))return;if(this.repairViewportViewsFor(e),n&&n.entityCount>0){n.isLoaded=!0;return}n||this._scene.addEmptyLayout(e);const o=[],r=i.newIterator();for(const l of r)o.push(l);if(o.length===0){const l=this._scene.layouts.get(e);l&&(l.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 l=this._scene.layouts.get(e);l&&(l.isLoaded=!0)}finally{this._loadingLayouts.delete(e)}})()}catch(t){p.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,o=>this.hasEntity(o));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)}startTextStyleFontPreload(e){var y,g;const t=this._convertEpoch;if(this._textStyleFontPreloadEpoch===t&&this._textStyleFontPreloadPromise)return;this._textStyleFontPreloadEpoch=t;const i=Jv(e),n=$.FontManager.instance.getFontsToLoad(),o=[...$.FontManager.instance.defaultFonts][0],r=Qv(i,n,{firstDefaultFont:o}),l=D.AcTrMTextRenderer.getInstance().getRenderMode()==="worker"?"worker":"main",c=k,d=(g=(y=c._instance)==null?void 0:y.lastPresetFontsForOpen)!=null&&g.length?[...c._instance.lastPresetFontsForOpen]:[...n];if(this._fontPreloadDiag={critical:[...r.critical],workerWarm:[],background:[],preset:d,workerSkipped:0,parseSite:l},l==="worker"){this._textStyleFontPreloadPromise=Promise.resolve();return}const h=3e4;if(r.critical.length===0){this._textStyleFontPreloadPromise=Promise.resolve();return}const f=$.FontManager.instance.requestFonts(r.critical);this._textStyleFontPreloadPromise=new Promise(b=>{const w=setTimeout(()=>{b()},h);f.then(()=>{clearTimeout(w),b()},()=>{clearTimeout(w),b()})})}async awaitTextStyleFontsReady(){if(!this._textStyleFontPreloadPromise){const e=this._renderer.context.database;if(e)this.startTextStyleFontPreload(e);else return}await this._textStyleFontPreloadPromise}async finishEntityGeometry(e,t){const i=performance.now();try{const n=e instanceof D.AcTrGroup,o=n&&this.groupHasPendingGlyphGeometry(e);(o||D.hasPendingComplexLineTypeGlyphs(e)||e instanceof D.AcTrGlyphEntity&&!e.hasDrawableGeometry())&&await this.ensureDeferredFontsReady();const a=()=>{this._convertPhaseMs.glyphEntityCount++,e instanceof D.AcTrMText?this._convertPhaseMs.mtextCount++:e instanceof D.AcTrShape&&this._convertPhaseMs.shapeCount++};if(n){if(!o)return;a();const c=performance.now();await e.asyncDraw(),this._convertPhaseMs.finishGeometryAsyncDraw+=performance.now()-c;return}if(D.hasPendingComplexLineTypeGlyphs(e)){a();const c=performance.now();await e.asyncDraw(),this._convertPhaseMs.finishGeometryAsyncDraw+=performance.now()-c;return}if(e.hasDrawableGeometry())return;a();const l=performance.now();await e.asyncDraw(),this._convertPhaseMs.finishGeometryAsyncDraw+=performance.now()-l}finally{this._convertPhaseMs.finishGeometry+=performance.now()-i}}needsDeferredFontGeometry(e){return e instanceof D.AcTrGlyphEntity?!e.hasDrawableGeometry():e instanceof D.AcTrGroup?this.groupHasPendingGlyphGeometry(e):D.hasPendingComplexLineTypeGlyphs(e)}clearFontLoadedRedrawTimer(){this._fontLoadedRedrawTimer!=null&&(clearTimeout(this._fontLoadedRedrawTimer),this._fontLoadedRedrawTimer=null)}scheduleGlyphRedrawAfterFontLoad(e){this.clearFontLoadedRedrawTimer();const t=this._convertEpoch;this._fontLoadedRedrawTimer=setTimeout(()=>{this._fontLoadedRedrawTimer=null,t===this._convertEpoch&&this.redrawGlyphEntitiesAfterFontLoad(t,e)},50)}async redrawGlyphEntitiesAfterFontLoad(e,t){var a,l;if(e!==this._convertEpoch)return;const i=++this._fontLoadedRedrawEpoch,n=[];for(const c of this._scene.layouts.values())c.layers.forEach(d=>{d.internalObject.traverse(h=>{h instanceof D.AcTrGlyphEntity&&n.push(h)})});for(const c of n){if(e!==this._convertEpoch||i!==this._fontLoadedRedrawEpoch)return;await c.asyncDraw()}if(n.length>0){e===this._convertEpoch&&(this._isDirty=!0);return}if(t){const c=$.FontManager.instance.defaultFonts,d=t.toLowerCase();if(c.has(t)||c.has(d)||[...c].some(h=>h.toLowerCase()===d))return}if(e!==this._convertEpoch||i!==this._fontLoadedRedrawEpoch||this._entityProcessingIdleAt<=0)return;const o=performance.now()-this._entityProcessingIdleAt;if(!aL(this.isProcessingEntities,0,o))return;const r=(l=(a=k.instance)==null?void 0:a.curDocument)==null?void 0:l.database;r&&r.regen()}groupHasPendingGlyphGeometry(e){for(const t of e.getSourceEntities())if(t instanceof D.AcTrGlyphEntity&&!t.hasDrawableGeometry())return!0;return de.directChildrenHavePendingGlyphs(e)}static directChildrenHavePendingGlyphs(e){const t=e.children;for(let i=0;i<t.length;i++){const n=t[i];if(n instanceof D.AcTrGlyphEntity){if(!n.hasDrawableGeometry())return!0;continue}if(n instanceof D.AcTrGroup){for(const o of n.getSourceEntities())if(o instanceof D.AcTrGlyphEntity&&!o.hasDrawableGeometry())return!0;if(de.directChildrenHavePendingGlyphs(n))return!0;continue}if(n instanceof D.AcTrEntity&&de.directChildrenHavePendingGlyphs(n))return!0}return!1}enqueueDeferredGeometry(e,t){t===this._convertEpoch&&(this._pendingGeometryJobs++,this._deferredGeometryQueue.push({run:e,epoch:t,enqueuedAt:performance.now()}),this.pumpDeferredGeometryQueue())}pumpDeferredGeometryQueue(){for(;this._deferredGeometryActive<de.DEFERRED_GEOMETRY_CONCURRENCY&&this._deferredGeometryQueue.length>0;){const e=this._deferredGeometryQueue.shift();if(e.epoch!==this._convertEpoch){this._pendingGeometryJobs=Math.max(0,this._pendingGeometryJobs-1);continue}this._convertPhaseMs.finishGeometryQueueWait+=performance.now()-e.enqueuedAt,this._deferredGeometryActive++,e.run().then(()=>{e.epoch===this._convertEpoch&&(this._progressiveRendering||this._cooperativeYield)&&(this._isDirty=!0)}).catch(t=>{p.log.error("[AcTrView2d] Deferred entity geometry failed:",t)}).finally(()=>{this._deferredGeometryActive=Math.max(0,this._deferredGeometryActive-1),e.epoch===this._convertEpoch&&(this._pendingGeometryJobs=Math.max(0,this._pendingGeometryJobs-1),this._pendingGeometryJobs===0&&(this._isDirty=!0),this.stampEntityProcessingIdle()),this.pumpDeferredGeometryQueue()})}}resetDeferredGeometryQueue(){this._deferredGeometryQueue.length=0,this._pendingGeometryJobs=0,this._textStyleFontPreloadPromise=null,this._textStyleFontPreloadEpoch=-1,this._deferredFontsReady=null,this._fontPreloadDiag=null}async waitUntilDeferredGeometryIdle(){const e=this._convertEpoch;for(;e===this._convertEpoch&&this._pendingGeometryJobs>0;)await new Promise(t=>setTimeout(t,0))}attachViewportView(e){if(D.AcTrViewportView.isDefaultPaperSpaceViewport(e))return;const t=e.ownerId,i=t?this._layoutViewManager.getAt(t):void 0;if(!i){t&&this._viewportRepairOwnerIds.add(t);return}i.addViewport(new D.AcTrViewportView(i,this.toGiViewportWithFrozenLayers(e),this._renderer)),this._isDirty=!0}ensureViewportViews(e,t){const i=e.newIterator();for(const n of i){if(!(n instanceof p.AcDbViewport)||D.AcTrViewportView.isDefaultPaperSpaceViewport(n))continue;const o=new D.AcTrViewportView(t,this.toGiViewportWithFrozenLayers(n),this._renderer);t.addViewport(o)}}toGiViewportWithFrozenLayers(e){var r;const t=e.toGiViewport();if(t.frozenLayers&&t.frozenLayers.length>0)return t;const i=e.frozenLayerIds;if(!(i!=null&&i.length))return t;const n=[],o=(r=e.database)==null?void 0:r.tables.layerTable;if(o)for(const a of i){const l=o.getIdAt(a);l&&n.push(l.name)}return t.frozenLayerIds=[...i],t.frozenLayers=n,t}async batchConvert(e,t={}){const i=this._convertEpoch;if(!t.forExport&&!this._textStyleFontPreloadPromise){const l=this._renderer.context.database;l&&this.startTextStyleFontPreload(l)}const n=this._progressiveRendering&&!t.forExport,o=n?de.PROGRESSIVE_OPEN_YIELD_BUDGET_MS:de.OPEN_CONVERT_YIELD_BUDGET_MS,r=t.forExport||!this._cooperativeYield?void 0:new p.AcCmUiYieldGate(o),a=()=>new Promise(l=>setTimeout(l,0));for(let l=0;l<e.length;++l){const c=e[l];try{if(i!==this._convertEpoch||c instanceof p.AcDbViewport&&D.AcTrViewportView.isDefaultPaperSpaceViewport(c)||!(t.forExport||this._convertInvisibleLayers?this._entityDisplay.shouldConvertForExport(c):this._entityDisplay.shouldConvert(c)))continue;const h=String(c.objectId??"");let f=0;if(h&&(this.hasEntity(h)||this._claimedConvertObjectIds.has(h))){c instanceof p.AcDbViewport&&this.attachViewportView(c);continue}h&&(this._claimedConvertObjectIds.add(h),f=this._entityConvertGeneration.get(h)??0);const y=D.tryBuildDirectEntityMeta(c,this._renderer);if(y){let b=!1,w=!1;try{h&&(this._entityConvertGeneration.get(h)??0)!==f?w=!0:(b=this._scene.addDirectEntity(y,D.shouldExtendBboxForDirectEntity(c)),b&&(this.applySessionHiddenObjectState(c.objectId),n?(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.getDrawingExtents(),l)):this.markInteractiveOpenDirty()))}finally{y.geometry.dispose()}if(w||b)continue}const g=this.drawEntity(c,!1);if(!g&&!(c instanceof p.AcDbViewport)){h&&this._claimedConvertObjectIds.delete(h);continue}if(g){g.objectId=c.objectId,g.ownerId=c.ownerId,g.layerName=c.layer,g.visible=c.visibility!==!1,g instanceof D.AcTrGroup&&g.isOnTheSameLayer&&(g.userData.insertLayerName=g.layerName);const b=g instanceof D.AcTrGroup&&!g.isOnTheSameLayer,w=!t.forExport&&this.needsDeferredFontGeometry(g);if(b)w?this.enqueueDeferredGeometry(()=>this.handleGroup(g,n,i,f),i):await this.handleGroup(g,n,i,f);else{const S=!(c instanceof p.AcDbRay||c instanceof p.AcDbXline),x=async()=>{if(await this.finishEntityGeometry(g,n),i!==this._convertEpoch){g.dispose();return}if(h&&(this._entityConvertGeneration.get(h)??0)!==f){g.dispose();return}g instanceof D.AcTrGroup&&(this.syncGroupSpatialBoundsForIndexing(g),g.isOnTheSameLayer&&this._inheritedLayerMaterialMapper.remap(g.children,"0",g.layerName));const _=performance.now();this._scene.addEntity(g,S),this._convertPhaseMs.addEntity+=performance.now()-_,this.applySessionHiddenObjectState(c.objectId),g.dispose(),n?(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.getDrawingExtents(),l)):this.markInteractiveOpenDirty()};w?this.enqueueDeferredGeometry(x,i):await x()}}if(i!==this._convertEpoch)continue;if(c instanceof p.AcDbViewport)this.attachViewportView(c);else if(c instanceof p.AcDbRasterImage){const b=c.imageFileName;b&&!c.image?this._missedImages.set(c.objectId,b):c.image&&this._missedImages.delete(c.objectId)}}catch(d){const h=String(c.objectId??"");h&&this._claimedConvertObjectIds.delete(h),p.log.error(`[AcTrView2d] Failed to convert entity ${c.objectId} (${c.type}):`,d)}finally{i===this._convertEpoch&&this.decreaseNumOfEntitiesToProcess()}i===this._convertEpoch&&(n?await this.progressiveYieldForInput(r,a):r&&await r.maybeYield(a)&&this._progressiveYieldCount++)}}syncGroupSpatialBoundsForIndexing(e){const t=e.peekLazyChildBoxes();if(t&&t.boxes.length>0){const o=e.userData;o.lazySpatialChildren=t;return}if(e.refreshWcsChildBoxesFromChildren(),e.wcsChildBoxes.length===0)return;const i=e.wcsChildBoxes.map(o=>({minX:o.minX,minY:o.minY,maxX:o.maxX,maxY:o.maxY,id:o.id}));e.wcsBbox=zl(e);const n=e.userData;n.spatialIndexChildBoxes=i}async handleGroup(e,t,i=this._convertEpoch,n=0){const o=performance.now();try{if(await this.finishEntityGeometry(e,t),i!==this._convertEpoch){e.dispose();return}const r=String(e.objectId??"");if(r&&(this._entityConvertGeneration.get(r)??0)!==n){e.dispose();return}this.syncGroupSpatialBoundsForIndexing(e);const a=e.children,l=new Map;a.forEach(x=>{var C;if(x.visible===!1)return;const _=x.userData.layerName;l.has(_)||l.set(_,[]),(C=l.get(_))==null||C.push(x)}),e.children=[];for(const x of a)x.parent=null;const c=e.renderContext,d=e.objectId,h=e.layerName,f=e.userData.lazySpatialChildren;process.env.NODE_ENV!=="production"&&!f&&pS(e);const y=f?[]:e.wcsChildBoxes.map(x=>({minX:x.minX,minY:x.minY,maxX:x.maxX,maxY:x.maxY,id:x.id})),g=f?e.wcsBbox.clone():y.length>0?zl(e):e.wcsBbox.clone();y.length>0&&(e.wcsBbox=g.clone());let b=!1;const w=()=>new Promise(x=>setTimeout(x,0));let S=t?performance.now():0;for(const[x,_]of l){const C=x==="0"?h:x,T=_.some(A=>(A.userData.authoredLayerName??x)==="0")?"0":x;this._inheritedLayerMaterialMapper.remap(_,T,C);const L=new D.AcTrEntity(c);L.matrix.copy(e.matrix),L.matrixAutoUpdate=!1,L.matrixWorldNeedsUpdate=!0,L.objectId=d,L.ownerId=e.ownerId,L.layerName=C,L.userData.insertLayerName=h,L.wcsBbox=g.clone();const N=L.userData;!b&&f?(L.userData.lazySpatialChildren=f,b=!0):!b&&y.length>0&&(N.spatialIndexChildBoxes=y,b=!0);for(let A=0;A<_.length;A++)L.add(_[A]);L.updateMatrixWorld(!0),this._layerAppearance.refreshTextMaterialsInObjectTree(L);const B=performance.now();this._scene.addEntity(L,!0),this._convertPhaseMs.addEntity+=performance.now()-B,this.applySessionHiddenObjectState(d),L.dispose(),t&&i===this._convertEpoch&&performance.now()-S>=de.PROGRESSIVE_OPEN_YIELD_BUDGET_MS&&(await w(),S=performance.now())}e.dispose(),t?(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.getDrawingExtents())):this.markInteractiveOpenDirty()}finally{this._convertPhaseMs.handleGroup+=performance.now()-o}}decreaseNumOfEntitiesToProcess(){this._numOfEntitiesToProcess--,this._numOfEntitiesToProcess<0?(this._numOfEntitiesToProcess=0,p.log.warn("Something wrong! The number of entities to process should not be less than 0.")):this._numOfEntitiesToProcess===0&&(this._isDirty=!0,Q.emit("missed-data-changed",{})),this.stampEntityProcessingIdle()}frameOpenLineworkIfReady(){if(!this._openLineworkFramePending||this.isConvertingEntities)return;const e=this.getDrawingExtents();if(!e||e.isEmpty()){this._openLineworkFramePending=!1;return}this._openLineworkFramePending=!1,this._progressiveOpenFit.frameProgrammatically(e)}stampEntityProcessingIdle(){this._numOfEntitiesToProcess===0&&this._pendingGeometryJobs===0&&(this._entityProcessingIdleAt=performance.now(),this.scheduleMeshGlyphWorldBatchFlush(),p.AcDbRenderingCache.instance.clear())}clearMeshGlyphFlushTimer(){this._meshGlyphFlushTimer!=null&&(clearTimeout(this._meshGlyphFlushTimer),this._meshGlyphFlushTimer=null)}scheduleMeshGlyphWorldBatchFlush(){if(!D.AcTrMTextRenderer.getInstance().getMeshGlyphInstancing())return;this.clearMeshGlyphFlushTimer();const t=this._convertEpoch;this._meshGlyphFlushTimer=setTimeout(()=>{this._meshGlyphFlushTimer=null,t===this._convertEpoch&&(this._numOfEntitiesToProcess>0||this._pendingGeometryJobs>0||this.flushMeshGlyphWorldBatch())},16)}flushMeshGlyphWorldBatch(){this.clearMeshGlyphFlushTimer();const e=D.AcTrMTextRenderer.getInstance();if(!e.getMeshGlyphInstancing())return;const{placements:t,buckets:i}=e.flushMeshGlyphInstances(this._scene.internalScene,n=>this.resolveMeshGlyphLayerParent(n));t>0&&(console.log(`[cad-simple-viewer-cli] mesh glyph InstancedMesh flush: placements=${t} buckets=${i}`),this._isDirty=!0)}resolveMeshGlyphLayerParent(e){var i;const t=(i=this._scene.activeLayout)==null?void 0:i.getLayer(e);if(t)return t.internalObject;for(const n of this._scene.layouts.values()){const o=n.getLayer(e);if(o)return o.internalObject}return null}};de.OPEN_CONVERT_YIELD_BUDGET_MS=300,de.PROGRESSIVE_OPEN_YIELD_BUDGET_MS=32,de.PROGRESSIVE_INPUT_PAUSE_MS=120,de.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS=2500,de.NON_PROGRESSIVE_OPEN_PAINT_INTERVAL_MS=4e3,de.DEFERRED_GEOMETRY_CONCURRENCY=8,de.CONVERT_SLICE_BUDGET_MS=64,de.CONVERT_SLICE_MAX=512;let Mn=de;function lL(s){if(!s)return!1;const e=Object.keys(s);return e.length>0&&e.every(t=>t==="visibility")}function cL(s,e,t){const{entity:i,changes:n}=s,o=i.objectId;if(!e(o))return!1;if(lL(n))return!(n.visibility===!0&&t(o)===void 0);if(n&&Object.keys(n).length>0)return!1;const r=t(o);return r===void 0?!1:r&&!i.visibility}function yx(s){return Array.isArray(s)?s:[s]}class Ea{constructor(e,t){this._active=!0,this._disposers=[],this._view=e,this._doc=t;const i=(n,o)=>{n.addEventListener(o),this._disposers.push(()=>n.removeEventListener(o))};i(t.database.events.entityAppended,n=>{if(!this._active)return;const o=yx(n.entity).filter(r=>{if(this.view.hasEntity(r.objectId))return!1;const a=t.database.tables.blockTable.getIdAt(r.ownerId);return!!(a&&(a.isModelSapce||a.isPaperSapce))});o.length!==0&&this.view.addEntity(o.length===1?o[0]:o)}),i(t.database.events.entityModified,n=>{if(!this._active)return;const o=n,r=this.view;r instanceof Mn&&cL(o,a=>r.hasEntity(a),a=>r.getEntityVisible(a))&&r.updateEntityVisibility(o.entity)||this.view.updateEntity(o.entity)}),i(t.database.events.entityErased,n=>{if(!this._active)return;const o=yx(n.entity).filter(r=>this.view.hasEntity(r.objectId));o.length!==0&&this.view.removeEntity(o.length===1?o[0]:o)}),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(p.AcDbSysVarManager.instance().events.sysVarChanged,n=>{if(!(!this._active||n.database!==this._doc.database)){if(n.name==p.AcDbSystemVariables.PDMODE.toLowerCase()||n.name==p.AcDbSystemVariables.PDSIZE.toLowerCase())this._view.rerenderPoints(n.database.pdmode,n.database.pdsize);else if(n.name==p.AcDbSystemVariables.LWDISPLAY.toLowerCase()){const o=this._view,r=!!n.database.lwdisplay;o.renderer.showLineWeight!==r&&(o.renderer.showLineWeight=r,o.clear(),n.database.regen())}}}),i(t.database.events.dictObjetSet,n=>{this._active&&n.object instanceof p.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 wu(s){return typeof s.hasEntity=="function"&&typeof s.setEntitySceneVisible=="function"}function dL(s,e,t){!s.isObjectHidden(t)||!wu(e)||e.setEntitySceneVisible(t,!1)}function gx(s,e){const t=s.view;if(!wu(t))return 0;const i=s.doc,n=i.database;let o=0;for(const r of e){if(i.isObjectHidden(r))continue;const a=n.tables.blockTable.getEntityById(r);!(a!=null&&a.visibility)||!t.hasEntity(r)||t.setEntitySceneVisible(r,!1)&&(i.addHiddenObject(r),o++)}return o>0&&t.selectionSet.clear(),o}function bx(s){const e=s.view;if(!wu(e))return 0;const t=s.doc,i=t.database,n=t.takeHiddenObjects();let o=0;for(const r of n){const a=i.tables.blockTable.getEntityById(r);!a||!e.hasEntity(r)||e.setEntitySceneVisible(r,a.visibility)&&o++}return e.selectionSet.clear(),o}const vu=500,uL=/[̀-ͯ]/g,xu=/\s+/g;function Xs(s,e=!1){let t=s.normalize("NFKC").replace(xu," ").trim();return e||(t=t.normalize("NFD").replace(uL,"").toLowerCase()),t}function qs(s){const e=/\\(U\+[0-9a-fA-F]{4}|[PX~SfFHWTQCcAaRrpLlOoKk\\{}])|[{}]/g,t=[];let i=0,n=!1,o;for(;o=e.exec(s);){t.push(s.slice(i,o.index));const r=o[1];let a="";if(r!=null&&r.startsWith("U+"))a=String.fromCharCode(parseInt(r.slice(2),16));else if(r==="P"||r==="X"||r==="~")a=" ";else if(r==="\\"||r==="{"||r==="}")a=r;else if(r&&/[SfFHWTQCcAaRrp]/.test(r)){const l=n?-1:s.indexOf(";",e.lastIndex);if(l===-1)n=!0,a=o[0];else{if(r==="S"){const c=s.slice(e.lastIndex,l),d=c.search(/[\^#/]/);if(d===-1)a=c;else{const h=c.slice(d+1);a=c.slice(0,d)+(h?`/${h}`:"")}}e.lastIndex=l+1}}t.push(a),i=e.lastIndex}return t.push(s.slice(i)),wx(t.join("")).replace(xu," ").trim()}function wx(s){return s.replace(/%%[cC]/g,"Ø").replace(/%%[dD]/g,"°").replace(/%%[pP]/g,"±")}function La(s){return typeof s=="string"?wx(s).normalize("NFKC").replace(xu," ").trim():""}function vx(s,e,t){var r;const i=t.get(e);if(i!==void 0)return i;const n=(r=s.tables.layerTable)==null?void 0:r.getAt(e),o=!(n!=null&&n.isOff||n!=null&&n.isFrozen);return t.set(e,o),o}function Ta(s){const e=s.position??s.location??s.textLocation??s.textPosition??{x:0,y:0};return{x:Number(e.x)||0,y:Number(e.y)||0}}function hL(s,e){const t=new Array(16);for(let i=0;i<4;i++)for(let n=0;n<4;n++){let o=0;for(let r=0;r<4;r++)o+=s[r*4+n]*e[i*4+r];t[i*4+n]=o}return t}function xx(s,e){if(!s)return{x:e.x,y:e.y};const t=Number(e.z)||0;return{x:s[0]*e.x+s[4]*e.y+s[8]*t+s[12],y:s[1]*e.x+s[5]*e.y+s[9]*t+s[13]}}function kx(s){var e;try{const t=(e=s.blockTransform)==null?void 0:e.elements;return Array.isArray(t)&&t.length===16?t:void 0}catch{return}}function pL(s,e){var n,o;let t;try{t=s.geometricExtents}catch{return}if(!t||!isFinite((n=t.min)==null?void 0:n.x)||!isFinite((o=t.max)==null?void 0:o.x))return;if(!e)return{min:{...t.min},max:{...t.max}};const i=[{x:t.min.x,y:t.min.y},{x:t.max.x,y:t.min.y},{x:t.min.x,y:t.max.y},{x:t.max.x,y:t.max.y}].map(r=>xx(e,r));return{min:{x:Math.min(...i.map(r=>r.x)),y:Math.min(...i.map(r=>r.y))},max:{x:Math.max(...i.map(r=>r.x)),y:Math.max(...i.map(r=>r.y))}}}const mL=8;function Sx(s,e,t,i={}){var w,S,x,_;const n=i.matchCase===!0,o=i.maxResults??vu,r=Xs(t,n),a={hits:[],truncated:!1};if(!r)return a;const l=s.tables.blockTable.getIdAt(e);if(!l)return a;const c=new Map,d=C=>C!==""&&Xs(C,n).includes(r);let h=!1;const f=C=>{if(a.hits.length>=o){a.truncated=!0,h=!0;return}a.hits.push(C)},y=(C,T,L,N,B,A,O={})=>{const P=pL(L,A);f({entityId:C.entity.objectId,textEntityId:`${T}/${L.objectId}`,kind:N,text:B,layer:C.layer,position:xx(A,Ta(L)),...P?{extents:P}:{},...O})},g=(C,T,L,N,B,A)=>{var O,P,E;for(const I of C){if(h)return;const j=I.dxfTypeName;if(j!=="TEXT"&&j!=="MTEXT"&&j!=="INSERT"&&j!=="ATTRIB"&&j!=="ATTDEF"||I.visibility===!1||j==="ATTDEF"&&(I.isInvisible||!(I.isConst||I.isConstMTextAttribute))||I.layer&&I.layer!=="0"&&!vx(s,I.layer,c))continue;if(j==="INSERT"){if(B>=mL)continue;const ee=kx(I),Z=L&&ee?hL(L,ee):ee??L,re=`${N}/${I.objectId}`;for(const pt of((O=I.attributeIterator)==null?void 0:O.call(I))??[]){if(h)return;if(pt.visibility===!1||pt.isInvisible)continue;const Be=La(pt.textString);d(Be)&&y(T,re,pt,"block",Be,L,{tag:pt.tag,blockName:I.blockName})}const Se=I.blockName;if(!Se||A.has(Se))continue;const Ke=(E=(P=s.tables.blockTable).getAt)==null?void 0:E.call(P,Se);if(!Ke)continue;A.add(Se),g(Ke.newIterator(),T,Z,re,B+1,A),A.delete(Se);continue}const Y=j==="MTEXT"||j==="ATTDEF"&&I.isConstMTextAttribute&&I.mtext?qs(String((j==="MTEXT"?I:I.mtext).contents??"")):La(I.textString);d(Y)&&y(T,N,I,T.kind,Y,L,j==="ATTDEF"?{tag:I.tag}:{})}},b=C=>{var T,L;try{const N=C.blockTableRecord;if(N!=null&&N.newIterator)return N;const B=C.dimBlockId,A=B?s.tables.blockTable.getIdAt(B):void 0;if(A)return A;const O=C.blockName;return O?(L=(T=s.tables.blockTable).getAt)==null?void 0:L.call(T,O):void 0}catch{return}};for(const C of l.newIterator()){if(h)break;const T=C.dxfTypeName;if(T!=="TEXT"&&T!=="MTEXT"&&T!=="INSERT"&&T!=="DIMENSION"&&T!=="MULTILEADER"&&T!=="ACAD_TABLE"||C.visibility===!1||!vx(s,C.layer,c))continue;if(T==="INSERT"){for(const A of((w=C.attributeIterator)==null?void 0:w.call(C))??[]){if(h)break;if(A.visibility===!1||A.isInvisible)continue;const O=La(A.textString);d(O)&&f({entityId:C.objectId,textEntityId:A.objectId,kind:"attribute",text:O,tag:A.tag,blockName:C.blockName,layer:C.layer,position:Ta(A)})}const N=C.blockName,B=N?(x=(S=s.tables.blockTable).getAt)==null?void 0:x.call(S,N):void 0;B&&!h&&g(B.newIterator(),{entity:C,kind:"block",layer:C.layer},kx(C),String(C.objectId),1,new Set([N]));continue}if(T==="DIMENSION"||T==="ACAD_TABLE"){const N=T==="DIMENSION"?"dimension":"table",B={entity:C,kind:N,layer:C.layer},A=b(C),O=a.hits.length;if(A&&g(A.newIterator(),B,void 0,String(C.objectId),1,new Set),A&&a.hits.length>O)continue;const P=[];if(T==="DIMENSION"){const E=String(C.dimensionText??"");E&&E!=="<>"&&E!==" "&&P.push(qs(E.replace("<>","")))}else{const E=Number(C.numRows)||0,I=Number(C.numColumns)||0;for(let j=0;j<E;j++)for(let G=0;G<I;G++)try{P.push(qs(String(((_=C.textString)==null?void 0:_.call(C,j,G))??"")))}catch{}}for(const E of P){if(h)break;d(E)&&f({entityId:C.objectId,textEntityId:`${C.objectId}/${a.hits.length}`,kind:N,text:E,layer:C.layer,position:Ta(C)})}continue}const L=T==="MTEXT"||T==="MULTILEADER"?qs(String(C.contents??"")):La(C.textString);d(L)&&f({entityId:C.objectId,textEntityId:C.objectId,kind:T==="MTEXT"?"mtext":T==="MULTILEADER"?"leader":"text",text:L,layer:C.layer,position:Ta(C)})}return a}function fL(s,e,t=!1,i=60){if(s.length<=i)return s;const n=Xs(e,t),o=Xs(s,t).indexOf(n),r=Math.max(0,Math.min(o-15,s.length-i)),a=s.slice(r,r+i);return`${r>0?"…":""}${a}${r+i<s.length?"…":""}`}function Cx(s){var i;const e=(i=s.objects)==null?void 0:i.layout;if(!(e!=null&&e.newIterator))return[];const t=[];for(const n of e.newIterator())n.blockTableRecordId&&t.push({name:n.layoutName??"",btrId:n.blockTableRecordId,tabOrder:Number(n.tabOrder)||0});return t.sort((n,o)=>n.tabOrder-o.tabOrder||n.name.localeCompare(o.name))}function yL(s,e,t){const i=t.maxResults??vu,n=Cx(s),o=l=>{var c;return((c=n.find(d=>d.btrId===l))==null?void 0:c.name)??""};let r;t.scope==="layout"||n.length===0?r=[{btrId:t.currentLayoutId,name:o(t.currentLayoutId)}]:r=n.map(l=>({btrId:l.btrId,name:l.name}));const a={hits:[],truncated:!1};for(const l of r){const c=Sx(s,l.btrId,e,{matchCase:t.matchCase,maxResults:i-a.hits.length});for(const d of c.hits)a.hits.push({...d,layoutId:l.btrId,layoutName:l.name});if(c.truncated){a.truncated=!0;break}}return a}function Ax(s,e,t){var g;const i=s.tables.blockTable.getIdAt(e),n=(g=i==null?void 0:i.getIdAt)==null?void 0:g.call(i,t.entityId);let o=n;if(t.kind==="attribute"&&(n!=null&&n.attributeIterator)){for(const b of n.attributeIterator())if(b.objectId===t.textEntityId){o=b;break}}let r,a;try{const b=t.extents??(o==null?void 0:o.geometricExtents);if(!b||!isFinite(b.min.x)||!isFinite(b.max.x))throw new Error("no extents");r=b.min,a=b.max}catch{r=a=t.position}const l=(r.x+a.x)/2,c=(r.y+a.y)/2,d=a.x-r.x,h=a.y-r.y,f=Math.max(d*3,h*10,.001),y=Math.max(h*3,f/4,.001);return{min:{x:l-f/2,y:c-y/2},max:{x:l+f/2,y:c+y/2}}}function gL(s,e,t,i){const n=Number(s.width)||0,o=Number(s.height)||0,r=Math.max(0,(i==null?void 0:i.left)??0),a=Math.max(0,(i==null?void 0:i.right)??0),l=Math.max(0,(i==null?void 0:i.top)??0),c=Math.max(0,(i==null?void 0:i.bottom)??0),d=n-r-a,h=o-l-c;if(!(n>0&&o>0&&r+a+l+c>0&&d>=n*.2&&h>=o*.2&&!!s.worldToScreen&&!!s.screenToWorld)){s.zoomTo(new p.AcGeBox2d(new p.AcGePoint2d(e.min.x,e.min.y),new p.AcGePoint2d(e.max.x,e.max.y)),t);return}const y=(e.min.x+e.max.x)/2,g=(e.min.y+e.max.y)/2,b=(e.max.x-e.min.x)/2*(n/d),w=(e.max.y-e.min.y)/2*(o/h);s.zoomTo(new p.AcGeBox2d(new p.AcGePoint2d(y-b,g-w),new p.AcGePoint2d(y+b,g+w)),t);const S=s.worldToScreen({x:y,y:g}),x=r+d/2,_=l+h/2,C=s.screenToWorld({x:n/2+(S.x-x),y:o/2+(S.y-_)});isFinite(C.x)&&isFinite(C.y)&&(s.center=new p.AcGePoint2d(C.x,C.y))}const ku=new WeakMap;async function bL(s,e,t={}){var a;const i=s.curView,n=(a=s.curDocument)==null?void 0:a.database;if(!i||!n)return"no-document";const o=(ku.get(i)??0)+1;if(ku.set(i,o),i.activeLayoutBtrId!==e.layoutId){if(t.activateLayout===!1)return"layout-mismatch";if(!n.tables.blockTable.getIdAt(e.layoutId))return"layout-missing";if(i.isLayoutInitialized(e.layoutId)||i.markLayoutAsInitialized(e.layoutId),p.acdbHostApplicationServices().layoutManager.setCurrentLayoutBtrId(e.layoutId,n),i.activeLayoutBtrId!==e.layoutId)return"layout-switch-failed";if(await i.waitUntilIdle(t.idleTimeoutMs??15e3),ku.get(i)!==o||i.activeLayoutBtrId!==e.layoutId)return"stale"}const r=Ax(n,e.layoutId,e);return gL(i,r,t.margin??1.1,t.insets),i.selectionSet.clear(),i.selectionSet.add(e.entityId),"navigated"}class wL extends K{async execute(e){p.log.info("Hello from ExamplePlugin!"),p.log.info("Current document:",e.doc),p.log.info("Current view:",e.view)}}class vL{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 wL),this.registeredCommands.push({group:"USER",name:"HELLO"}),p.log.info(`[${this.name}] Plugin loaded successfully`),p.log.info(`[${this.name}] Registered command: HELLO`)}onUnload(e,t){for(const i of this.registeredCommands)t.removeCmd(i.group,i.name);this.registeredCommands=[],p.log.info(`[${this.name}] Plugin unloaded`)}}const _x=[".dxf",".dwg"],Js="local",Su="url",xL="100%",kL="150px";function Px(s,e){return s==null?e:typeof s=="number"?`${s}px`:s}const zn=class zn{constructor(e){if(this.activeView=Js,this.menuOpen=!1,this.disposed=!1,this.unsubManager=null,this.unsubTheme=null,this.onDocPointerDown=null,this.options={...e,cardSize:{...e.cardSize??{}}},zn.ensureStyles(),this.root=document.createElement("div"),this.root.className="ml-ui-file-open",this.root.setAttribute("data-ml-ui-file-open","1"),this.applyTheme(),e.title||e.subtitle){const a=document.createElement("div");if(a.className="ml-ui-file-open-header",e.title){const l=document.createElement("h2");l.className="ml-ui-file-open-title",l.textContent=e.title,a.appendChild(l)}if(e.subtitle){const l=document.createElement("p");l.className="ml-ui-file-open-subtitle",l.textContent=e.subtitle,a.appendChild(l)}this.root.appendChild(a)}if(e.showNewDrawing){const a=document.createElement("button");a.type="button",a.className="ml-ui-file-open-primary",a.textContent=m.t("main.dataSource.newDrawing"),a.addEventListener("click",()=>this.emit({kind:"new-drawing"})),this.root.appendChild(a),this.root.appendChild(this.createDivider())}this.card=document.createElement("div"),this.card.className="ml-ui-file-open-card",this.applyCardSize(),this.root.appendChild(this.card),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept=e.accept??_x.join(","),this.fileInput.className="ml-ui-file-open-input-hidden",this.fileInput.addEventListener("change",()=>{var l;const a=(l=this.fileInput.files)==null?void 0:l[0];this.fileInput.value="",a&&this.isSupportedFileName(a.name)&&this.emitLocal(a)}),this.card.appendChild(this.fileInput),this.contentEl=document.createElement("div"),this.contentEl.className="ml-ui-file-open-body",this.card.appendChild(this.contentEl),this.dropzone=document.createElement("div"),this.dropzone.className="ml-ui-file-open-dropzone",this.dropzone.tabIndex=0,this.dropzone.setAttribute("role","button"),this.dropzone.setAttribute("aria-label",m.t("main.dataSource.dropOrBrowse"));const t=document.createElement("p");t.className="ml-ui-file-open-drop-title",t.append(document.createTextNode(`${m.t("main.dataSource.dropFile")} `));const i=document.createElement("span");i.className="ml-ui-file-open-drop-link",i.textContent=m.t("main.dataSource.browse"),t.appendChild(i);const n=document.createElement("div");n.className="ml-ui-file-open-tags";for(const a of["DWG","DXF"]){const l=document.createElement("span");l.className="ml-ui-file-open-tag",l.textContent=a,n.appendChild(l)}this.dropzone.appendChild(t),this.dropzone.appendChild(n),this.dropzone.addEventListener("click",()=>this.fileInput.click()),this.dropzone.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),this.fileInput.click())}),this.dropzone.addEventListener("dragenter",a=>this.onDrag(a,!0)),this.dropzone.addEventListener("dragover",a=>this.onDrag(a,!0)),this.dropzone.addEventListener("dragleave",a=>this.onDrag(a,!1)),this.dropzone.addEventListener("drop",a=>this.onDrop(a)),this.urlRow=document.createElement("div"),this.urlRow.className="ml-ui-file-open-url-row",this.urlInput=document.createElement("input"),this.urlInput.type="url",this.urlInput.className="ml-ui-file-open-url-input",this.urlInput.placeholder=m.t("main.dataSource.urlPlaceholder"),this.urlInput.autocomplete="off",this.urlInput.spellcheck=!1,this.urlInput.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.submitUrl())});const o=document.createElement("button");o.type="button",o.className="ml-ui-file-open-secondary",o.textContent=m.t("main.dataSource.open"),o.addEventListener("click",()=>this.submitUrl()),this.urlRow.appendChild(this.urlInput),this.urlRow.appendChild(o),this.sourceActionsEl=document.createElement("div"),this.sourceActionsEl.className="ml-ui-file-open-sources";const r=document.createElement("div");r.className="ml-ui-file-open-footer",this.footerBtn=document.createElement("button"),this.footerBtn.type="button",this.footerBtn.className="ml-ui-file-open-footer-btn",this.footerBtn.setAttribute("aria-label",m.t("main.dataSource.source")),this.footerBtn.setAttribute("aria-haspopup","listbox"),this.footerBtn.setAttribute("aria-expanded","false"),this.footerLabel=document.createElement("span"),this.footerLabel.className="ml-ui-file-open-footer-label",this.footerChevron=document.createElement("span"),this.footerChevron.className="ml-ui-file-open-footer-chevron",this.footerChevron.setAttribute("aria-hidden","true"),this.footerChevron.textContent="▾",this.footerBtn.appendChild(this.footerLabel),this.footerBtn.appendChild(this.footerChevron),this.footerBtn.addEventListener("click",a=>{a.stopPropagation(),this.toggleMenu()}),r.appendChild(this.footerBtn),this.card.appendChild(r),this.menuEl=document.createElement("div"),this.menuEl.className="ml-ui-file-open-menu",this.menuEl.hidden=!0,this.menuEl.setAttribute("role","listbox"),this.card.appendChild(this.menuEl),this.onDocPointerDown=a=>{if(!this.menuOpen)return;const l=a.target;l instanceof Node&&(this.card.contains(l)||this.closeMenu())},document.addEventListener("pointerdown",this.onDocPointerDown),this.unsubTheme=Vo(()=>{this.options.theme||this.applyTheme()}),e.host.appendChild(this.root),this.bindManagerEvents(),this.refreshSourceButtons()}get element(){return this.root}refreshSourceButtons(){this.disposed||(this.bindManagerEvents(),this.applyTheme(),this.applyCardSize(),this.syncSourceChrome(),this.renderActiveView())}setTheme(e){this.disposed||(this.options.theme=e,this.applyTheme())}setCardSize(e){this.disposed||(this.options.cardSize={...this.options.cardSize,...e},this.applyCardSize())}dispose(){var e,t;this.disposed||(this.disposed=!0,(e=this.unsubManager)==null||e.call(this),this.unsubManager=null,(t=this.unsubTheme)==null||t.call(this),this.unsubTheme=null,this.onDocPointerDown&&(document.removeEventListener("pointerdown",this.onDocPointerDown),this.onDocPointerDown=null),this.root.remove())}applyTheme(){const e=this.options.theme!=null,t=this.options.theme??Oe(this.options.host);ot(t,this.root,{isolated:e})}applyCardSize(){const e=this.options.cardSize;this.card.style.width=Px(e==null?void 0:e.width,xL),this.card.style.height=Px(e==null?void 0:e.height,kL)}syncSourceChrome(){const e=this.resolveSourceOptions();new Set(e.map(o=>o.value)).has(this.activeView)||(this.activeView=Js,this.closeMenu());const i=e.find(o=>o.value===this.activeView)??e[0];this.footerLabel.textContent=(i==null?void 0:i.label)??"";const n=e.length>1;this.footerBtn.disabled=!n,this.footerBtn.classList.toggle("is-single",!n),this.footerChevron.hidden=!n,n||this.closeMenu(),this.menuEl.replaceChildren();for(const o of e){const r=document.createElement("button");r.type="button",r.className="ml-ui-file-open-menu-item",r.setAttribute("role","option"),r.setAttribute("aria-selected",o.value===this.activeView?"true":"false"),o.value===this.activeView&&r.classList.add("is-active"),r.textContent=o.label,r.addEventListener("click",a=>{a.stopPropagation(),this.selectSource(o.value)}),this.menuEl.appendChild(r)}}selectSource(e){this.activeView=e,this.closeMenu(),this.syncSourceChrome(),this.renderActiveView(),this.maybeAutoSignIn(e)}maybeAutoSignIn(e){if(e===Js||e===Su)return;const t=this.resolveSources().find(n=>n.id===e);if(t){t.requiresAuth&&t.getAuthState()==="signed-out"&&t.signIn().catch(()=>{}).finally(()=>this.refreshSourceButtons());return}const i=this.resolveExtraMenuItems().find(n=>n.sourceId===e&&n.action==="sign-in");i&&this.emit({kind:"data-source",item:i})}toggleMenu(){this.footerBtn.disabled||(this.menuOpen?this.closeMenu():this.openMenu())}openMenu(){this.menuOpen=!0,this.menuEl.hidden=!1,this.footerBtn.setAttribute("aria-expanded","true"),this.footerBtn.classList.add("is-open"),this.footerChevron.textContent="▴"}closeMenu(){this.menuOpen=!1,this.menuEl.hidden=!0,this.footerBtn.setAttribute("aria-expanded","false"),this.footerBtn.classList.remove("is-open"),this.footerChevron.textContent="▾"}resolveSourceOptions(){const e=[{value:Js,label:m.t("main.dataSource.local")}];this.options.showUrl!==!1&&e.push({value:Su,label:m.t("main.dataSource.url")});const t=new Set;for(const i of this.resolveMenuItems())t.has(i.sourceId)||(t.add(i.sourceId),e.push({value:i.sourceId,label:this.resolveSourceLabel(i.sourceId)}));return e}resolveSourceLabel(e){var n;const t=this.resolveSources().find(o=>o.id===e);if(t)return m.t(t.labelKey);const i=this.resolveExtraMenuItems().find(o=>o.sourceId===e);return(n=i==null?void 0:i.labelParams)!=null&&n.name?i.labelParams.name:e}renderActiveView(){if(this.contentEl.replaceChildren(),this.activeView===Js){this.contentEl.appendChild(this.dropzone);return}if(this.activeView===Su){this.contentEl.appendChild(this.urlRow),requestAnimationFrame(()=>this.urlInput.focus());return}this.renderSourceActions(this.activeView),this.contentEl.appendChild(this.sourceActionsEl)}canPickSource(e){const t=this.resolveSources().find(i=>i.id===e);return t?t.requiresAuth?t.getAuthState()==="signed-in":!0:this.resolveExtraMenuItems().some(i=>i.sourceId===e&&i.action==="pick")}buildPickMenuItem(e){const t=this.resolveSourceLabel(e),i=m.t("main.dataSource.openFrom");return{id:`${e}:pick`,sourceId:e,action:"pick",labelKey:"main.dataSource.openFrom",labelParams:{name:t},label:i.includes("{name}")?i.split("{name}").join(t):m.t("main.dataSource.selectFile")}}resolveAccountProfile(e){var r,a,l,c;const t=(a=(r=this.options).getAccountProfile)==null?void 0:a.call(r,e);if(t!=null&&t.displayName)return t;const i=this.resolveSources().find(d=>d.id===e);if(!i||i.getAuthState()!=="signed-in")return;const n=(l=i.getAccountProfile)==null?void 0:l.call(i);if(n!=null&&n.displayName)return n;const o=(c=i.getAccountLabel)==null?void 0:c.call(i);if(o)return{displayName:o}}initialsFromName(e){const t=e.trim().split(/\s+/).filter(Boolean);return t.length===0?"?":t.length===1?t[0].slice(0,2).toUpperCase():`${t[0][0]??""}${t[1][0]??""}`.toUpperCase()}renderSourceActions(e){this.sourceActionsEl.replaceChildren();const t=this.resolveAccountProfile(e);if(t){const o=document.createElement("div");o.className="ml-ui-file-open-account";const r=document.createElement("div");if(r.className="ml-ui-file-open-avatar",t.avatarUrl){const c=document.createElement("img");c.className="ml-ui-file-open-avatar-img",c.src=t.avatarUrl,c.alt="",c.referrerPolicy="no-referrer",r.appendChild(c)}else{const c=document.createElement("span");c.className="ml-ui-file-open-avatar-initials",c.textContent=this.initialsFromName(t.displayName),r.appendChild(c)}const a=document.createElement("div");a.className="ml-ui-file-open-account-text";const l=document.createElement("div");if(l.className="ml-ui-file-open-account-name",l.textContent=t.displayName,a.appendChild(l),t.email&&t.email!==t.displayName){const c=document.createElement("div");c.className="ml-ui-file-open-account-email",c.textContent=t.email,a.appendChild(c)}o.appendChild(r),o.appendChild(a),this.sourceActionsEl.appendChild(o)}const i=document.createElement("button");i.type="button",i.className="ml-ui-file-open-source-btn ml-ui-file-open-source-btn--primary",i.textContent=m.t("main.dataSource.selectFile");const n=this.canPickSource(e);i.disabled=!n,n||(i.title=m.t("main.dataSource.signInRequired")),i.addEventListener("click",()=>{this.canPickSource(e)&&this.emit({kind:"data-source",item:this.buildPickMenuItem(e)})}),this.sourceActionsEl.appendChild(i)}resolveMenuItems(){const e=this.resolveSources().filter(r=>r.id!==wa&&r.id!==iu),t=Sv(e),i=this.resolveExtraMenuItems(),n=new Set(t.map(r=>r.sourceId)),o=i.filter(r=>!n.has(r.sourceId));return[...t,...o]}resolveSources(){var e;return this.options.getSources?this.options.getSources():((e=k.tryGetInstance())==null?void 0:e.dataSourceManager.list())??[]}resolveExtraMenuItems(){const e=this.options.extraMenuItems;return e?typeof e=="function"?e():e:[]}bindManagerEvents(){var i;if(this.unsubManager)return;const e=(i=k.tryGetInstance())==null?void 0:i.dataSourceManager;if(!e)return;const t=()=>this.refreshSourceButtons();e.on("changed",t),e.on("auth-changed",t),this.unsubManager=()=>{e.off("changed",t),e.off("auth-changed",t)}}submitUrl(){const e=this.urlInput.value.trim();if(!e){this.urlInput.focus();return}this.emit({kind:"url",url:e})}onDrag(e,t){e.preventDefault(),e.stopPropagation(),this.dropzone.classList.toggle("is-dragover",t)}onDrop(e){var i,n;this.onDrag(e,!1);const t=(n=(i=e.dataTransfer)==null?void 0:i.files)==null?void 0:n[0];t&&this.isSupportedFileName(t.name)&&this.emitLocal(t)}isSupportedFileName(e){const t=e.toLowerCase();return _x.some(i=>t.endsWith(i))}emitLocal(e){this.emit({kind:"local",file:e})}emit(e){var t,i,n,o,r,a,l,c,d,h;switch((i=(t=this.options).onResult)==null||i.call(t,e),e.kind){case"local":(o=(n=this.options).onLocalFile)==null||o.call(n,e.file);break;case"url":(a=(r=this.options).onUrl)==null||a.call(r,e.url);break;case"data-source":(c=(l=this.options).onDataSourceAction)==null||c.call(l,e.item);break;case"new-drawing":(h=(d=this.options).onNewDrawing)==null||h.call(d);break}}createDivider(){const e=document.createElement("p");e.className="ml-ui-file-open-divider",e.setAttribute("aria-hidden","true");const t=document.createElement("span");return t.textContent=m.t("main.dataSource.or"),e.appendChild(t),e}static ensureStyles(){if(typeof document>"u"||document.getElementById(zn.styleId))return;const e=document.createElement("style");e.id=zn.styleId,e.textContent=`
2659
+ `,document.head.appendChild(e)}class OE{constructor(){this._center=new Ca,this._defaultStore=this._center,this._showDefaultUi=!0,this._isCustom=!1}install(e,t={}){var i;this._docManager=e,this._host=t.host,this._showDefaultUi=t.showDefaultUi!==!1,this._placement=t.placement,t.enableBridge!==!1?((i=this._bridge)==null||i.uninstall(),this._bridge=new Gv(e,()=>this.center),this._bridge.install()):this._center.setActiveSession(e.activeSessionId),!this._isCustom&&this._showDefaultUi&&this.mountDefaultUi()}get placement(){return this._placement}setPlacement(e){var t;this._placement=e,(t=this._defaultUi)==null||t.setPlacement(e)}get center(){return this._center}get isCustom(){return this._isCustom}setCenter(e){var t,i;if(e==null){this.restoreDefault();return}this._center!==e&&(this.disposeDefaultUi(),this._isCustom?(i=(t=this._center).dispose)==null||i.call(t):this._defaultStore.dispose(),this._center=e,this._isCustom=!0,this._docManager&&this._center.setActiveSession(this._docManager.activeSessionId))}restoreDefault(){var e,t;if(!this._isCustom){this._showDefaultUi&&!this._defaultUi&&this.mountDefaultUi();return}(t=(e=this._center).dispose)==null||t.call(e),this._defaultStore=new Ca,this._center=this._defaultStore,this._isCustom=!1,this._docManager&&this._center.setActiveSession(this._docManager.activeSessionId),this._showDefaultUi&&this.mountDefaultUi()}resolveHost(){var t,i;if(this._host)return this._host;const e=(i=(t=this._docManager)==null?void 0:t.curView)==null?void 0:i.container;return e||document.body}mountDefaultUi(){this.disposeDefaultUi(),!(typeof document>"u")&&(this._defaultUi=new Wv(this._center,this.resolveHost(),{placement:this._placement}))}disposeDefaultUi(){var e;(e=this._defaultUi)==null||e.dispose(),this._defaultUi=void 0}dispose(){var e,t,i;(e=this._bridge)==null||e.uninstall(),this._bridge=void 0,this.disposeDefaultUi(),(i=(t=this._center).dispose)==null||i.call(t),this._defaultStore=new Ca,this._center=this._defaultStore,this._isCustom=!1,this._docManager=void 0,this._host=void 0,this._showDefaultUi=!0,this._placement=void 0}}const Wi=new OE;function DE(){return Wi.center}function NE(s){Wi.setCenter(s)}function BE(){return Wi.placement}function FE(s){Wi.setPlacement(s??void 0)}function Xv(s,e){Wi.install(s,e)}function qv(){Wi.dispose()}function zE(s){var r;const e=s.tables.blockTable,t=e.getAt(p.AcDbBlockTableRecord.PAPER_SPACE_NAME_PREFIX);if(t)return t.objectId;const i=(r=s.objects)==null?void 0:r.layout;if(!(i!=null&&i.newIterator))return;const n=e.modelSpace.objectId;let o;for(const a of i.newIterator()){const l=a.blockTableRecordId;if(!l||l===n)continue;const c=e.getIdAt(l);if(!(!c||!p.AcDbBlockTableRecord.isPaperSapceName(c.name))){if(a.tabSelected)return l;o||(o=l)}}return o}function RE(s){const e=s.tables.blockTable.modelSpace.objectId;if(s.tilemode){s.currentSpaceId!==e&&(s.currentSpaceId=e);return}const t=zE(s);t&&t!==s.currentSpaceId&&(s.currentSpaceId=t)}const jE="https://cdn.jsdelivr.net/gh/mlightcad/cad-data",VE="templates/acadiso.dxf",GE={ARC:["A"],CIRCLE:["C"],ELLIPSE:["EL"],ERASE:["E"],DIMLINEAR:["DLI"],DIMALIGNED:["DAL","DIMALI"],DIMRADIUS:["DRA","DIMRAD"],DIMDIAMETER:["DDI","DIMDIA"],DIMANGULAR:["DAN","DIMANG"],DIMARC:["DAR"],DIMORDINATE:["DOR"],DIMCONTINUE:["DCO"],DIMBASELINE:["DBA"],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"],READINGMODE:["RM"]},HE="modern";class k{constructor(e={}){var c;this._sessions=[],this._nextSessionId=1,this._openFileProfiler=new ka,this._workersReady=null,this._nextOverlayId=1,this._presetFontsForOpenPromise=null,this._lastPresetFontsForOpen=[],this.events={documentToBeOpened:new p.AcCmEventManager,documentCreated:new p.AcCmEventManager,documentActivated:new p.AcCmEventManager,documentToBeActivated:new p.AcCmEventManager,documentToBeDestroyed:new p.AcCmEventManager,documentDestroyed:new p.AcCmEventManager,workersReady:new p.AcCmEventManager},this._baseUrl=e.baseUrl??jE,Gu(e.docsBaseUrl??ao),this._commandAliasOverrides=this.normalizeCommandAliasConfig(e.commandAliases),this._openDocumentDefaults=e.openDocumentDefaults,this._disableExport=e.disableExport===!0,e.useMainThreadDraw?D.AcTrMTextRenderer.getInstance().setRenderMode("main"):D.AcTrMTextRenderer.getInstance().setRenderMode("worker"),$.FontManager.instance.setDefaultFonts(HE),$.FontManager.instance.lazyFontLoading=!0,$.FontManager.instance.awaitFontsBeforeDraw=!0,D.AcTrMTextRenderer.getInstance().setLazyFontLoading(!0),D.AcTrMTextRenderer.getInstance().setAwaitFontsBeforeDraw(!0);const t=new ba,i=((c=e.container)==null?void 0:c.getBoundingClientRect())??{width:300,height:150},n=()=>{var d;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 f=(d=e.container)==null?void 0:d.getBoundingClientRect();return{width:Math.max(1,Math.floor((f==null?void 0:f.width)??i.width)),height:Math.max(1,Math.floor((f==null?void 0:f.height)??i.height))}}else return{width:e.width??i.width,height:e.height??i.height}},o=new Mn({container:e.container,calculateSizeCallback:n});this._mainView=o;const r=new Ea(o,t);this._activeSession=new ya(`doc-${this._nextSessionId++}`,r),this._sessions=[this._activeSession],Hn(this._activeSession.id),this._fontLoader=new dv,$.FontManager.instance.setFontLoader(this._fontLoader.fontLoader);const a=this.resolveFontsBaseUrl();this._fontLoader.baseUrl=a,$.FontManager.instance.baseUrl=a,D.AcTrMTextRenderer.getInstance().setFontUrl(a),this.installFontFileLoadTimeout(),p.acdbHostApplicationServices().workingDatabase=t.database,this._commandManager=new Me,this.registerCommands(),p.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(d=>{const h=d.name.toUpperCase();(h===p.AcDbSystemVariables.CANNOSCALE||h===p.AcDbSystemVariables.ANNOALLVISIBLE)&&this.regen()}),this._pluginManager=new av(this.context,this._commandManager),this._dataSourceManager=new xv,this._dataSourceManager.register(new hv),this._dataSourceManager.register(new kv);const l=e.busyIndicatorHost??o.container;if(this._busyIndicatorHost=l,this._openFileProgress=new Qd(l),this._openFileProgress.setSceneBusyGate(()=>this.openProgressView.isProcessingEntities),this._openFileProgress.setOnHidden(()=>this.onOpenProgressHidden()),this._busyIndicator=new X1(l),Pp({showMessage:(d,h,f)=>this.editor.showMessage(d,h,f),showBusyIndicator:d=>this.showBusyIndicator(d),hideBusyIndicator:()=>this.hideBusyIndicator(),withBusyIndicator:(d,h)=>this.withBusyIndicator(d,h)}),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(d=>{p.log.error("[AcApDocManager] Error loading plugins:",d)}),mv({enabled:e.builtinOpenFileDialog!==!1,getOpenDocumentDefaults:()=>this.resolveOpenDocumentDefaults()}),e.notificationCenter!==!1){const d=typeof e.notificationCenter=="object"?e.notificationCenter:{};Xv(this,{host:d.host,showDefaultUi:d.showDefaultUi!==!1,placement:d.placement,enableBridge:!0})}}static createInstance(e={}){return k._instance==null&&(k._instance=new k(e)),this._instance}static checkWebworkerReadiness(e){return vv(e)}static get instance(){if(!k._instance)throw new Error("AcApDocManager instance is not created yet!");return k._instance}static tryGetInstance(){return k._instance}async destroy(){var e,t;this._mainView.abortConversion(),(e=this._splitView)==null||e.abortConversion(),await this._pluginManager.unloadAllPlugins();for(const i of[...this._sessions])i.context.dispose(),i.doc.destroy(),i.viewState&&this.curView.disposeSessionState(i.viewState);this._sessions=[],(t=this._splitView)==null||t.dispose(),this._splitView=void 0,this._mainView.dispose(),yv(),qv(),D.AcTrMTextRenderer.resetInstance(),uE(),k._instance=void 0}get workersReady(){return this._workersReady}areWorkersReady(){return this._workersReady===!0?Promise.resolve(!0):(this._workersReadyCheckPromise||(this._workersReadyCheckPromise=vv(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()),Hn(t.id),p.acdbHostApplicationServices().workingDatabase=e.database,this._pluginManager.setContext(t.context),this.curView.bindDrawDatabase(e.database),this.setActiveLayout(),this.curView.syncDisplaySysVars(e.database),this.events.documentActivated.dispatch({doc:e,mode:e.openMode}),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 Mn({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,o=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),tl(i.id);const r=i.context.view;if(i.viewState?(r.disposeSessionState(i.viewState),i.viewState=void 0):r.clear(),this._sessions.splice(o,1),this.events.documentDestroyed.dispatch({doc:t,mode:t.openMode}),n){const a=this._sessions[Math.min(o,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 dataSourceManager(){return this._dataSourceManager}get drawStyleSessionAccessory(){return Vy(this._mainView)}get baseUrl(){return this._baseUrl}get disableExport(){return this._disableExport}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 getAvaiableFonts(){try{return await this._fontLoader.getAvaiableFonts()}catch{return Q.emit("failed-to-get-avaiable-fonts",{url:this._fontLoader.baseUrl}),[]}}async loadFonts(e){await this._fontLoader.load(e)}async loadDefaultFonts(e){e==null?await this._fontLoader.load([...$.FontManager.instance.getFontsToLoad()]):await this._fontLoader.load(e)}ensurePresetFontsForOpen(){if(this._presetFontsForOpenPromise)return this._presetFontsForOpenPromise;const e=[...$.FontManager.instance.getFontsToLoad()];if(this._lastPresetFontsForOpen=e,e.length===0)return this._presetFontsForOpenPromise=Promise.resolve(),this._presetFontsForOpenPromise;const t=D.AcTrMTextRenderer.getInstance(),i=t.getRenderMode()==="worker"?"worker":"main",n=3e4,o=i==="worker"?t.loadFonts(e,{scope:"all"}).then(()=>{}):$.FontManager.instance.requestFonts(e).then(()=>{});return this._presetFontsForOpenPromise=new Promise(r=>{const a=setTimeout(()=>{r()},n);o.then(()=>{clearTimeout(a),r()},()=>{clearTimeout(a),r()})}),this._presetFontsForOpenPromise}async awaitPresetFontsReady(){await this.ensurePresetFontsForOpen()}get lastPresetFontsForOpen(){return this._lastPresetFontsForOpen}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 o=await this.ensureOpenSession(n);this.beginOpenProgress(),this.onBeforeOpenDocument(i,!o);try{await this._openFileProgress.beginOpen(this.context.doc.database);const r=await this.context.doc.openDocument(e,t,i);return this.onAfterOpenDocument(r,i),!r&&o&&await this.closeFailedOpenSession(),r}catch(r){throw this._openFileProfiler.cancel(),o&&await this.closeFailedOpenSession(),r}}async loadOverlay(e,t,i={}){var l;const{targetView:n,...o}=i,r=new p.AcDbDatabase,a=(l=e.split(".").pop())==null?void 0:l.toLocaleLowerCase();return await Fd(r,async()=>{await r.read(t,{readOnly:!0,...o},a==="dwg"?p.AcDbFileType.DWG:p.AcDbFileType.DXF)}),this.registerOverlayDatabase(r,{targetView:n})}async registerOverlayDatabase(e,t){const i=(t==null?void 0:t.targetView)??this.curView,n=await i.addOverlayEntities(e),o=`overlay-${this._nextOverlayId++}`;return(this._sessions.find(a=>a.context.view===i)??this._activeSession).overlays.set(o,{db:e,layout:n}),i.isDirty=!0,o}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)}isReadingModeEnabled(e){return(e??this.curView).readingModeEnabled}setReadingMode(e,t){(t??this.curView).setReadingMode(e)}toggleReadingMode(e){(e??this.curView).toggleReadingMode()}setOverlayCompareDisplay(e,t,i){for(const n of this._sessions){const o=n.overlays.get(e);if(!o)continue;return(i??n.context.view??this.curView).setCompareDisplay(t,o.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}/`}${VE}`,n=this.setOptions({...e,mode:U.Write}),o=await this.ensureOpenSession();this.beginOpenProgress(),this.onBeforeOpenDocument(n,!o),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&&o&&await this.closeFailedOpenSession(),r}setOpenDocumentDefaults(e){this._openDocumentDefaults=e,fv({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()}installFontFileLoadTimeout(){const t=$.FontManager.instance.loader;if(!t||t.__cadFontLoadTimeout)return;const i=t.loadAsync.bind(t),n=3e4;t.loadAsync=o=>new Promise((r,a)=>{const l=setTimeout(()=>{a(new Error(`Font load timed out after ${n}ms`))},n);i(o).then(c=>{clearTimeout(l),r(c)},c=>{clearTimeout(l),a(c)})}),t.__cadFontLoadTimeout=!0}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,o,r)=>{const a=GE[n.toUpperCase()]??[];e.addCommand(Me.SYSTEMT_COMMAND_GROUP_NAME,n,o,r,this.resolveCommandAliases(n,a))};t("about","about",new Gw),t("arc","arc",new gg),t("cachefont","cachefont",new Us),t("circle","circle",new Sg),t("close","close",new qw),this._disableExport||(t("bmpout","bmpout",new Wy),t("cdxf","cdxf",new Ky),t("jpgout","jpgout",new Yy),t("pngout","pngout",new Zy)),t("entout","entout",new Jy),t("ellipse","ellipse",new sb),t("erase","erase",new Nw),t("hideobjects","hideobjects",new Bw),t("dimlinear","dimlinear",new Xg),t("dimaligned","dimaligned",new Og),t("dimradius","dimradius",new eb),t("dimdiameter","dimdiameter",new Yg),t("dimangular","dimangular",new Ng),t("dimarc","dimarc",new zg),t("dimordinate","dimordinate",new Jg),t("dimcontinue","dimcontinue",new Wg),t("dimbaseline","dimbaseline",new $g),pw(t,{view:this._mainView,commandManager:this._commandManager}),t("-hatch","-hatch",new Zr),t("imageattach","imageattach",new ob),t("-insert","-insert",new ab),t("xattach","xattach",new Fb),t("-layer","-layer",new dg),t("laycur","laycur",new ig),t("laydel","laydel",new tg),t("layfrz","layfrz",new Fr),t("layiso","layiso",new zr),t("laylck","laylck",new ng),t("layon","layon",new sg),t("layoff","layoff",new Rr),t("laythw","laythw",new rg),t("layuniso","layuniso",new ag),t("layulk","layulk",new lg),t("layerp","layerp",new og),t("layerclose","layerclose",new cg),t("line","line",new ji),t("mline","mline",new cb),t("mtext","mtext",new db),t("copy","copy",new ha),t("move","move",new zw),t("offset","offset",new Gs),t("rotate","rotate",new ma),t("log","log",new Hw),t("objectscale","objectscale",new Xw),t("open","open",new Zw),t("pan","pan",new rv),t("point","point",new ub),t("polygon","polygon",new Jr),t("pline","pline",new fb),t("qnew","qnew",new Jw),t("ray","ray",new gb),t("rectang","rectang",new Qr),t("regen","regen",new Qw),t("revcloud","revcloud",new ea),Dw(t,{view:this._mainView,commandManager:this._commandManager}),t("select","select",new ev),t("sketch","sketch",new sa),t("spline","spline",new Ob),t("switchbg","switchbg",new iv),t("readingmode","readingmode",new nv),t("unisolateobjects","unisolateobjects",new Vw),t("xline","xline",new zb),t("undo","undo",new sv),t("redo","redo",new ov),t("zoom","zoom",new yi),p.AcDbSysVarManager.instance().getAllDescriptors().forEach(n=>{e.addCommand(Me.SYSTEMT_COMMAND_GROUP_NAME,n.name,n.name,new tv,this.resolveCommandAliases(n.name,[]))})}normalizeCommandAliasConfig(e){const t=new Map;return e&&Object.entries(e).forEach(([i,n])=>{const o=i.trim().toUpperCase();if(!o)return;const r=Array.isArray(n)?n:[n],a=new Set;r.forEach(l=>{const c=l.trim().toUpperCase();c&&c!==o&&a.add(c)}),t.set(o,[...a])}),t}resolveCommandAliases(e,t){const i=e.trim().toUpperCase(),n=this._commandAliasOverrides.get(i);if(n)return[...n];const o=new Set;return t.forEach(r=>{const a=r.trim().toUpperCase();a&&a!==i&&o.add(a)}),[...o]}sendStringToExecute(e){this.executeCommandString(e).catch(t=>{const i=t instanceof Error?t.message:String(t);this.editor.showMessage(i,"error"),p.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=Xd(e);for(this.editor.clearScriptInputs(),this.editor.enqueueScriptInputs(t);this.editor.hasScriptInputs();){const i=this.consumeNextScriptCommandName();if(i==null)break;if(lv(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 '${U[n.mode]}' but document is in mode '${U[i]}'!`);await this._commandManager.cancelActive(),await this._commandManager.runActive(n,this.curView,async()=>{try{await n.trigger(this.context)}finally{t.preserveScriptInputs||this.editor.clearScriptInputs()}})}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=Xd(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&&(Si.instance.clearAll(),this.clearOverlays(),vl(),Jc(),yi.clearOriginalViews(),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.openProgressView.convertInvisibleLayers=(e==null?void 0:e.convertInvisibleLayers)===!0,this.openProgressView.cooperativeYield=(e==null?void 0:e.cooperativeYield)!==!1;const i=this.openProgressView.cadScene;i&&(i.skipSpatialIndex=(e==null?void 0:e.skipSpatialIndex)===!0),this.ensurePresetFontsForOpen(),this._openFileProfiler.begin(this.context.doc.database)}onAfterOpenDocument(e,t){const i=!e&&this.hasRecoverablePartialContent();if(e||i){const n=this._openingSession??this._activeSession,o=n.context.view;n.doc.destroy();const r=n.doc,a=r.database;RE(a),this.setActiveLayout(o,a),o.syncDisplaySysVars(a),this.events.documentActivated.dispatch({doc:r,mode:this.getDocumentEventMode(t)});const l=a.tables.blockTable.modelSpace.objectId,c=a.currentSpaceId!==l,d=p.acdbHostApplicationServices().layoutManager.getActiveLayout(a),h=d==null?void 0:d.limits,f=this.resolveOpenViewMode(t);o.setOpenViewMode(f);const y=(t==null?void 0:t.progressiveRendering)??!1;let g=!1;const b=()=>{y&&o.beginProgressiveOpenFit(),o.zoomToFitDrawing(),o.requestOpenLineworkFrame()};if(c&&f===_t.Saved){const w=d==null?void 0:d.extents,S=kr({limits:h,viewportsBox:Ff(a,a.currentSpaceId),layoutExtents:w&&!w.isEmpty()?{min:{x:w.min.x,y:w.min.y},max:{x:w.max.x,y:w.max.y}}:void 0});S?(o.zoomTo(S.box),g=!0):b()}else if(!c&&f===_t.Saved){const w=o.width/Math.max(o.height,1),S=a.tables.viewportTable.getActiveVportBox(w);S?(o.zoomTo(S),g=!0):b()}else b();o.markLayoutAsInitialized(a.currentSpaceId),g&&yi.rememberOriginalView(o,a.currentSpaceId),t!=null&&t.convertAllLayouts&&o.ensureEntitiesConvertedForExport({includeInvisibleLayers:t.convertInvisibleLayers!==!1,includeLayouts:!0}).catch(w=>{p.log.error("[AcApDocManager] convertAllLayouts export convert failed",w)}),this._openFileProfiler.markReadCompleteAndScheduleReport(o)}else this._openFileProfiler.cancel(),this.openProgressView.endProgressiveOpenFit(),this.regen()}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),this.stripDeprecatedWaitForTextGeometry(e),e.drawNoPlotLayers==null&&(e.drawNoPlotLayers=!1),e.progressiveRendering==null&&(e.progressiveRendering=!1)),e}stripDeprecatedWaitForTextGeometry(e){e.waitForTextGeometry!=null&&(delete e.waitForTextGeometry,console.warn("[AcApDocManager] Ignoring deprecated open option waitForTextGeometry; both stages of progressive rendering are controlled by progressiveRendering."))}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)??U.Read}resolveOpenViewMode(e){return(e==null?void 0:e.openViewMode)!=null?e.openViewMode:this.getDocumentEventMode(e)===U.Write?_t.Saved:_t.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)??wv.mtextRender),t.setDefaultFonts([...$.FontManager.instance.defaultFonts])}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&&p.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from config:`,t.loaded),t.failed.length>0&&p.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s):`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){p.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&&p.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from folder:`,t.loaded),t.failed.length>0&&p.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s) from folder:`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){p.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==="STYLE"&&t.subStageStatus==="END"){const o=this._sessions.find(a=>a.doc===e),r=(o==null?void 0:o.context.view)??this.curView;r&&r.startTextStyleFontPreload(e.database)}if(t.subStage!=="HEADER")return;const i=this._sessions.find(o=>o.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 ba,o=new Ea(t,n),r=new ya(`doc-${this._nextSessionId++}`,o);return this._sessions.push(r),this._activeSession=r,Hn(r.id),p.acdbHostApplicationServices().workingDatabase=n.database,this._pluginManager.setContext(o),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;Si.instance.clearAll(),this.clearOverlays(),vl(),Jc(),this.curView.clear(),e.context.dispose(),t.destroy(),tl(i);const n=new ba,o=new Ea(this.curView,n),r=new ya(`doc-${this._nextSessionId++}`,o);this._sessions=[r],this._activeSession=r,Hn(r.id),p.acdbHostApplicationServices().workingDatabase=n.database,this._pluginManager.setContext(o),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 UE=Object.freeze(Object.defineProperty({__proto__:null,AcApDocManager:k},Symbol.toStringTag,{value:"Module"}));class Wt{static isFontLoaded(e){return $.FontManager.instance.isFontLoaded(e)}static getFontType(e){return $.FontManager.instance.getFontType(e)}static getReplacementFontName(e){return $.FontManager.instance.findAndReplaceFont(e)}static getShxCodePoints(e){var o;const t=$.FontManager.instance.getFontByName(e,!1);if(!t||t.type!=="shx")return[];const i=t.data;return Object.keys(((o=i.content)==null?void 0:o.data)??{}).map(r=>Number(r)).filter(r=>Number.isFinite(r)).sort((r,a)=>r-a)}static getLoadedShxFontData(e){const t=$.FontManager.instance.getFontByName(e,!1);if(!(!t||t.type!=="shx"))return t.data}static createShxParserFont(e){return new $.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(o=>o.name.some(r=>r.trim().toLowerCase()===i))}static getCatalogFontType(e){var t;return(t=Wt.findFontInfoByName(e))==null?void 0:t.type}static async ensureDrawingFontLoaded(e){const t=k.instance;t&&(Wt.isFontLoaded(e)||await t.loadFonts([e]))}static async cacheFont(e,t,i,n){return $.FontManager.instance.cacheFont(e,t,i,n)}static async getCachedMeshFontProgram(e){const t=[e],i=Wt.findFontInfoByName(e);i!=null&&i.file&&t.push(i.file);for(const r of(i==null?void 0:i.name)??[])t.push(r);const n=Wt.getReplacementFontName(e);if(n&&n!==e){t.push(n);const r=Wt.findFontInfoByName(n);r!=null&&r.file&&t.push(r.file);for(const a of(r==null?void 0:r.name)??[])t.push(a)}const o=new Set;for(const r of t){const a=r.trim().toLowerCase();if(!a||o.has(a))continue;o.add(a);const l=await $.FontManager.instance.getCachedMeshFontProgram(r);if(l&&l.byteLength>0)return new Uint8Array(l)}}static async persistMeshFontProgram(e,t,i){await $.FontManager.instance.persistMeshFontProgram(e,t,i)}}function Jv(s){const e=[];try{const t=s.tables.textStyleTable;if(e.push(...t.fonts??[]),t.newIterator)for(const i of t.newIterator()){const n=i.textStyle;n!=null&&n.font&&e.push(n.font),n!=null&&n.bigFont&&e.push(n.bigFont),n!=null&&n.extendedFont&&e.push(n.extendedFont)}}catch{return[]}return Zs(e)}function Qv(s,e,t){const i=Zs([...s]);i.length===0&&(t!=null&&t.firstDefaultFont)&&i.push(t.firstDefaultFont);const n=new Set(i.map($i)),o=new Set(e.map($i)),r=Zs(e.filter(l=>!n.has($i(l))));let a=Zs(i.filter(l=>o.has($i(l))));if(a.length===0&&(t!=null&&t.firstDefaultFont)){const l=$i(t.firstDefaultFont);l&&n.has(l)&&(a=[t.firstDefaultFont])}return a.length>3&&(a=a.slice(0,3)),{critical:i,workerWarm:a,background:r}}function Zs(s){const e=new Set,t=[];for(const i of s){if(!i)continue;const n=$i(i);!n||e.has(n)||(e.add(n),t.push(i))}return t}function $i(s){if(s==null)return"";let e=String(s).trim();if(!e)return"";const t=e.lastIndexOf(".");return t>0&&(t===e.length-4||t===e.length-5)&&(e=e.substring(0,t)),e.toLowerCase()}const lu=13,cu=14,du=1,WE=cu*2+du*2,ex=.5,tx=.5;let In;function $E(){if(In!==void 0)return In;if(typeof document>"u")return In=null,null;try{In=document.createElement("canvas").getContext("2d")}catch{In=null}return In}function ix(s){return(s==null?void 0:s.padXEm)??cu/lu}function nx(s){const e=(s==null?void 0:s.borderEm)??du/lu;return e>0?e:0}function uu(s,e){return s>0?2*(ix(e)+nx(e))*s:0}function sx(s,e,t){const i=uu(e,t);if(!(e>0))return i;const n=$E();if(!n)return s.length*e*.6+i;const o=(t==null?void 0:t.fontWeight)??"500",r=(t==null?void 0:t.fontFamily)??"sans-serif";return n.font=`${o} ${e}px ${r}`,n.measureText(s).width+i}function ox(s,e,t,i){if(!(e>0)||!(t>0))return e;const n=(i==null?void 0:i.maxLineFraction)??ex,o=t*n,r=sx(s,e,i);if(r<=o)return e;if(!(o>0))return 1;const l=Math.max(0,r-uu(e,i))/e,c=2*(ix(i)+nx(i)),d=l+c;return d>0?Math.max(1,o/d):e}function xt(s,e,t,i){return e.textHeightMode==="custom"?e.fontSize:ox(s,e.fontSize,t,i)}function Ci(s,e,t){const i=s(e),n=s(t);return Math.hypot(n.x-i.x,n.y-i.y)}function Aa(s,e,t){return!(s>0)||!(e>0)||!(t>0)||t>=e?s:Math.max(1,s*(t/e))}function hu(s,e,t,i){return Math.min(Ci(s,e,t),Ci(s,e,i))*tx}function _a(s,e,t,i){if(!(t>0)||!(i>0))return 0;const n=s(e),o=s({x:e.x+t,y:e.y});return Math.hypot(o.x-n.x,o.y-n.y)/t*i}function KE(s,e,t){const i=t.x-e.x,n=t.y-e.y,o=i*i+n*n;if(!(o>0))return Math.hypot(s.x-e.x,s.y-e.y);let r=((s.x-e.x)*i+(s.y-e.y)*n)/o;return r=Math.max(0,Math.min(1,r)),Math.hypot(s.x-(e.x+r*i),s.y-(e.y+r*n))}function pu(s,e){const t=e.length;if(t<3)return 0;let i=1/0;for(let l=0;l<t;l++){const c=e[l],d=e[(l+1)%t];i=Math.min(i,Ci(s,c,d))}let n=0,o=0;for(const l of e)n+=l.x,o+=l.y;n/=t,o/=t;const r=s({x:n,y:o});let a=1/0;for(let l=0;l<t;l++){const c=s(e[l]),d=s(e[(l+1)%t]);a=Math.min(a,KE(r,c,d))}return Math.min(i,2*a)}const rx=s=>new p.AcGeBox3d(s.min,s.max),ax=s=>new p.AcGeBox2d(s.min,s.max),lx=s=>new V.Box3(s.min,s.max),cx=s=>new p.AcGeBox2d(s.min,s.max),dx=s=>new V.Box2(s.min,s.max),ux=s=>new p.AcGeBox2d(s.min,s.max),hx=s=>{const e=new V.Box3;return e.min.set(s.min.x,s.min.y,0),e.max.set(s.max.x,s.max.y,0),e},mu={threeBo2dToGeBox2d:cx,geBox2dToThreeBox2d:dx,threeBox3dToGeBox3d:rx,geBox3dToThreeBox3d:lx,goBox3dToGeBox2d:ax,threeBox3dToGeBox2d:ux,geBox2dToThreeBox3d:hx};function px(s,e){if(!e||s.length<2)return s;let t=-1,i=-1;for(let r=0;r<s.length&&(s[r].ownerId===e?t<0&&(t=r):i<0&&(i=r),!(t>=0&&i>=0));r++);if(t<0||i<0||t<i)return s;const n=[],o=[];for(let r=0;r<s.length;r++){const a=s[r];a.ownerId===e?n.push(a):o.push(a)}return n.concat(o)}function YE(s,e){return{pending:px(s,e),cursor:0,activeOwnerId:e}}function ZE(s,e,t){if(e.length===0&&t===s.activeOwnerId)return s;const i=s.cursor===0?s.pending:s.pending.slice(s.cursor);if(t!==s.activeOwnerId)return{pending:px(e.length>0?e.concat(i):i,t),cursor:0,activeOwnerId:t};let n=!1;const o=[],r=[];for(let a=0;a<e.length;a++)t&&e[a].ownerId===t?(n=!0,o.push(e[a])):r.push(e[a]);if(n)return{pending:o.concat(i,r),cursor:0,activeOwnerId:t};for(let a=0;a<r.length;a++)s.pending.push(r[a]);return s}function XE(s){const{pending:e,cursor:t,activeOwnerId:i}=s;if(!i)return!1;for(let n=t;n<e.length;n++)if(e[n].ownerId===i)return!0;return!1}function qE(s){const{tookMs:e,budgetMs:t,maxSlice:i,activeLayoutPending:n}=s,o=Math.max(1,s.slice),r=n?2:4;return e<t/2?Math.min(o*r,i):e>t*2?Math.max(1,o>>1):o}class JE{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:on.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 p.AcDbBlockReference}collectMissingEntities(e,t,i){const n=[],o=e.newIterator();for(const r of o)i(r)&&(t(r.objectId)||n.push(r));return n}}var Pa=(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))(Pa||{});class QE extends V.Object3D{constructor(e,t,i=150,n=2){super(),this.camera=e,this.renderer=t,this.gizmoCamera=new V.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 V.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,o=-((t-i.min.y)/this.gizmoDim)*2+1;return{x:n,y:o}}calculateViewportPos(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,o=this.gizmoDim;let r=t-o,a=i-o;switch(n){case 0:r=0,a=0;break;case 1:r=0;break;case 4:a=0;break}return{x:r,y:a}}calculateViewportBbox(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,o=this.gizmoDim,r=new V.Box2(new V.Vector2(t-o,0),new V.Vector2(t,o));switch(n){case 0:r.set(new V.Vector2(0,i-o),new V.Vector2(o,i));break;case 1:r.set(new V.Vector2(0,0),new V.Vector2(o,o));break;case 4:r.set(new V.Vector2(t-o,i-o),new V.Vector2(t,i));break}return r}}function eL(s,e){const t=e.font||"Helvetica",i=e.fontSize||30,n=e.width||200,o=e.height||200,r=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=o;const c=l.getContext("2d");if(c){c.font=`bold ${i}px ${t}`,c.fillStyle=`rgba(${r})`,c.fillRect(0,0,n,o);const f=c.measureText(s).width;c.fillStyle=`rgba(${a})`,c.fillText(s,n/2-f/2,o/2+i/2-2)}const d=new V.Texture(l);return d.minFilter=V.LinearFilter,d.needsUpdate=!0,d}function fu(s){const e=eL(s,{fontSize:100,font:"Arial Narrow, sans-serif",color:[255,255,255,1],bgColor:[0,0,0,0]}),t=new V.SpriteMaterial({map:e,transparent:!0});return new V.Sprite(t)}Pa.RIGHT_TOP;const tL={pos:Pa.LEFT_BOTTOM,size:100,hasZAxis:!0};class iL extends QE{constructor(e,t,i){const n={...tL,...i};super(e,t,n.size,i.pos),this.hasZAxis=n.hasZAxis;const o=[0,0,0,2,0,0,0,0,0,0,2,0],r=[1,0,0,1,.6,0,0,1,0,.6,1,0];this.hasZAxis&&(o.push(0,0,0,0,0,2),r.push(0,0,1,0,.6,1));const a=new V.BufferGeometry;a.setAttribute("position",new V.Float32BufferAttribute(o,3)),a.setAttribute("color",new V.Float32BufferAttribute(r,3));const l=new V.LineBasicMaterial({vertexColors:!0,toneMapped:!1});this.axes=new V.LineSegments(a,l),this.axes.position.set(-1,-1,-1),this.add(this.axes),this.xText=fu("X"),this.xText.position.set(1.5,-1,-1),this.add(this.xText),this.yText=fu("Y"),this.yText.position.set(-1,1.5,-1),this.add(this.yText),this.hasZAxis&&(this.zText=fu("Z"),this.zText.position.set(-1,-1,1.5),this.add(this.zText))}setLineColors(e,t){const i=new V.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 nL extends D.AcTrBaseView{constructor(e,t,i,n){super(e,i,n),this._layoutBtrId=t,this._mode=qe.SELECTION,this._axesGizmo=this.createAxesGizmo(),this._viewportViews=new Map,this._overlayViewport=new D.AcTrOverlayViewport(e)}get layoutBtrId(){return this._layoutBtrId}get mode(){return this._mode}set mode(e){e==qe.SELECTION?this._cameraControls.mouseButtons={MIDDLE:V.MOUSE.PAN}:e==qe.PAN&&(this._cameraControls.mouseButtons={LEFT:V.MOUSE.PAN}),this._cameraControls.update(),this._mode=e}get viewportCount(){return this._viewportViews.size}get viewportViews(){return this._viewportViews.values()}get overlayViewport(){return this._overlayViewport}get internalCamera(){return this._camera.internalCamera}get viewportsBoundingBox(){if(this._viewportViews.size===0)return;const e=new p.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),this.drawOverlay(e),(n=this._axesGizmo)==null||n.update(),t}createAxesGizmo(){return new iL(this._camera.internalCamera,this._renderer.internalRenderer,{hasZAxis:!1,pos:Pa.LEFT_BOTTOM})}drawViewports(e){if(this._viewportViews.size>0){const t=this._renderer.autoClear;this._renderer.autoClear=!1;const i=new V.Vector4;this._renderer.getViewport(i),this._renderer.clearDepth();const n=e.visible;e.visible=!0,this._viewportViews.forEach(o=>{o.render(e)}),e.visible=n,this._renderer.setViewport(i.x,i.y,i.z,i.w),this._renderer.autoClear=t}}drawOverlay(e){const t=this._overlayViewport;if(!t.visible)return;t.render(e.internalScene,this._height);const i=e.modelSpaceLayout;!i||this._viewportViews.size===0||this.drawOverlayViewports(i.internalObject,t)}drawOverlayViewports(e,t){const i=t.screenRect,n=t.viewBox,o=e.visible;e.visible=!0,this._viewportViews.forEach(r=>{const a=D.acTrWcsBoxToCssRect(r.viewport.box,n,i),l=D.acTrIntersectCssRects(a,i);if(!l)return;const c=D.acTrCssRectToWcsBox(l,n,i),d=new p.AcGeBox2d;d.expandByPoint(r.paperPointToModel({x:c.minX,y:c.minY})),d.expandByPoint(r.paperPointToModel({x:c.maxX,y:c.minY})),d.expandByPoint(r.paperPointToModel({x:c.maxX,y:c.maxY})),d.expandByPoint(r.paperPointToModel({x:c.minX,y:c.maxY})),!d.isEmpty()&&r.withFrozenLayersHidden(e,()=>{t.renderNested(e,d,l,l,this._height,r.viewport.viewTwistAngle)})}),e.visible=o}}class yu{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 sL(s,e){return[...s].sort((t,i)=>oL(t,i,e))}function oL(s,e,t){const i=mx(s)-mx(e);if(Math.abs(i)>Number.EPSILON)return i;const n=fx(t,s)-fx(t,e);return Math.abs(n)>Number.EPSILON?n:0}function mx(s){return Math.max(s.maxX-s.minX,0)*Math.max(s.maxY-s.minY,0)}function fx(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 ai=class ai{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)}frameProgrammatically(e){this.userAdjusted||this.applyZoom(e)}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>=ai.SMALL_ENTITY_THRESHOLD||this.convertedCount>=ai.SMALL_ENTITY_THRESHOLD)&&(this.incrementalEnabled=!0)}maybeIncrementalFit(e){if(!this.active||!this.incrementalEnabled||this.userAdjusted)return;const t=performance.now();if(t-this.lastZoomAt<ai.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*ai.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 p.AcGeVector2d;return e.getSize(t),Math.abs(t.x)*Math.abs(t.y)}snapshotFitBox(e){return new p.AcGeBox2d({x:e.min.x,y:e.min.y},{x:e.max.x,y:e.max.y})}};ai.SMALL_ENTITY_THRESHOLD=500,ai.BBOX_GROWTH_RATIO=1.5,ai.FIT_INTERVAL_MS=2500;let gu=ai;const rL=1e3;function aL(s,e,t){return s||e>0?!1:t==null?!0:t>=rL}const bu={background:p.ACGI_MODEL_SPACE_BACKGROUND},de=class de extends Cf{constructor(e=bu){const t={...bu,...e},i=t.container??document.createElement("div");t.container=i,i.style.overflow="hidden",i.hasAttribute("tabindex")||(i.tabIndex=-1);const n=new V.WebGLRenderer({antialias:!0,alpha:!0});i.appendChild(n.domElement),n.domElement.style.display="block",n.domElement.style.maxWidth="100%",n.domElement.style.maxHeight="100%";const o=wm(n.domElement,i);super(n.domElement,i),this._rafId=null,this._loadingLayouts=new Set,this._initializedLayouts=new Set,this._externallyFramedLayouts=new Set,this._openViewMode=_t.Extents,this._convertingLayers=new Set,this._claimedConvertObjectIds=new Set,this._entityConvertGeneration=new Map,this._progressiveRendering=!1,this._convertInvisibleLayers=!1,this._cooperativeYield=!0,this._convertQueue=[],this._viewportRepairOwnerIds=new Set,this._convertDrainPromise=null,this._convertEpoch=0,this._transientDrawGeneration=new Map,this._transientSkipMeshGlyphDepth=0,this._lastProgressivePaintAt=0,this._progressivePaintUrgent=!1,this._progressiveInputPauseUntil=0,this._progressivePaintCount=0,this._progressiveYieldCount=0,this._openLineworkFramePending=!1,this._openLineworkFrameTimer=null,this._pendingGeometryJobs=0,this._deferredGeometryQueue=[],this._deferredGeometryActive=0,this._fontLoadedRedrawTimer=null,this._fontLoadedRedrawEpoch=0,this._entityProcessingIdleAt=0,this._textStyleFontPreloadEpoch=-1,this._textStyleFontPreloadPromise=null,this._viewDomAbort=new AbortController,this._viewDisposed=!1,this._readingMode=new Wu({getCurrentBackgroundColor:()=>this._renderer.currentBackgroundColor,applyViewClearColor:A=>this.applyViewClearColor(A),setCompareDisplay:A=>this.setCompareDisplay(A),markDirty:()=>{this._isDirty=!0}}),this._deferredFontsReady=null,this._convertPhaseMs={finishGeometry:0,finishGeometryAsyncDraw:0,finishGeometryQueueWait:0,handleGroup:0,addEntity:0,awaitFonts:0,glyphEntityCount:0,mtextCount:0,shapeCount:0,sharedGlyphDrawCount:0},this._fontPreloadDiag=null,this.animate=()=>{var G;this._rafId=requestAnimationFrame(this.animate),this.events.renderFrame.dispatch({render:this._renderer,camera:this.internalCamera});const A=this._numOfEntitiesToProcess>0,O=A||this._pendingGeometryJobs>0,P=!this._progressiveRendering&&!this._cooperativeYield&&O;if(!this._isDirty&&!this._htmlDirty&&!O||P||!this._isDirty&&!this._htmlDirty)return;const E=this.shouldCountMidOpenPaint(A,O);if(this._isDirty&&!this._progressivePaintUrgent&&E){const Y=this._progressiveRendering?de.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS:de.NON_PROGRESSIVE_OPEN_PAINT_INTERVAL_MS;if(performance.now()-this._lastProgressivePaintAt<Y)return}let j=!1;this._isDirty&&(E&&(this._progressivePaintCount++,this._lastProgressivePaintAt=performance.now(),this._progressivePaintUrgent=!1),j=this._layoutViewManager.render(this._scene)),this.internalCamera&&(this._isDirty||this._htmlDirty)&&this._css2dRenderer.render(this._scene.internalScene,this.internalCamera),(G=this._stats)==null||G.update(),this._isDirty=j,this._htmlDirty=!1},this._meshGlyphFlushTimer=null,this._disposeCanvasTouchCallout=o;const r=()=>this.noteProgressiveUserInput(),a=()=>{r(),this.focusViewerForShortcuts()},l=()=>{r(),this.focusViewerForShortcuts()};n.domElement.addEventListener("pointerdown",a,{capture:!0}),n.domElement.addEventListener("wheel",l,{capture:!0,passive:!0}),this._disposeProgressiveInputWatch=()=>{n.domElement.removeEventListener("pointerdown",a,{capture:!0}),n.domElement.removeEventListener("wheel",l,{capture:!0})},this._gripManager=new nm(this),this._keyHandler=new No(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),D.setAcTrDrawOrderZAllocator(()=>this._renderer.allocateDrawOrderZ());const c=le.instance.fontMapping;this._renderer.setFontMapping(c),this._onFontNotFound=A=>{Q.emit("font-not-found",{fontName:A.fontName,count:A.count??0})},this._onFontLoaded=A=>{Q.emit("missed-data-changed",{}),this.scheduleGlyphRedrawAfterFontLoad(A==null?void 0:A.fontName)},this._renderer.events.fontNotFound.addEventListener(this._onFontNotFound),this._renderer.events.fontLoaded.addEventListener(this._onFontLoaded),this._scene=this.createScene(),this._layerAppearance=new Gl(this._scene,this._renderer),this._inheritedLayerMaterialMapper=new yp(A=>this._layerAppearance.getEffectiveLayerTraits(A),this._renderer),this.backgroundColor=t.background??p.ACGI_MODEL_SPACE_BACKGROUND,this._stats=this.createStats(le.instance.isShowStats&&(k.tryGetInstance()==null||this.isActiveManagedView()));const d=p.AcDbSysVarManager.instance(),h=p.AcDbSystemVariables.MODELBKCOLOR.toLowerCase(),f=p.AcDbSystemVariables.PAPERBKCOLOR.toLowerCase();this._onSysVarChanged=A=>{const O=A.name.toLowerCase();if(O===h||O===f){const P=A.database;if(!P)return;const E=this.isModelSpaceLayout(P);if(!(O===h&&E||O===f&&!E))return;this.applyCanvasBackground(Mo(P,E))}},d.events.sysVarChanged.addEventListener(this._onSysVarChanged),this._onSettingsModified=A=>{A.key=="isShowStats"&&this.toggleStatsVisibility(this._stats,A.value)},le.instance.events.modified.addEventListener(this._onSettingsModified);let y=null,g=null,b=null;const w=()=>!this.editor.isActive&&!qt.getActiveInputBox()&&!If()&&!this._gripManager.isDragging,S=()=>this.mode===qe.SELECTION&&w(),x=()=>w()&&Ve().canIdleTouchBox(this.mode),_=()=>{b==null||b.remove(),b=null},C=()=>{y=null,g=null,_()},T=(A,O)=>{g=this.viewportToCanvas({x:A,y:O}),y=this.screenToWorld(g),_(),b=document.createElement("div"),b.className="ml-jig-preview-rect",this.container.appendChild(b)},L=(A,O,P="replace")=>{if(!y||!b||!g)return;const E=this.viewportToCanvas({x:A,y:O}),I=this.screenToWorld(E),j=this.worldToScreen(y),G=this.worldToScreen(I),Y=Math.min(j.x,G.x),ee=Math.min(j.y,G.y),Z=Math.abs(j.x-G.x),re=Math.abs(j.y-G.y),Se=this.getSelectionMode(g,E),Ke=this.getSelectionPreviewStyle(Se,P);Object.assign(b.style,{left:`${Y}px`,top:`${ee}px`,width:`${Z}px`,height:`${re}px`,borderStyle:Ke.borderStyle,background:Ke.background}),b.style.setProperty("--line-color",Ke.lineColor)},N=(A,O,P,E)=>{if(!y||!g)return;const I=this.viewportToCanvas({x:A,y:O}),j=this.screenToWorld(I);if(_(),E)if(Yh(this,I.x,I.y,P))P==="replace"&&this.selectionSet.clear();else if(this.entitySelectionEnabled){const G=this.pick(j);G.length>0?(P==="replace"&&this.htmlTransientManager.deselectAll(),this.applySelection([G[0].id],P)):P==="replace"&&this.selectionSet.clear()}else P==="replace"&&this.selectionSet.clear();else{const G=new p.AcGeBox2d().expandByPoint(y).expandByPoint(j),Y=this.getSelectionMode(g,I);this.entitySelectionEnabled&&this.selectByBoxWithMode(G,Y,P),Zh(this,G,Y,P)}y=null,g=null},B=this._viewDomAbort.signal;this.canvas.addEventListener("mousedown",A=>{A.button===0&&S()&&(yt(A)||He()||T(A.clientX,A.clientY))},{signal:B}),this.canvas.addEventListener("mousemove",A=>{!y||!b||!g||yt(A)||He()||L(A.clientX,A.clientY,this.getPointerSelectionAction(A))},{signal:B}),this.canvas.addEventListener("mouseup",A=>{if(this._gripManager.isDragging){C();return}if(!y||!g||yt(A)||He())return;const O=this.viewportToCanvas({x:A.clientX,y:A.clientY}),P=this.getPointerSelectionAction(A);N(A.clientX,A.clientY,P,this.isSelectionClick(g,O))},{signal:B}),this._disposeMobileBoxGesture=cr({element:this.canvas,shouldStart:()=>x(),setNavigationEnabled:A=>{this.setNavigationEnabled(A)},onActivate:(A,O)=>{T(A,O),L(A,O)},onMove:(A,O)=>{L(A,O)},onBoxEnd:(A,O,P)=>{N(A,O,"replace",!P)},onTap:(A,O)=>{g=this.viewportToCanvas({x:A,y:O}),y=this.screenToWorld(g),N(A,O,"replace",!0)},onAbort:()=>{C()}}),this.canvas.addEventListener("dblclick",A=>{A.button===0&&S()&&this.entitySelectionEnabled&&k.instance.curDocument.openMode===U.Write&&this.openPickedEntityEditor(A)},{signal:B}),document.addEventListener("keydown",A=>{this.isActiveManagedView()&&this.isShortcutEventInsideViewer(A)&&this._keyHandler.handleKeyDown(A)},{signal:B}),this._onLayoutSwitched=A=>{var j,G;if(!this.isActiveManagedView())return;const O=A.layout.database,P=(G=(j=k._instance)==null?void 0:j.curDocument)==null?void 0:G.database;if(O&&P&&O!==P)return;const E=A.layout.blockTableRecordId,I=!this._initializedLayouts.has(E);this._initializedLayouts.add(E),this.activeLayoutBtrId=E,this.createLayoutViewIfNeeded(E),this.loadLayoutEntitiesIfNeeded(E),this.refreshCanvasBackgroundForActiveLayout(),this._isDirty=!0,I&&this.applyInitialZoom(E,A.layout)},p.acdbHostApplicationServices().layoutManager.events.layoutSwitched.addEventListener(this._onLayoutSwitched),this._css2dRenderer=new jx.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=String(Tp),this._css2dRenderer.domElement.style.maxWidth="100%",this._css2dRenderer.domElement.style.maxHeight="100%",i.appendChild(this._css2dRenderer.domElement),this._missedImages=new Map,this._layoutViewManager=new yu,this._progressiveOpenFit=new gu((A,O)=>{this.activeLayoutView.zoomTo(A,O??1.1),this._isDirty=!0}),this._entityDisplay=new JE(A=>this.resolveLayerInfo(A)),this.initialize(),this.onWindowResize(),this._isDirty=!0,this._htmlDirty=!1,this.startAnimationLoop(),this._numOfEntitiesToProcess=0,this.resetDeferredGeometryQueue()}ensureDeferredFontsReady(){if(!this._deferredFontsReady){const e=performance.now(),t=Promise.all([this.awaitPresetFontsReadySafe(),this.awaitTextStyleFontsReady()]).then(()=>{},()=>{});this._deferredFontsReady=t.then(()=>{this._convertPhaseMs.awaitFonts+=performance.now()-e})}return this._deferredFontsReady}async awaitPresetFontsReadySafe(){const e=k;e._instance&&await e._instance.awaitPresetFontsReady()}takeConvertPhaseTimings(){const e={...this._convertPhaseMs,fontPreload:this._fontPreloadDiag?{...this._fontPreloadDiag}:void 0};return this._convertPhaseMs={finishGeometry:0,finishGeometryAsyncDraw:0,finishGeometryQueueWait:0,handleGroup:0,addEntity:0,awaitFonts:0,glyphEntityCount:0,mtextCount:0,shapeCount:0,sharedGlyphDrawCount:0},this._fontPreloadDiag=null,e}getPointerSelectionAction(e){return Sf(e)}initialize(){this.setCursor(Ti.Crosshair),this._onCommandWillStartHitTest=()=>{this.htmlTransientManager.setHitTestEnabled(!1)},this._onCommandEndedHitTest=()=>{this.htmlTransientManager.setHitTestEnabled(!0)},this.editor.events.commandWillStart.addEventListener(this._onCommandWillStartHitTest),this.editor.events.commandEnded.addEventListener(this._onCommandEndedHitTest)}get mode(){const e=this.activeLayoutView;return e?e.mode:qe.SELECTION}set mode(e){this.activeLayoutView.mode=e}setNavigationEnabled(e){const t=this.activeLayoutView;t&&(t.enabled=e)}setSnapLoupe(e){var i;const t=(i=this.activeLayoutView)==null?void 0:i.overlayViewport;if(t){if(!e){t.visible=!1,this._isDirty=!0;return}t.setScreenRect(e.x,e.y,e.size,e.size),t.setViewBox(e.viewBox),t.visible=!0,this._isDirty=!0}}get renderer(){return this._renderer}get gripManager(){return this._gripManager}get isDirty(){return this._isDirty}get isProcessingEntities(){return this._numOfEntitiesToProcess>0||this._pendingGeometryJobs>0}get isConvertingEntities(){return this._numOfEntitiesToProcess>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 convertInvisibleLayers(){return this._convertInvisibleLayers}set convertInvisibleLayers(e){this._convertInvisibleLayers=e}get cooperativeYield(){return this._cooperativeYield}set cooperativeYield(e){this._cooperativeYield=e}get progressiveOpenStats(){return{paintCount:this._progressivePaintCount,yieldCount:this._progressiveYieldCount}}resetProgressiveOpenStats(){this._progressivePaintCount=0,this._progressiveYieldCount=0,this._lastProgressivePaintAt=0,this._progressivePaintUrgent=!1,this._progressiveInputPauseUntil=0}isProgressiveGesturePauseActive(){return performance.now()<this._progressiveInputPauseUntil}isProgressiveDiscreteInputPending(){var t;const e=navigator.scheduling;return((t=e==null?void 0:e.isInputPending)==null?void 0:t.call(e))===!0}noteProgressiveUserInput(){!this._progressiveRendering||this._numOfEntitiesToProcess<=0||(this._progressivePaintUrgent=!0,this._isDirty=!0,this._progressiveInputPauseUntil=performance.now()+de.PROGRESSIVE_INPUT_PAUSE_MS)}async progressiveYieldForInput(e,t){if(this.isProgressiveGesturePauseActive()){for(await t();performance.now()<this._progressiveInputPauseUntil;)await new Promise(n=>setTimeout(n,16));this._progressiveYieldCount++;return}if(this.isProgressiveDiscreteInputPending()){await t(),this._progressiveYieldCount++;return}if(!e)return;await e.maybeYield(t)&&this._progressiveYieldCount++}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(o=>({name:o.name,pathName:o.pathName,isOverlay:o.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){if(this._renderer.currentBackgroundColor=e,this._layerAppearance.refreshTextMaterialsInObjectTree(this._scene.internalScene),this._scene.repaintForegroundMaterials(p.acgiForegroundColorForBackground(e)),this._scene.repaintBackgroundMaterials(e),this.resyncForegroundLayersForBackground(),this._readingMode.isEnabled){this._readingMode.noteLayoutBackground(e),this.applyViewClearColor($a);return}this.applyViewClearColor(e)}applyViewClearColor(e){this._renderer.setClearColor(e),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?cp(e):this.activeLayoutBtrId===this.modelSpaceBtrId}bindDrawDatabase(e){this._renderer.context.database=e}syncDisplaySysVars(e){this.bindDrawDatabase(e),this.applyCanvasBackground(Mo(e,this.isModelSpaceLayout(e))),this._readingMode.reapplyIfEnabled()}get readingModeEnabled(){return this._readingMode.isEnabled}toggleReadingMode(){this._readingMode.toggle()}setReadingMode(e){this._readingMode.setEnabled(e)}async addOverlayEntities(e){const t=new Ap;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 o of n.newIterator())if(!(o instanceof p.AcDbViewport))try{const r=this.drawEntity(o,!1);if(!r)continue;r.objectId=o.objectId,r.ownerId=o.ownerId,r.layerName=o.layer,r.visible=o.visibility!==!1,r instanceof D.AcTrGroup&&r.isOnTheSameLayer&&(r.userData.insertLayerName=r.layerName),await this.finishEntityGeometry(r,!1),r instanceof D.AcTrGroup&&r.isOnTheSameLayer&&this._inheritedLayerMaterialMapper.remap(r.children,"0",r.layerName),t.addEntity(r),r.dispose()}catch(r){p.log.error(`[AcTrView2d] Failed to convert overlay entity ${o.objectId} (${o.type}):`,r)}}finally{this._renderer.context.database=i}return t}refreshCanvasBackgroundForActiveLayout(){var n,o;const t=(o=(n=k._instance)==null?void 0:n.curDocument)==null?void 0:o.database;if(!t)return;const i=this.activeLayoutBtrId===this.modelSpaceBtrId;this.applyCanvasBackground(Mo(t,i))}get modelSpaceBtrId(){return this._scene.modelSpaceBtrId}set modelSpaceBtrId(e){this._scene.modelSpaceBtrId=e}get activeLayoutBtrId(){return this._scene.activeLayoutBtrId}set activeLayoutBtrId(e){const t=this._scene.activeLayoutBtrId;this._layoutViewManager.activeLayoutBtrId=e,this._scene.activeLayoutBtrId=e,this.htmlTransientManager.setActiveLayoutId(e),this._isDirty=!0,t!==e&&zh()}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,o=[];await this.drainConvertQueue();const r=(l=n.objects)==null?void 0:l.layout;if(i&&(r!=null&&r.newIterator))for(const c of r.newIterator()){const d=c.blockTableRecordId;d&&this._scene.addEmptyLayout(d)}for(const[c]of this._scene.layouts){if(!i&&c!==this._scene.modelSpaceBtrId)continue;const d=n.tables.blockTable.getIdAt(c);d&&o.push(...this._entityDisplay.collectMissingEntitiesForExport(d,h=>this.isEntityConvertScheduled(h),t))}o.length>0&&(this._numOfEntitiesToProcess+=o.length,await this.batchConvert(o,{forExport:!0})),await this.waitUntilIdle(12e4)||p.log.warn("[AcTrView2d] Timed out waiting for deferred geometry before export"),this.flushMeshGlyphWorldBatch()}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 p.AcGePoint2d(e)}worldToScreen(e){const t=this.activeLayoutView;return t?t.worldToScreen(e):new p.AcGePoint2d(e)}zoomTo(e,t=1.1){this.activeLayoutView.zoomTo(e,t),this._isDirty=!0}rerenderPoints(e,t=0){const i=this._scene.activeLayout;i&&(i.rerenderPoints(e,t),this._isDirty=!0)}requestOpenLineworkFrame(){this._openLineworkFramePending=!0,this.scheduleOpenLineworkFrame()}cancelOpenLineworkFrame(){this._openLineworkFramePending=!1,this._openLineworkFrameTimer!=null&&(clearTimeout(this._openLineworkFrameTimer),this._openLineworkFrameTimer=null)}scheduleOpenLineworkFrame(){if(this._openLineworkFrameTimer!=null||!this._openLineworkFramePending)return;const e=this.isConvertingEntities?50:0;this._openLineworkFrameTimer=setTimeout(()=>{if(this._openLineworkFrameTimer=null,!!this._openLineworkFramePending){if(this.isConvertingEntities){this.scheduleOpenLineworkFrame();return}this.frameOpenLineworkIfReady()}},e)}zoomToFitDrawing(e=0,t){new jo(()=>!this.isProcessingEntities,()=>{if(t&&this._externallyFramedLayouts.delete(t)){this.endProgressiveOpenFit();return}this._progressiveOpenFit.applyFinalFit(()=>this.getDrawingExtents()),this.endProgressiveOpenFit();const n=t??this.activeLayoutBtrId;n&&yi.rememberOriginalView(this,n)},300,e).start()}zoomToFitLayer(e){const t=this._scene.activeLayout;if(t){const i=t.getLayer(e);if(i&&!i.box.isEmpty()){const n=mu.threeBox3dToGeBox2d(i.box);return this.zoomTo(n),this._isDirty=!0,!0}}return!1}zoomToSmartExtents(e=0){return new Promise((t,i)=>{new jo(()=>!this.isProcessingEntities,()=>{(async()=>{try{const o=await this.resolveSmartFitBox();if(o){this.zoomTo(o),this._isDirty=!0,this.endProgressiveOpenFit(),t();return}this._progressiveOpenFit.applyFinalFit(()=>this.getDrawingExtents()),this.endProgressiveOpenFit(),t()}catch(o){this.endProgressiveOpenFit(),i(o)}})()},300,e).start()})}async resolveSmartFitBox(){const e=this._scene.activeLayout;if(!e)return;const t=e.cachedSmartExtents;if(t)return t;const i=e.smartExtentsGeneration,n=new gp,o=await e.collectSpatialExtentBoxesAsync(n),r=await bp(o,n);return e.smartExtentsGeneration!==i?e.cachedSmartExtents:(r&&(e.cachedSmartExtents=r),r)}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 o=k.instance.curDocument.database.tables.blockTable.getEntityById(n[0].id);if(!o)return;const r=this.resolveAttributedBlockReference(o);if(r){e.preventDefault(),this.selectionSet.clear(),this.selectionSet.add(r.objectId),k.instance.sendStringToExecute("attedit");return}if(o instanceof p.AcDbMText){e.preventDefault(),await this.editMTextEntity(o);return}o instanceof p.AcDbText&&(e.preventDefault(),await this.editTextEntity(o))}resolveAttributedBlockReference(e){if(e instanceof p.AcDbBlockReference)return e.attributeIterator().count>0?e:void 0;if(e instanceof p.AcDbAttribute||e.type==="Attrib"||e.type==="Attribute"){const t=k.instance.curDocument.database.tables.blockTable.getEntityById(e.ownerId);if(t instanceof p.AcDbBlockReference&&t.attributeIterator().count>0)return t}}async editMTextEntity(e){const t=e.database;this.setEntitySceneVisible(e.objectId,!1),this._isDirty=!0;const i=e.resolveAnnotativePresentation,n=typeof i=="function"?i.call(e):null,o=(n==null?void 0:n.position)??e.location,r={x:o.x,y:o.y,z:o.z??0},a=(n==null?void 0:n.direction)??e.direction,l=(n==null?void 0:n.attachmentPoint)??e.attachmentPoint,c=n&&Number.isFinite(n.width)&&n.width>0?n.width:this.resolveMTextEditorWidth(e),d=n&&Number.isFinite(n.height)&&n.height>0?n.height:this.resolveMTextEditorTextHeight(e),h=new qt;let f=!1;try{const y=await h.open({view:this,location:r,width:c,textHeight:d,initialText:e.contents,initialAttachmentPoint:l,initialDrawingDirection:e.drawingDirection,rotation:e.rotation,directionVector:{x:a.x,y:a.y,z:a.z},textStyleName:e.styleName,initialLineSpaceFactor:e.lineSpacingFactor,toolbarFontFamilies:await this.getMTextToolbarFontFamilies()});if(!y)return;ui(t,"Edit MText",()=>{const g=t.openEntityForWrite(e);g instanceof p.AcDbMText&&(g.location=y.location,g.contents=y.contents,g.width=y.width,g.height=y.height,g.lineSpacingFactor=y.lineSpacingFactor,g.attachmentPoint=y.attachmentPoint)}),f=!0}finally{this.setEntitySceneVisible(e.objectId,!0),f||this.updateEntity(e),this._isDirty=!0}}async editTextEntity(e){const t=e.database;this.setEntitySceneVisible(e.objectId,!1),this._isDirty=!0;const i=Number(e.height),n=Number.isFinite(i)&&i>0?i:this.pixelsToWorldY(24),o=e.textString??"",r=Math.max(n*Math.max(o.length,1)*.6,n),a=Number(e.rotation),l=new qt;let c=!1;try{const d=await l.open({view:this,location:e.position,width:r,textHeight:n,initialText:o,initialAttachmentPoint:p.AcGiMTextAttachmentPoint.BaselineLeft,...Number.isFinite(a)?{rotation:a}:{},toolbarFontFamilies:await this.getMTextToolbarFontFamilies()});if(!d)return;ui(t,"Edit Text",()=>{const h=t.openEntityForWrite(e);h instanceof p.AcDbText&&(h.position=new p.AcGePoint3d(d.location),h.textString=d.contents,Number.isFinite(d.height)&&d.height>0&&(h.height=d.height))}),c=!0}finally{this.setEntitySceneVisible(e.objectId,!0),c||this.updateEntity(e),this._isDirty=!0}}resolveMTextEditorWidth(e){const t=Number(e.width);return Number.isFinite(t)&&t>0?t:0}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)}async getMTextToolbarFontFamilies(){const e=await k.instance.getAvaiableFonts()??[];return Array.from(new Set(e.flatMap(t=>t.name).map(t=>t.trim()).filter(t=>t.length>0)))}pick(e,t,i){e==null&&(e=this.curPos);const n=[],o=this._scene.activeLayout;if(!o)return n;const r=this.activeLayoutView,a=t??this.selectionBoxSize,l=r.pointToBox(e,a),c=Math.max(l.size.width/2,l.size.height/2),d=r.layoutBtrId!==this._scene.modelSpaceBtrId,h=(l.size.width+l.size.height)/2,f=[],y=new Set;if(d)for(const C of r.viewportViews)C.containsPaperPoint(e)&&!C.isNearPaperBorder(e,h)&&(f.push(C),y.add(C.viewport.id));const g=this._scene.search(l),b=r.resetRaycaster(e,c),w=D.AcTrMTextRenderer.getInstance(),S=new Set;g.forEach(C=>{if(y.has(C.id))return;const T=w.intersectMeshGlyphObjectId(C.id,b);!ts(C)&&!T||(o.isIntersectWith(C.id,b)||T)&&(n.push(C),S.add(C.id))});const x=w.queryMeshGlyphObjectIdsIntersectingBox({minX:l.min.x,minY:l.min.y,maxX:l.max.x,maxY:l.max.y});for(const C of x){if(S.has(C)||y.has(C)||!w.intersectMeshGlyphObjectId(C,b))continue;const T=w.getMeshGlyphWorldPickBoxes().get(C);n.push({id:C,minX:(T==null?void 0:T.min.x)??l.min.x,minY:(T==null?void 0:T.min.y)??l.min.y,maxX:(T==null?void 0:T.max.x)??l.max.x,maxY:(T==null?void 0:T.max.y)??l.max.y}),S.add(C)}f.length>0&&this.pickThroughViewports(e,l,f,n);const _=sL(n,e);return i?_.slice(0,1):_}getViewportCoordinateMapper(e){var i;let t;for(const n of((i=this.activeLayoutView)==null?void 0:i.viewportViews)??[])if(n.viewport.id===e){t=n;break}if(t)return{paperToModel:n=>t.paperPointToModel(n),modelToPaper:n=>t.modelPointToPaper(n),containsPaperPoint:n=>t.containsPaperPoint(n)}}pickThroughViewports(e,t,i,n){const o=this._scene.modelSpaceLayout;if(!o)return;const r=(t.size.width+t.size.height)/4;for(const a of i){const l=a.paperPointToModel(e),c=r*a.paperToModelScale;if(c<=0)continue;const d=new p.AcGeBox2d().setFromPoints([new p.AcGePoint2d(l.x-c,l.y-c),new p.AcGePoint2d(l.x+c,l.y+c)]),h=a.resetRaycaster(l,c);o.search(d).forEach(y=>{ts(y)&&o.isIntersectWith(y.id,h)&&n.push({...y,viewportId:a.viewport.id})})}}search(e,t){return this._scene.search(e,t)}select(e){const t=[];this.pick(e).forEach(o=>t.push(o.id));const n=this.selectableIds(t,"add");n.length>0&&this.selectionSet.add(n)}selectByBox(e){this.selectByBoxWithMode(e,"crossing","add")}refineCrossingSelectionHits(e,t){var o;const i=(o=k.instance.curDocument)==null?void 0:o.database;if(!i)return t.map(r=>r.id);const n=[];for(const r of t){if(!Ef(r)){n.push(r.id);continue}const a=new p.AcGeBox2d({x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY});if(e.containsBox(a)){n.push(r.id);continue}const l=i.tables.blockTable.getEntityById(r.id);(!l||Pf(l,e))&&n.push(r.id)}return n}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);(on.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;const o=this._renderer.context;this._transientSkipMeshGlyphDepth++,o.skipMeshGlyphInstancing=!0;const r=()=>{this._transientSkipMeshGlyphDepth=Math.max(0,this._transientSkipMeshGlyphDepth-1),this._transientSkipMeshGlyphDepth===0&&(o.skipMeshGlyphInstancing=!1)};try{for(let a=0;a<t.length;++a){const l=t[a],c=String(l.objectId??""),d=c?(this._transientDrawGeneration.get(c)??0)+1:0;c&&(this._transientDrawGeneration.set(c,d),D.AcTrMTextRenderer.getInstance().removeMeshGlyphInstances(c));const h=this.drawEntity(l,!0);if(h){h.objectId=l.objectId,h.userData.skipMeshGlyphInstancing=!0;try{h.syncDraw()}catch(f){p.log.error("[AcTrView2d] Transient entity geometry failed:",f),h.dispose();continue}if(i!==this._convertEpoch){h.dispose();continue}if(c&&this._transientDrawGeneration.get(c)!==d){h.dispose();continue}this._scene.addTransientEntity(h),this._isDirty=!0}}}finally{this._renderer.forceShowLineWeight=n,r()}}removeTransientEntity(e){const t=String(e??"");t&&this._transientDrawGeneration.set(t,(this._transientDrawGeneration.get(t)??0)+1),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){var i;const t=Array.isArray(e)?e:[e];for(let n=0;n<t.length;n++){const o=(i=t[n])==null?void 0:i.ownerId;if(!o)continue;let r=this._scene.layouts.get(o);r||(this._scene.addEmptyLayout(o),r=this._scene.layouts.get(o)),r&&!r.isLoaded&&(r.isLoaded=!0)}this._numOfEntitiesToProcess+=t.length,this._convertQueue.push(...t),this.drainConvertQueue()}removeEntity(e){(Array.isArray(e)?e:[e]).forEach(i=>{this.releaseConvertClaim(i.objectId),this._scene.removeEntity(i.objectId)}),this._isDirty=!0}releaseConvertClaim(e){const t=String(e??"");t&&(this._claimedConvertObjectIds.delete(t),this._entityConvertGeneration.set(t,(this._entityConvertGeneration.get(t)??0)+1))}hasEntity(e){return this._scene.hasEntity(e)}isEntityConvertScheduled(e){const t=String(e??"");return t?this.hasEntity(e)||this._claimedConvertObjectIds.has(t):!1}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 o=t[n],r=String(o.objectId??"");r&&(this._entityConvertGeneration.set(r,(this._entityConvertGeneration.get(r)??0)+1),this._claimedConvertObjectIds.delete(r),D.AcTrMTextRenderer.getInstance().removeMeshGlyphInstances(r)),this._scene.hasEntity(o.objectId)&&this._scene.removeEntity(o.objectId)}(async()=>(await this.batchConvert(t),await this.waitUntilDeferredGeometryIdle(),i.length>0&&this.highlight(i),this._gripManager.refresh(),this._isDirty=!0))(),this._isDirty=!0,setTimeout(()=>{this._isDirty=!0},100)}resolveSceneUpdateEntities(e){var o;const t=(o=k.instance.curDocument)==null?void 0:o.database,i=[],n=new Set;for(const r of e){let a=r;if(r instanceof p.AcDbAttribute){const l=t==null?void 0:t.tables.blockTable.getEntityById(r.ownerId);if(!(l instanceof p.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)}setOpenViewMode(e){this._openViewMode=e}isLayoutInitialized(e){return this._initializedLayouts.has(e)}getDrawingExtents(){const e=this._scene.box;if(e&&!e.isEmpty())return mu.threeBox3dToGeBox2d(e)}applyInitialZoom(e,t){new jo(()=>!this.isProcessingEntities,()=>{if(this._externallyFramedLayouts.delete(e))return;const n=this.resolveFirstVisitFrameBox(e,t);n&&this.zoomTo(n),this._isDirty=!0,yi.rememberOriginalView(this,e)},300,0).start()}resolveFirstVisitFrameBox(e,t){var d,h;const i=e===this.modelSpaceBtrId,n=this._openViewMode===_t.Saved;if(n&&i){const f=k.instance.curDocument.database,y=this.width/Math.max(this.height,1),g=f.tables.viewportTable.getActiveVportBox(y);if(g)return g}const o=this._layoutViewManager.getAt(e),r=t.extents,a=r&&!r.isEmpty()?{min:{x:r.min.x,y:r.min.y},max:{x:r.max.x,y:r.max.y}}:void 0,l=this.getDrawingExtents(),c=o==null?void 0:o.viewportsBoundingBox;return n&&!i?(d=kr({limits:t.limits,viewportsBox:c,layoutExtents:a,entityBox:l}))==null?void 0:d.box:(h=kr({limits:void 0,viewportsBox:i?void 0:c,layoutExtents:a,entityBox:l}))==null?void 0:h.box}abortConversion(){this._convertEpoch++,this.clearFontLoadedRedrawTimer(),this.clearMeshGlyphFlushTimer(),this._convertQueue.length=0,this._viewportRepairOwnerIds.clear(),this._numOfEntitiesToProcess=0,this._claimedConvertObjectIds.clear(),this._entityConvertGeneration.clear(),this.cancelOpenLineworkFrame(),this.resetDeferredGeometryQueue(),this._entityProcessingIdleAt=0}clear(){this.abortConversion(),this._scene.clear(),D.AcTrMTextRenderer.getInstance().resetMeshGlyphBatch(),this._renderer.resetDrawOrderZ(),this._isDirty=!0,this._missedImages.clear(),this._initializedLayouts.clear(),this._externallyFramedLayouts.clear(),this._openViewMode=_t.Extents,this._loadingLayouts.clear(),this._renderer.dispose(),p.AcDbRenderingCache.instance.clear(),Q.emit("missed-data-changed",{})}captureSessionState(){return this.clearMeshGlyphFlushTimer(),{scene:this._scene,layoutViewManager:this._layoutViewManager,initializedLayouts:this._initializedLayouts,externallyFramedLayouts:this._externallyFramedLayouts,openViewMode:this._openViewMode,loadingLayouts:this._loadingLayouts,missedImages:this._missedImages,missedFonts:this._renderer.snapshotMissedFonts(),selectionIds:this.selectionSet.ids,meshGlyphBatch:D.AcTrMTextRenderer.getInstance().detachMeshGlyphBatch()}}restoreSessionState(e){this._convertEpoch++,this.clearFontLoadedRedrawTimer(),this.clearMeshGlyphFlushTimer(),this.cancelOpenLineworkFrame(),this._convertQueue.length=0,this._viewportRepairOwnerIds.clear(),this._numOfEntitiesToProcess=0,this._claimedConvertObjectIds.clear(),this._entityConvertGeneration.clear(),this.resetDeferredGeometryQueue(),this._entityProcessingIdleAt=0,this._scene=e.scene,this._layoutViewManager=e.layoutViewManager,this._initializedLayouts=e.initializedLayouts,this._externallyFramedLayouts=e.externallyFramedLayouts,this._openViewMode=e.openViewMode??_t.Extents,this._loadingLayouts=e.loadingLayouts,this._missedImages=e.missedImages,this._renderer.replaceMissedFonts(e.missedFonts??{}),D.AcTrMTextRenderer.getInstance().attachMeshGlyphBatch(e.meshGlyphBatch),this.rebindLayerAppearance(),this._layoutViewManager.resize(this.width,this.height),this.selectionSet.clear(),e.selectionIds.length>0&&this.selectionSet.add(e.selectionIds),this._isDirty=!0,Q.emit("missed-data-changed",{})}beginNewSession(){const e=this.captureSessionState();return this._convertEpoch++,this.clearFontLoadedRedrawTimer(),this.cancelOpenLineworkFrame(),this._convertQueue.length=0,this._viewportRepairOwnerIds.clear(),this._numOfEntitiesToProcess=0,this._claimedConvertObjectIds.clear(),this._entityConvertGeneration.clear(),this.resetDeferredGeometryQueue(),this._entityProcessingIdleAt=0,this._scene=this.createScene(),this._layoutViewManager=new yu,this._initializedLayouts=new Set,this._externallyFramedLayouts=new Set,this._openViewMode=_t.Extents,this._loadingLayouts=new Set,this._missedImages=new Map,this._renderer.clearMissedFonts(),this.rebindLayerAppearance(),this.selectionSet.clear(),this._isDirty=!0,Q.emit("missed-data-changed",{}),e}disposeSessionState(e){e.meshGlyphBatch.dispose(),e.scene.clear(),e.layoutViewManager=new yu,e.initializedLayouts.clear(),e.externallyFramedLayouts.clear(),e.loadingLayouts.clear(),e.missedImages.clear(),e.missedFonts={},e.selectionIds=[]}rebindLayerAppearance(){this._layerAppearance=new Gl(this._scene,this._renderer)}isActiveManagedView(){var i;const t=(i=k._instance)==null?void 0:i.curView;return t!=null&&t===this}focusViewerForShortcuts(){const e=document.activeElement;e instanceof Node&&this.container.contains(e)||e instanceof HTMLElement&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable)||this.container.focus({preventScroll:!0})}isShortcutEventInsideViewer(e){const t=e.target;if(t instanceof Node&&this.container.contains(t))return!0;const i=document.activeElement;return i instanceof Node&&this.container.contains(i)}async drainConvertQueue(){if(this._convertDrainPromise){await this._convertDrainPromise,this._convertQueue.length>0&&await this.drainConvertQueue();return}this._convertDrainPromise=this.runConvertDrain().finally(()=>{this._convertDrainPromise=null}),await this._convertDrainPromise}async runConvertDrain(){const e=this._convertEpoch,t=this._cooperativeYield;let i=t?this.activeLayoutBtrId===this.modelSpaceBtrId?de.CONVERT_SLICE_MAX:1:Number.POSITIVE_INFINITY,n=performance.now(),o=YE(this._convertQueue.splice(0,this._convertQueue.length),this.activeLayoutBtrId);for(this.repairViewportViewsFor(o.activeOwnerId);o.cursor<o.pending.length||this._convertQueue.length>0;){if(this._convertEpoch!==e)return;const r=this._convertQueue.splice(0,this._convertQueue.length),a=this.activeLayoutBtrId,l=a!==o.activeOwnerId;if(o=ZE(o,r,a),l&&(this.repairViewportViewsFor(a),t&&(i=1)),this.flushViewportViewRepairs(),o.cursor>=o.pending.length)break;const c=Math.min(o.pending.length,o.cursor+i),d=performance.now();if(await this.batchConvert(o.pending.slice(o.cursor,c)),o.cursor=c,this._convertEpoch!==e)return;if(!t)continue;const h=performance.now()-d,f=o.activeOwnerId===this.modelSpaceBtrId,y=this._progressiveRendering?de.PROGRESSIVE_OPEN_YIELD_BUDGET_MS:de.OPEN_CONVERT_YIELD_BUDGET_MS,g=f?y:de.CONVERT_SLICE_BUDGET_MS;if(i=qE({slice:i,tookMs:h,budgetMs:g,maxSlice:de.CONVERT_SLICE_MAX,activeLayoutPending:!f&&XE(o)}),this._progressiveRendering&&this.isProgressiveGesturePauseActive()){for(await new Promise(b=>setTimeout(b,0));performance.now()<this._progressiveInputPauseUntil;)await new Promise(b=>setTimeout(b,16));if(n=performance.now(),this._convertEpoch!==e)return}else if(this._progressiveRendering&&this.isProgressiveDiscreteInputPending()){if(await new Promise(b=>setTimeout(b,0)),n=performance.now(),this._convertEpoch!==e)return}else if(performance.now()-n>=g&&(await new Promise(b=>setTimeout(b,0)),n=performance.now(),this._convertEpoch!==e))return}this.repairViewportViewsFor(this.activeLayoutBtrId),this.flushViewportViewRepairs()}repairViewportViewsFor(e){var i;if(!e||e===this.modelSpaceBtrId)return;const t=this._layoutViewManager.getAt(e);if(!t||t.viewportCount>0){t&&t.viewportCount>0&&this._viewportRepairOwnerIds.delete(e);return}try{const n=(i=k.instance.curDocument)==null?void 0:i.database,o=n==null?void 0:n.tables.blockTable.getIdAt(e);if(!o)return;const r=t.viewportCount;this.ensureViewportViews(o,t),t.viewportCount>r&&(this._isDirty=!0),this._viewportRepairOwnerIds.delete(e)}catch(n){p.log.error("[AcTrView2d] Error repairing viewport views:",n)}}flushViewportViewRepairs(){if(this._viewportRepairOwnerIds.size===0)return;const e=Array.from(this._viewportRepairOwnerIds);for(let t=0;t<e.length;t++)this.repairViewportViewsFor(e[t])}markProgressiveDirty(e=!1){const t=performance.now();(e||t-this._lastProgressivePaintAt>=de.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS)&&(this._isDirty=!0)}markInteractiveOpenDirty(){this._progressiveRendering||!this._cooperativeYield||(this._isDirty=!0)}shouldCountMidOpenPaint(e,t){return this._progressiveRendering&&e||!this._progressiveRendering&&this._cooperativeYield&&t}highlight(e){this.entitySelectionEnabled&&(this._isDirty=this._scene.select(e))}unhighlight(e){this._isDirty=this._scene.unselect(e)}setCompareDisplay(e,t){var o,r,a,l;const i=e.baseColor??((o=e.colors)==null?void 0:o.unchanged)??10265519,n={enabled:e.enabled,baseColor:i,colors:{deleted:(r=e.colors)==null?void 0:r.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)}dispose(){var t,i,n;if(this._viewDisposed)return;this._viewDisposed=!0,this.abortConversion(),(t=this._disposeCanvasTouchCallout)==null||t.call(this),this._disposeCanvasTouchCallout=void 0,(i=this._disposeProgressiveInputWatch)==null||i.call(this),this._disposeProgressiveInputWatch=void 0,(n=this._disposeMobileBoxGesture)==null||n.call(this),this._disposeMobileBoxGesture=void 0,this._viewDomAbort.abort(),this._onFontNotFound&&this._renderer.events.fontNotFound.removeEventListener(this._onFontNotFound),this._onFontLoaded&&this._renderer.events.fontLoaded.removeEventListener(this._onFontLoaded),this._onSysVarChanged&&p.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this._onSysVarChanged),this._onSettingsModified&&le.instance.events.modified.removeEventListener(this._onSettingsModified),this._onLayoutSwitched&&p.acdbHostApplicationServices().layoutManager.events.layoutSwitched.removeEventListener(this._onLayoutSwitched),this._onCommandWillStartHitTest&&this.editor.events.commandWillStart.removeEventListener(this._onCommandWillStartHitTest),this._onCommandEndedHitTest&&this.editor.events.commandEnded.removeEventListener(this._onCommandEndedHitTest),this._gripManager.dispose(),this.clearFontLoadedRedrawTimer(),this.cancelOpenLineworkFrame(),this.stopAnimationLoop(),this.selectionSet.clear(),this.htmlTransientManager.dispose(),this._scene.clear(),this._renderer.dispose(),p.AcDbRenderingCache.instance.clear();const e=this._renderer.internalRenderer;e.dispose(),e.forceContextLoss(),this.canvas.remove(),this._css2dRenderer.domElement.remove(),this._stats.dom.remove(),super.dispose()}onHover(e){this.entitySelectionEnabled&&(this._isDirty=this._scene.hover([e]))}onUnhover(e){this._isDirty=this._scene.unhover([e])}createScene(){return new _p}createStats(e){const t=new Rx;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(){this.refreshViewSize(),this._renderer.setSize(this.width,this.height),this._css2dRenderer.setSize(this.width,this.height),this._layoutViewManager.resize(this.width,this.height),this._isDirty=!0,this.events.viewResize.dispatch({width:this.width,height:this.height}),this.events.viewChanged.dispatch()}startAnimationLoop(){this._rafId==null&&(this._rafId=requestAnimationFrame(this.animate))}createLayoutViewIfNeeded(e){let t=this._layoutViewManager.getAt(e);return t==null&&(t=new nL(this._renderer,e,this.width,this.height),t.events.viewChanged.addEventListener(()=>{this._progressiveOpenFit.onLayoutViewChanged(),this._isDirty=!0,this._progressiveRendering&&this._numOfEntitiesToProcess>0&&(this._progressivePaintUrgent=!0),this.events.viewChanged.dispatch(),this.clearHover()}),this._layoutViewManager.add(t)),this.flushViewportViewRepairs(),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.repairViewportViewsFor(e);return}if(this._loadingLayouts.has(e))return;if(this.repairViewportViewsFor(e),n&&n.entityCount>0){n.isLoaded=!0;return}n||this._scene.addEmptyLayout(e);const o=[],r=i.newIterator();for(const l of r)o.push(l);if(o.length===0){const l=this._scene.layouts.get(e);l&&(l.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 l=this._scene.layouts.get(e);l&&(l.isLoaded=!0)}finally{this._loadingLayouts.delete(e)}})()}catch(t){p.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,o=>this.hasEntity(o));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)}startTextStyleFontPreload(e){var y,g;const t=this._convertEpoch;if(this._textStyleFontPreloadEpoch===t&&this._textStyleFontPreloadPromise)return;this._textStyleFontPreloadEpoch=t;const i=Jv(e),n=$.FontManager.instance.getFontsToLoad(),o=[...$.FontManager.instance.defaultFonts][0],r=Qv(i,n,{firstDefaultFont:o}),l=D.AcTrMTextRenderer.getInstance().getRenderMode()==="worker"?"worker":"main",c=k,d=(g=(y=c._instance)==null?void 0:y.lastPresetFontsForOpen)!=null&&g.length?[...c._instance.lastPresetFontsForOpen]:[...n];if(this._fontPreloadDiag={critical:[...r.critical],workerWarm:[],background:[],preset:d,workerSkipped:0,parseSite:l},l==="worker"){this._textStyleFontPreloadPromise=Promise.resolve();return}const h=3e4;if(r.critical.length===0){this._textStyleFontPreloadPromise=Promise.resolve();return}const f=$.FontManager.instance.requestFonts(r.critical);this._textStyleFontPreloadPromise=new Promise(b=>{const w=setTimeout(()=>{b()},h);f.then(()=>{clearTimeout(w),b()},()=>{clearTimeout(w),b()})})}async awaitTextStyleFontsReady(){if(!this._textStyleFontPreloadPromise){const e=this._renderer.context.database;if(e)this.startTextStyleFontPreload(e);else return}await this._textStyleFontPreloadPromise}async finishEntityGeometry(e,t){const i=performance.now();try{const n=e instanceof D.AcTrGroup,o=n&&this.groupHasPendingGlyphGeometry(e);(o||D.hasPendingComplexLineTypeGlyphs(e)||e instanceof D.AcTrGlyphEntity&&!e.hasDrawableGeometry())&&await this.ensureDeferredFontsReady();const a=()=>{this._convertPhaseMs.glyphEntityCount++,e instanceof D.AcTrMText?this._convertPhaseMs.mtextCount++:e instanceof D.AcTrShape&&this._convertPhaseMs.shapeCount++};if(n){if(!o)return;a();const c=performance.now();await e.asyncDraw(),this._convertPhaseMs.finishGeometryAsyncDraw+=performance.now()-c;return}if(D.hasPendingComplexLineTypeGlyphs(e)){a();const c=performance.now();await e.asyncDraw(),this._convertPhaseMs.finishGeometryAsyncDraw+=performance.now()-c;return}if(e.hasDrawableGeometry())return;a();const l=performance.now();await e.asyncDraw(),this._convertPhaseMs.finishGeometryAsyncDraw+=performance.now()-l}finally{this._convertPhaseMs.finishGeometry+=performance.now()-i}}needsDeferredFontGeometry(e){return e instanceof D.AcTrGlyphEntity?!e.hasDrawableGeometry():e instanceof D.AcTrGroup?this.groupHasPendingGlyphGeometry(e):D.hasPendingComplexLineTypeGlyphs(e)}clearFontLoadedRedrawTimer(){this._fontLoadedRedrawTimer!=null&&(clearTimeout(this._fontLoadedRedrawTimer),this._fontLoadedRedrawTimer=null)}scheduleGlyphRedrawAfterFontLoad(e){this.clearFontLoadedRedrawTimer();const t=this._convertEpoch;this._fontLoadedRedrawTimer=setTimeout(()=>{this._fontLoadedRedrawTimer=null,t===this._convertEpoch&&this.redrawGlyphEntitiesAfterFontLoad(t,e)},50)}async redrawGlyphEntitiesAfterFontLoad(e,t){var a,l;if(e!==this._convertEpoch)return;const i=++this._fontLoadedRedrawEpoch,n=[];for(const c of this._scene.layouts.values())c.layers.forEach(d=>{d.internalObject.traverse(h=>{h instanceof D.AcTrGlyphEntity&&n.push(h)})});for(const c of n){if(e!==this._convertEpoch||i!==this._fontLoadedRedrawEpoch)return;await c.asyncDraw()}if(n.length>0){e===this._convertEpoch&&(this._isDirty=!0);return}if(t){const c=$.FontManager.instance.defaultFonts,d=t.toLowerCase();if(c.has(t)||c.has(d)||[...c].some(h=>h.toLowerCase()===d))return}if(e!==this._convertEpoch||i!==this._fontLoadedRedrawEpoch||this._entityProcessingIdleAt<=0)return;const o=performance.now()-this._entityProcessingIdleAt;if(!aL(this.isProcessingEntities,0,o))return;const r=(l=(a=k.instance)==null?void 0:a.curDocument)==null?void 0:l.database;r&&r.regen()}groupHasPendingGlyphGeometry(e){for(const t of e.getSourceEntities())if(t instanceof D.AcTrGlyphEntity&&!t.hasDrawableGeometry())return!0;return de.directChildrenHavePendingGlyphs(e)}static directChildrenHavePendingGlyphs(e){const t=e.children;for(let i=0;i<t.length;i++){const n=t[i];if(n instanceof D.AcTrGlyphEntity){if(!n.hasDrawableGeometry())return!0;continue}if(n instanceof D.AcTrGroup){for(const o of n.getSourceEntities())if(o instanceof D.AcTrGlyphEntity&&!o.hasDrawableGeometry())return!0;if(de.directChildrenHavePendingGlyphs(n))return!0;continue}if(n instanceof D.AcTrEntity&&de.directChildrenHavePendingGlyphs(n))return!0}return!1}enqueueDeferredGeometry(e,t){t===this._convertEpoch&&(this._pendingGeometryJobs++,this._deferredGeometryQueue.push({run:e,epoch:t,enqueuedAt:performance.now()}),this.pumpDeferredGeometryQueue())}pumpDeferredGeometryQueue(){for(;this._deferredGeometryActive<de.DEFERRED_GEOMETRY_CONCURRENCY&&this._deferredGeometryQueue.length>0;){const e=this._deferredGeometryQueue.shift();if(e.epoch!==this._convertEpoch){this._pendingGeometryJobs=Math.max(0,this._pendingGeometryJobs-1);continue}this._convertPhaseMs.finishGeometryQueueWait+=performance.now()-e.enqueuedAt,this._deferredGeometryActive++,e.run().then(()=>{e.epoch===this._convertEpoch&&(this._progressiveRendering||this._cooperativeYield)&&(this._isDirty=!0)}).catch(t=>{p.log.error("[AcTrView2d] Deferred entity geometry failed:",t)}).finally(()=>{this._deferredGeometryActive=Math.max(0,this._deferredGeometryActive-1),e.epoch===this._convertEpoch&&(this._pendingGeometryJobs=Math.max(0,this._pendingGeometryJobs-1),this._pendingGeometryJobs===0&&(this._isDirty=!0),this.stampEntityProcessingIdle()),this.pumpDeferredGeometryQueue()})}}resetDeferredGeometryQueue(){this._deferredGeometryQueue.length=0,this._pendingGeometryJobs=0,this._textStyleFontPreloadPromise=null,this._textStyleFontPreloadEpoch=-1,this._deferredFontsReady=null,this._fontPreloadDiag=null}async waitUntilDeferredGeometryIdle(){const e=this._convertEpoch;for(;e===this._convertEpoch&&this._pendingGeometryJobs>0;)await new Promise(t=>setTimeout(t,0))}attachViewportView(e){if(D.AcTrViewportView.isDefaultPaperSpaceViewport(e))return;const t=e.ownerId,i=t?this._layoutViewManager.getAt(t):void 0;if(!i){t&&this._viewportRepairOwnerIds.add(t);return}i.addViewport(new D.AcTrViewportView(i,this.toGiViewportWithFrozenLayers(e),this._renderer)),this._isDirty=!0}ensureViewportViews(e,t){const i=e.newIterator();for(const n of i){if(!(n instanceof p.AcDbViewport)||D.AcTrViewportView.isDefaultPaperSpaceViewport(n))continue;const o=new D.AcTrViewportView(t,this.toGiViewportWithFrozenLayers(n),this._renderer);t.addViewport(o)}}toGiViewportWithFrozenLayers(e){var r;const t=e.toGiViewport();if(t.frozenLayers&&t.frozenLayers.length>0)return t;const i=e.frozenLayerIds;if(!(i!=null&&i.length))return t;const n=[],o=(r=e.database)==null?void 0:r.tables.layerTable;if(o)for(const a of i){const l=o.getIdAt(a);l&&n.push(l.name)}return t.frozenLayerIds=[...i],t.frozenLayers=n,t}async batchConvert(e,t={}){const i=this._convertEpoch;if(!t.forExport&&!this._textStyleFontPreloadPromise){const l=this._renderer.context.database;l&&this.startTextStyleFontPreload(l)}const n=this._progressiveRendering&&!t.forExport,o=n?de.PROGRESSIVE_OPEN_YIELD_BUDGET_MS:de.OPEN_CONVERT_YIELD_BUDGET_MS,r=t.forExport||!this._cooperativeYield?void 0:new p.AcCmUiYieldGate(o),a=()=>new Promise(l=>setTimeout(l,0));for(let l=0;l<e.length;++l){const c=e[l];try{if(i!==this._convertEpoch||c instanceof p.AcDbViewport&&D.AcTrViewportView.isDefaultPaperSpaceViewport(c)||!(t.forExport||this._convertInvisibleLayers?this._entityDisplay.shouldConvertForExport(c):this._entityDisplay.shouldConvert(c)))continue;const h=String(c.objectId??"");let f=0;if(h&&(this.hasEntity(h)||this._claimedConvertObjectIds.has(h))){c instanceof p.AcDbViewport&&this.attachViewportView(c);continue}h&&(this._claimedConvertObjectIds.add(h),f=this._entityConvertGeneration.get(h)??0);const y=D.tryBuildDirectEntityMeta(c,this._renderer);if(y){let b=!1,w=!1;try{h&&(this._entityConvertGeneration.get(h)??0)!==f?w=!0:(b=this._scene.addDirectEntity(y,D.shouldExtendBboxForDirectEntity(c)),b&&(this.applySessionHiddenObjectState(c.objectId),n?(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.getDrawingExtents(),l)):this.markInteractiveOpenDirty()))}finally{y.geometry.dispose()}if(w||b)continue}const g=this.drawEntity(c,!1);if(!g&&!(c instanceof p.AcDbViewport)){h&&this._claimedConvertObjectIds.delete(h);continue}if(g){g.objectId=c.objectId,g.ownerId=c.ownerId,g.layerName=c.layer,g.visible=c.visibility!==!1,g instanceof D.AcTrGroup&&g.isOnTheSameLayer&&(g.userData.insertLayerName=g.layerName);const b=g instanceof D.AcTrGroup&&!g.isOnTheSameLayer,w=!t.forExport&&this.needsDeferredFontGeometry(g);if(b)w?this.enqueueDeferredGeometry(()=>this.handleGroup(g,n,i,f),i):await this.handleGroup(g,n,i,f);else{const S=!(c instanceof p.AcDbRay||c instanceof p.AcDbXline),x=async()=>{if(await this.finishEntityGeometry(g,n),i!==this._convertEpoch){g.dispose();return}if(h&&(this._entityConvertGeneration.get(h)??0)!==f){g.dispose();return}g instanceof D.AcTrGroup&&(this.syncGroupSpatialBoundsForIndexing(g),g.isOnTheSameLayer&&this._inheritedLayerMaterialMapper.remap(g.children,"0",g.layerName));const _=performance.now();this._scene.addEntity(g,S),this._convertPhaseMs.addEntity+=performance.now()-_,this.applySessionHiddenObjectState(c.objectId),g.dispose(),n?(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.getDrawingExtents(),l)):this.markInteractiveOpenDirty()};w?this.enqueueDeferredGeometry(x,i):await x()}}if(i!==this._convertEpoch)continue;if(c instanceof p.AcDbViewport)this.attachViewportView(c);else if(c instanceof p.AcDbRasterImage){const b=c.imageFileName;b&&!c.image?this._missedImages.set(c.objectId,b):c.image&&this._missedImages.delete(c.objectId)}}catch(d){const h=String(c.objectId??"");h&&this._claimedConvertObjectIds.delete(h),p.log.error(`[AcTrView2d] Failed to convert entity ${c.objectId} (${c.type}):`,d)}finally{i===this._convertEpoch&&this.decreaseNumOfEntitiesToProcess()}i===this._convertEpoch&&(n?await this.progressiveYieldForInput(r,a):r&&await r.maybeYield(a)&&this._progressiveYieldCount++)}}syncGroupSpatialBoundsForIndexing(e){const t=e.peekLazyChildBoxes();if(t&&t.boxes.length>0){const o=e.userData;o.lazySpatialChildren=t;return}if(e.refreshWcsChildBoxesFromChildren(),e.wcsChildBoxes.length===0)return;const i=e.wcsChildBoxes.map(o=>({minX:o.minX,minY:o.minY,maxX:o.maxX,maxY:o.maxY,id:o.id}));e.wcsBbox=zl(e);const n=e.userData;n.spatialIndexChildBoxes=i}async handleGroup(e,t,i=this._convertEpoch,n=0){const o=performance.now();try{if(await this.finishEntityGeometry(e,t),i!==this._convertEpoch){e.dispose();return}const r=String(e.objectId??"");if(r&&(this._entityConvertGeneration.get(r)??0)!==n){e.dispose();return}this.syncGroupSpatialBoundsForIndexing(e);const a=e.children,l=new Map;a.forEach(x=>{var C;if(x.visible===!1)return;const _=x.userData.layerName;l.has(_)||l.set(_,[]),(C=l.get(_))==null||C.push(x)}),e.children=[];for(const x of a)x.parent=null;const c=e.renderContext,d=e.objectId,h=e.layerName,f=e.userData.lazySpatialChildren;process.env.NODE_ENV!=="production"&&!f&&pS(e);const y=f?[]:e.wcsChildBoxes.map(x=>({minX:x.minX,minY:x.minY,maxX:x.maxX,maxY:x.maxY,id:x.id})),g=f?e.wcsBbox.clone():y.length>0?zl(e):e.wcsBbox.clone();y.length>0&&(e.wcsBbox=g.clone());let b=!1;const w=()=>new Promise(x=>setTimeout(x,0));let S=t?performance.now():0;for(const[x,_]of l){const C=x==="0"?h:x,T=_.some(A=>(A.userData.authoredLayerName??x)==="0")?"0":x;this._inheritedLayerMaterialMapper.remap(_,T,C);const L=new D.AcTrEntity(c);L.matrix.copy(e.matrix),L.matrixAutoUpdate=!1,L.matrixWorldNeedsUpdate=!0,L.objectId=d,L.ownerId=e.ownerId,L.layerName=C,L.userData.insertLayerName=h,L.wcsBbox=g.clone();const N=L.userData;!b&&f?(L.userData.lazySpatialChildren=f,b=!0):!b&&y.length>0&&(N.spatialIndexChildBoxes=y,b=!0);for(let A=0;A<_.length;A++)L.add(_[A]);L.updateMatrixWorld(!0),this._layerAppearance.refreshTextMaterialsInObjectTree(L);const B=performance.now();this._scene.addEntity(L,!0),this._convertPhaseMs.addEntity+=performance.now()-B,this.applySessionHiddenObjectState(d),L.dispose(),t&&i===this._convertEpoch&&performance.now()-S>=de.PROGRESSIVE_OPEN_YIELD_BUDGET_MS&&(await w(),S=performance.now())}e.dispose(),t?(this.markProgressiveDirty(),this._progressiveOpenFit.afterGeometryBatch(()=>this.getDrawingExtents())):this.markInteractiveOpenDirty()}finally{this._convertPhaseMs.handleGroup+=performance.now()-o}}decreaseNumOfEntitiesToProcess(){this._numOfEntitiesToProcess--,this._numOfEntitiesToProcess<0?(this._numOfEntitiesToProcess=0,p.log.warn("Something wrong! The number of entities to process should not be less than 0.")):this._numOfEntitiesToProcess===0&&(this._isDirty=!0,Q.emit("missed-data-changed",{})),this.stampEntityProcessingIdle()}frameOpenLineworkIfReady(){if(!this._openLineworkFramePending||this.isConvertingEntities)return;const e=this.getDrawingExtents();if(!e||e.isEmpty()){this._openLineworkFramePending=!1;return}this._openLineworkFramePending=!1,this._progressiveOpenFit.frameProgrammatically(e)}stampEntityProcessingIdle(){this._numOfEntitiesToProcess===0&&this._pendingGeometryJobs===0&&(this._entityProcessingIdleAt=performance.now(),this.scheduleMeshGlyphWorldBatchFlush(),p.AcDbRenderingCache.instance.clear())}clearMeshGlyphFlushTimer(){this._meshGlyphFlushTimer!=null&&(clearTimeout(this._meshGlyphFlushTimer),this._meshGlyphFlushTimer=null)}scheduleMeshGlyphWorldBatchFlush(){if(!D.AcTrMTextRenderer.getInstance().getMeshGlyphInstancing())return;this.clearMeshGlyphFlushTimer();const t=this._convertEpoch;this._meshGlyphFlushTimer=setTimeout(()=>{this._meshGlyphFlushTimer=null,t===this._convertEpoch&&(this._numOfEntitiesToProcess>0||this._pendingGeometryJobs>0||this.flushMeshGlyphWorldBatch())},16)}flushMeshGlyphWorldBatch(){this.clearMeshGlyphFlushTimer();const e=D.AcTrMTextRenderer.getInstance();if(!e.getMeshGlyphInstancing())return;const{placements:t,buckets:i}=e.flushMeshGlyphInstances(this._scene.internalScene,(n,o)=>this.resolveMeshGlyphLayerParent(n,o));t>0&&(console.log(`[cad-simple-viewer-cli] mesh glyph InstancedMesh flush: placements=${t} buckets=${i}`),this._isDirty=!0)}resolveMeshGlyphLayerParent(e,t){var o,r;const i=t==null?void 0:t.trim();if(i){const a=this._scene.layouts.get(i);return a?((o=a.getLayer(e))==null?void 0:o.internalObject)??null:null}const n=(r=this._scene.activeLayout)==null?void 0:r.getLayer(e);if(n)return n.internalObject;for(const a of this._scene.layouts.values()){const l=a.getLayer(e);if(l)return l.internalObject}return null}};de.OPEN_CONVERT_YIELD_BUDGET_MS=300,de.PROGRESSIVE_OPEN_YIELD_BUDGET_MS=32,de.PROGRESSIVE_INPUT_PAUSE_MS=120,de.PROGRESSIVE_OPEN_PAINT_INTERVAL_MS=2500,de.NON_PROGRESSIVE_OPEN_PAINT_INTERVAL_MS=4e3,de.DEFERRED_GEOMETRY_CONCURRENCY=8,de.CONVERT_SLICE_BUDGET_MS=64,de.CONVERT_SLICE_MAX=512;let Mn=de;function lL(s){if(!s)return!1;const e=Object.keys(s);return e.length>0&&e.every(t=>t==="visibility")}function cL(s,e,t){const{entity:i,changes:n}=s,o=i.objectId;if(!e(o))return!1;if(lL(n))return!(n.visibility===!0&&t(o)===void 0);if(n&&Object.keys(n).length>0)return!1;const r=t(o);return r===void 0?!1:r&&!i.visibility}function yx(s){return Array.isArray(s)?s:[s]}class Ea{constructor(e,t){this._active=!0,this._disposers=[],this._view=e,this._doc=t;const i=(n,o)=>{n.addEventListener(o),this._disposers.push(()=>n.removeEventListener(o))};i(t.database.events.entityAppended,n=>{if(!this._active)return;const o=yx(n.entity).filter(r=>{if(this.view.hasEntity(r.objectId))return!1;const a=t.database.tables.blockTable.getIdAt(r.ownerId);return!!(a&&(a.isModelSapce||a.isPaperSapce))});o.length!==0&&this.view.addEntity(o.length===1?o[0]:o)}),i(t.database.events.entityModified,n=>{if(!this._active)return;const o=n,r=this.view;r instanceof Mn&&cL(o,a=>r.hasEntity(a),a=>r.getEntityVisible(a))&&r.updateEntityVisibility(o.entity)||this.view.updateEntity(o.entity)}),i(t.database.events.entityErased,n=>{if(!this._active)return;const o=yx(n.entity).filter(r=>this.view.hasEntity(r.objectId));o.length!==0&&this.view.removeEntity(o.length===1?o[0]:o)}),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(p.AcDbSysVarManager.instance().events.sysVarChanged,n=>{if(!(!this._active||n.database!==this._doc.database)){if(n.name==p.AcDbSystemVariables.PDMODE.toLowerCase()||n.name==p.AcDbSystemVariables.PDSIZE.toLowerCase())this._view.rerenderPoints(n.database.pdmode,n.database.pdsize);else if(n.name==p.AcDbSystemVariables.LWDISPLAY.toLowerCase()){const o=this._view,r=!!n.database.lwdisplay;o.renderer.showLineWeight!==r&&(o.renderer.showLineWeight=r,o.clear(),n.database.regen())}}}),i(t.database.events.dictObjetSet,n=>{this._active&&n.object instanceof p.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 wu(s){return typeof s.hasEntity=="function"&&typeof s.setEntitySceneVisible=="function"}function dL(s,e,t){!s.isObjectHidden(t)||!wu(e)||e.setEntitySceneVisible(t,!1)}function gx(s,e){const t=s.view;if(!wu(t))return 0;const i=s.doc,n=i.database;let o=0;for(const r of e){if(i.isObjectHidden(r))continue;const a=n.tables.blockTable.getEntityById(r);!(a!=null&&a.visibility)||!t.hasEntity(r)||t.setEntitySceneVisible(r,!1)&&(i.addHiddenObject(r),o++)}return o>0&&t.selectionSet.clear(),o}function bx(s){const e=s.view;if(!wu(e))return 0;const t=s.doc,i=t.database,n=t.takeHiddenObjects();let o=0;for(const r of n){const a=i.tables.blockTable.getEntityById(r);!a||!e.hasEntity(r)||e.setEntitySceneVisible(r,a.visibility)&&o++}return e.selectionSet.clear(),o}const vu=500,uL=/[̀-ͯ]/g,xu=/\s+/g;function Xs(s,e=!1){let t=s.normalize("NFKC").replace(xu," ").trim();return e||(t=t.normalize("NFD").replace(uL,"").toLowerCase()),t}function qs(s){const e=/\\(U\+[0-9a-fA-F]{4}|[PX~SfFHWTQCcAaRrpLlOoKk\\{}])|[{}]/g,t=[];let i=0,n=!1,o;for(;o=e.exec(s);){t.push(s.slice(i,o.index));const r=o[1];let a="";if(r!=null&&r.startsWith("U+"))a=String.fromCharCode(parseInt(r.slice(2),16));else if(r==="P"||r==="X"||r==="~")a=" ";else if(r==="\\"||r==="{"||r==="}")a=r;else if(r&&/[SfFHWTQCcAaRrp]/.test(r)){const l=n?-1:s.indexOf(";",e.lastIndex);if(l===-1)n=!0,a=o[0];else{if(r==="S"){const c=s.slice(e.lastIndex,l),d=c.search(/[\^#/]/);if(d===-1)a=c;else{const h=c.slice(d+1);a=c.slice(0,d)+(h?`/${h}`:"")}}e.lastIndex=l+1}}t.push(a),i=e.lastIndex}return t.push(s.slice(i)),wx(t.join("")).replace(xu," ").trim()}function wx(s){return s.replace(/%%[cC]/g,"Ø").replace(/%%[dD]/g,"°").replace(/%%[pP]/g,"±")}function La(s){return typeof s=="string"?wx(s).normalize("NFKC").replace(xu," ").trim():""}function vx(s,e,t){var r;const i=t.get(e);if(i!==void 0)return i;const n=(r=s.tables.layerTable)==null?void 0:r.getAt(e),o=!(n!=null&&n.isOff||n!=null&&n.isFrozen);return t.set(e,o),o}function Ta(s){const e=s.position??s.location??s.textLocation??s.textPosition??{x:0,y:0};return{x:Number(e.x)||0,y:Number(e.y)||0}}function hL(s,e){const t=new Array(16);for(let i=0;i<4;i++)for(let n=0;n<4;n++){let o=0;for(let r=0;r<4;r++)o+=s[r*4+n]*e[i*4+r];t[i*4+n]=o}return t}function xx(s,e){if(!s)return{x:e.x,y:e.y};const t=Number(e.z)||0;return{x:s[0]*e.x+s[4]*e.y+s[8]*t+s[12],y:s[1]*e.x+s[5]*e.y+s[9]*t+s[13]}}function kx(s){var e;try{const t=(e=s.blockTransform)==null?void 0:e.elements;return Array.isArray(t)&&t.length===16?t:void 0}catch{return}}function pL(s,e){var n,o;let t;try{t=s.geometricExtents}catch{return}if(!t||!isFinite((n=t.min)==null?void 0:n.x)||!isFinite((o=t.max)==null?void 0:o.x))return;if(!e)return{min:{...t.min},max:{...t.max}};const i=[{x:t.min.x,y:t.min.y},{x:t.max.x,y:t.min.y},{x:t.min.x,y:t.max.y},{x:t.max.x,y:t.max.y}].map(r=>xx(e,r));return{min:{x:Math.min(...i.map(r=>r.x)),y:Math.min(...i.map(r=>r.y))},max:{x:Math.max(...i.map(r=>r.x)),y:Math.max(...i.map(r=>r.y))}}}const mL=8;function Sx(s,e,t,i={}){var w,S,x,_;const n=i.matchCase===!0,o=i.maxResults??vu,r=Xs(t,n),a={hits:[],truncated:!1};if(!r)return a;const l=s.tables.blockTable.getIdAt(e);if(!l)return a;const c=new Map,d=C=>C!==""&&Xs(C,n).includes(r);let h=!1;const f=C=>{if(a.hits.length>=o){a.truncated=!0,h=!0;return}a.hits.push(C)},y=(C,T,L,N,B,A,O={})=>{const P=pL(L,A);f({entityId:C.entity.objectId,textEntityId:`${T}/${L.objectId}`,kind:N,text:B,layer:C.layer,position:xx(A,Ta(L)),...P?{extents:P}:{},...O})},g=(C,T,L,N,B,A)=>{var O,P,E;for(const I of C){if(h)return;const j=I.dxfTypeName;if(j!=="TEXT"&&j!=="MTEXT"&&j!=="INSERT"&&j!=="ATTRIB"&&j!=="ATTDEF"||I.visibility===!1||j==="ATTDEF"&&(I.isInvisible||!(I.isConst||I.isConstMTextAttribute))||I.layer&&I.layer!=="0"&&!vx(s,I.layer,c))continue;if(j==="INSERT"){if(B>=mL)continue;const ee=kx(I),Z=L&&ee?hL(L,ee):ee??L,re=`${N}/${I.objectId}`;for(const pt of((O=I.attributeIterator)==null?void 0:O.call(I))??[]){if(h)return;if(pt.visibility===!1||pt.isInvisible)continue;const Be=La(pt.textString);d(Be)&&y(T,re,pt,"block",Be,L,{tag:pt.tag,blockName:I.blockName})}const Se=I.blockName;if(!Se||A.has(Se))continue;const Ke=(E=(P=s.tables.blockTable).getAt)==null?void 0:E.call(P,Se);if(!Ke)continue;A.add(Se),g(Ke.newIterator(),T,Z,re,B+1,A),A.delete(Se);continue}const Y=j==="MTEXT"||j==="ATTDEF"&&I.isConstMTextAttribute&&I.mtext?qs(String((j==="MTEXT"?I:I.mtext).contents??"")):La(I.textString);d(Y)&&y(T,N,I,T.kind,Y,L,j==="ATTDEF"?{tag:I.tag}:{})}},b=C=>{var T,L;try{const N=C.blockTableRecord;if(N!=null&&N.newIterator)return N;const B=C.dimBlockId,A=B?s.tables.blockTable.getIdAt(B):void 0;if(A)return A;const O=C.blockName;return O?(L=(T=s.tables.blockTable).getAt)==null?void 0:L.call(T,O):void 0}catch{return}};for(const C of l.newIterator()){if(h)break;const T=C.dxfTypeName;if(T!=="TEXT"&&T!=="MTEXT"&&T!=="INSERT"&&T!=="DIMENSION"&&T!=="MULTILEADER"&&T!=="ACAD_TABLE"||C.visibility===!1||!vx(s,C.layer,c))continue;if(T==="INSERT"){for(const A of((w=C.attributeIterator)==null?void 0:w.call(C))??[]){if(h)break;if(A.visibility===!1||A.isInvisible)continue;const O=La(A.textString);d(O)&&f({entityId:C.objectId,textEntityId:A.objectId,kind:"attribute",text:O,tag:A.tag,blockName:C.blockName,layer:C.layer,position:Ta(A)})}const N=C.blockName,B=N?(x=(S=s.tables.blockTable).getAt)==null?void 0:x.call(S,N):void 0;B&&!h&&g(B.newIterator(),{entity:C,kind:"block",layer:C.layer},kx(C),String(C.objectId),1,new Set([N]));continue}if(T==="DIMENSION"||T==="ACAD_TABLE"){const N=T==="DIMENSION"?"dimension":"table",B={entity:C,kind:N,layer:C.layer},A=b(C),O=a.hits.length;if(A&&g(A.newIterator(),B,void 0,String(C.objectId),1,new Set),A&&a.hits.length>O)continue;const P=[];if(T==="DIMENSION"){const E=String(C.dimensionText??"");E&&E!=="<>"&&E!==" "&&P.push(qs(E.replace("<>","")))}else{const E=Number(C.numRows)||0,I=Number(C.numColumns)||0;for(let j=0;j<E;j++)for(let G=0;G<I;G++)try{P.push(qs(String(((_=C.textString)==null?void 0:_.call(C,j,G))??"")))}catch{}}for(const E of P){if(h)break;d(E)&&f({entityId:C.objectId,textEntityId:`${C.objectId}/${a.hits.length}`,kind:N,text:E,layer:C.layer,position:Ta(C)})}continue}const L=T==="MTEXT"||T==="MULTILEADER"?qs(String(C.contents??"")):La(C.textString);d(L)&&f({entityId:C.objectId,textEntityId:C.objectId,kind:T==="MTEXT"?"mtext":T==="MULTILEADER"?"leader":"text",text:L,layer:C.layer,position:Ta(C)})}return a}function fL(s,e,t=!1,i=60){if(s.length<=i)return s;const n=Xs(e,t),o=Xs(s,t).indexOf(n),r=Math.max(0,Math.min(o-15,s.length-i)),a=s.slice(r,r+i);return`${r>0?"…":""}${a}${r+i<s.length?"…":""}`}function Cx(s){var i;const e=(i=s.objects)==null?void 0:i.layout;if(!(e!=null&&e.newIterator))return[];const t=[];for(const n of e.newIterator())n.blockTableRecordId&&t.push({name:n.layoutName??"",btrId:n.blockTableRecordId,tabOrder:Number(n.tabOrder)||0});return t.sort((n,o)=>n.tabOrder-o.tabOrder||n.name.localeCompare(o.name))}function yL(s,e,t){const i=t.maxResults??vu,n=Cx(s),o=l=>{var c;return((c=n.find(d=>d.btrId===l))==null?void 0:c.name)??""};let r;t.scope==="layout"||n.length===0?r=[{btrId:t.currentLayoutId,name:o(t.currentLayoutId)}]:r=n.map(l=>({btrId:l.btrId,name:l.name}));const a={hits:[],truncated:!1};for(const l of r){const c=Sx(s,l.btrId,e,{matchCase:t.matchCase,maxResults:i-a.hits.length});for(const d of c.hits)a.hits.push({...d,layoutId:l.btrId,layoutName:l.name});if(c.truncated){a.truncated=!0;break}}return a}function Ax(s,e,t){var g;const i=s.tables.blockTable.getIdAt(e),n=(g=i==null?void 0:i.getIdAt)==null?void 0:g.call(i,t.entityId);let o=n;if(t.kind==="attribute"&&(n!=null&&n.attributeIterator)){for(const b of n.attributeIterator())if(b.objectId===t.textEntityId){o=b;break}}let r,a;try{const b=t.extents??(o==null?void 0:o.geometricExtents);if(!b||!isFinite(b.min.x)||!isFinite(b.max.x))throw new Error("no extents");r=b.min,a=b.max}catch{r=a=t.position}const l=(r.x+a.x)/2,c=(r.y+a.y)/2,d=a.x-r.x,h=a.y-r.y,f=Math.max(d*3,h*10,.001),y=Math.max(h*3,f/4,.001);return{min:{x:l-f/2,y:c-y/2},max:{x:l+f/2,y:c+y/2}}}function gL(s,e,t,i){const n=Number(s.width)||0,o=Number(s.height)||0,r=Math.max(0,(i==null?void 0:i.left)??0),a=Math.max(0,(i==null?void 0:i.right)??0),l=Math.max(0,(i==null?void 0:i.top)??0),c=Math.max(0,(i==null?void 0:i.bottom)??0),d=n-r-a,h=o-l-c;if(!(n>0&&o>0&&r+a+l+c>0&&d>=n*.2&&h>=o*.2&&!!s.worldToScreen&&!!s.screenToWorld)){s.zoomTo(new p.AcGeBox2d(new p.AcGePoint2d(e.min.x,e.min.y),new p.AcGePoint2d(e.max.x,e.max.y)),t);return}const y=(e.min.x+e.max.x)/2,g=(e.min.y+e.max.y)/2,b=(e.max.x-e.min.x)/2*(n/d),w=(e.max.y-e.min.y)/2*(o/h);s.zoomTo(new p.AcGeBox2d(new p.AcGePoint2d(y-b,g-w),new p.AcGePoint2d(y+b,g+w)),t);const S=s.worldToScreen({x:y,y:g}),x=r+d/2,_=l+h/2,C=s.screenToWorld({x:n/2+(S.x-x),y:o/2+(S.y-_)});isFinite(C.x)&&isFinite(C.y)&&(s.center=new p.AcGePoint2d(C.x,C.y))}const ku=new WeakMap;async function bL(s,e,t={}){var a;const i=s.curView,n=(a=s.curDocument)==null?void 0:a.database;if(!i||!n)return"no-document";const o=(ku.get(i)??0)+1;if(ku.set(i,o),i.activeLayoutBtrId!==e.layoutId){if(t.activateLayout===!1)return"layout-mismatch";if(!n.tables.blockTable.getIdAt(e.layoutId))return"layout-missing";if(i.isLayoutInitialized(e.layoutId)||i.markLayoutAsInitialized(e.layoutId),p.acdbHostApplicationServices().layoutManager.setCurrentLayoutBtrId(e.layoutId,n),i.activeLayoutBtrId!==e.layoutId)return"layout-switch-failed";if(await i.waitUntilIdle(t.idleTimeoutMs??15e3),ku.get(i)!==o||i.activeLayoutBtrId!==e.layoutId)return"stale"}const r=Ax(n,e.layoutId,e);return gL(i,r,t.margin??1.1,t.insets),i.selectionSet.clear(),i.selectionSet.add(e.entityId),"navigated"}class wL extends K{async execute(e){p.log.info("Hello from ExamplePlugin!"),p.log.info("Current document:",e.doc),p.log.info("Current view:",e.view)}}class vL{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 wL),this.registeredCommands.push({group:"USER",name:"HELLO"}),p.log.info(`[${this.name}] Plugin loaded successfully`),p.log.info(`[${this.name}] Registered command: HELLO`)}onUnload(e,t){for(const i of this.registeredCommands)t.removeCmd(i.group,i.name);this.registeredCommands=[],p.log.info(`[${this.name}] Plugin unloaded`)}}const _x=[".dxf",".dwg"],Js="local",Su="url",xL="100%",kL="150px";function Px(s,e){return s==null?e:typeof s=="number"?`${s}px`:s}const zn=class zn{constructor(e){if(this.activeView=Js,this.menuOpen=!1,this.disposed=!1,this.unsubManager=null,this.unsubTheme=null,this.onDocPointerDown=null,this.options={...e,cardSize:{...e.cardSize??{}}},zn.ensureStyles(),this.root=document.createElement("div"),this.root.className="ml-ui-file-open",this.root.setAttribute("data-ml-ui-file-open","1"),this.applyTheme(),e.title||e.subtitle){const a=document.createElement("div");if(a.className="ml-ui-file-open-header",e.title){const l=document.createElement("h2");l.className="ml-ui-file-open-title",l.textContent=e.title,a.appendChild(l)}if(e.subtitle){const l=document.createElement("p");l.className="ml-ui-file-open-subtitle",l.textContent=e.subtitle,a.appendChild(l)}this.root.appendChild(a)}if(e.showNewDrawing){const a=document.createElement("button");a.type="button",a.className="ml-ui-file-open-primary",a.textContent=m.t("main.dataSource.newDrawing"),a.addEventListener("click",()=>this.emit({kind:"new-drawing"})),this.root.appendChild(a),this.root.appendChild(this.createDivider())}this.card=document.createElement("div"),this.card.className="ml-ui-file-open-card",this.applyCardSize(),this.root.appendChild(this.card),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept=e.accept??_x.join(","),this.fileInput.className="ml-ui-file-open-input-hidden",this.fileInput.addEventListener("change",()=>{var l;const a=(l=this.fileInput.files)==null?void 0:l[0];this.fileInput.value="",a&&this.isSupportedFileName(a.name)&&this.emitLocal(a)}),this.card.appendChild(this.fileInput),this.contentEl=document.createElement("div"),this.contentEl.className="ml-ui-file-open-body",this.card.appendChild(this.contentEl),this.dropzone=document.createElement("div"),this.dropzone.className="ml-ui-file-open-dropzone",this.dropzone.tabIndex=0,this.dropzone.setAttribute("role","button"),this.dropzone.setAttribute("aria-label",m.t("main.dataSource.dropOrBrowse"));const t=document.createElement("p");t.className="ml-ui-file-open-drop-title",t.append(document.createTextNode(`${m.t("main.dataSource.dropFile")} `));const i=document.createElement("span");i.className="ml-ui-file-open-drop-link",i.textContent=m.t("main.dataSource.browse"),t.appendChild(i);const n=document.createElement("div");n.className="ml-ui-file-open-tags";for(const a of["DWG","DXF"]){const l=document.createElement("span");l.className="ml-ui-file-open-tag",l.textContent=a,n.appendChild(l)}this.dropzone.appendChild(t),this.dropzone.appendChild(n),this.dropzone.addEventListener("click",()=>this.fileInput.click()),this.dropzone.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),this.fileInput.click())}),this.dropzone.addEventListener("dragenter",a=>this.onDrag(a,!0)),this.dropzone.addEventListener("dragover",a=>this.onDrag(a,!0)),this.dropzone.addEventListener("dragleave",a=>this.onDrag(a,!1)),this.dropzone.addEventListener("drop",a=>this.onDrop(a)),this.urlRow=document.createElement("div"),this.urlRow.className="ml-ui-file-open-url-row",this.urlInput=document.createElement("input"),this.urlInput.type="url",this.urlInput.className="ml-ui-file-open-url-input",this.urlInput.placeholder=m.t("main.dataSource.urlPlaceholder"),this.urlInput.autocomplete="off",this.urlInput.spellcheck=!1,this.urlInput.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.submitUrl())});const o=document.createElement("button");o.type="button",o.className="ml-ui-file-open-secondary",o.textContent=m.t("main.dataSource.open"),o.addEventListener("click",()=>this.submitUrl()),this.urlRow.appendChild(this.urlInput),this.urlRow.appendChild(o),this.sourceActionsEl=document.createElement("div"),this.sourceActionsEl.className="ml-ui-file-open-sources";const r=document.createElement("div");r.className="ml-ui-file-open-footer",this.footerBtn=document.createElement("button"),this.footerBtn.type="button",this.footerBtn.className="ml-ui-file-open-footer-btn",this.footerBtn.setAttribute("aria-label",m.t("main.dataSource.source")),this.footerBtn.setAttribute("aria-haspopup","listbox"),this.footerBtn.setAttribute("aria-expanded","false"),this.footerLabel=document.createElement("span"),this.footerLabel.className="ml-ui-file-open-footer-label",this.footerChevron=document.createElement("span"),this.footerChevron.className="ml-ui-file-open-footer-chevron",this.footerChevron.setAttribute("aria-hidden","true"),this.footerChevron.textContent="▾",this.footerBtn.appendChild(this.footerLabel),this.footerBtn.appendChild(this.footerChevron),this.footerBtn.addEventListener("click",a=>{a.stopPropagation(),this.toggleMenu()}),r.appendChild(this.footerBtn),this.card.appendChild(r),this.menuEl=document.createElement("div"),this.menuEl.className="ml-ui-file-open-menu",this.menuEl.hidden=!0,this.menuEl.setAttribute("role","listbox"),this.card.appendChild(this.menuEl),this.onDocPointerDown=a=>{if(!this.menuOpen)return;const l=a.target;l instanceof Node&&(this.card.contains(l)||this.closeMenu())},document.addEventListener("pointerdown",this.onDocPointerDown),this.unsubTheme=Vo(()=>{this.options.theme||this.applyTheme()}),e.host.appendChild(this.root),this.bindManagerEvents(),this.refreshSourceButtons()}get element(){return this.root}refreshSourceButtons(){this.disposed||(this.bindManagerEvents(),this.applyTheme(),this.applyCardSize(),this.syncSourceChrome(),this.renderActiveView())}setTheme(e){this.disposed||(this.options.theme=e,this.applyTheme())}setCardSize(e){this.disposed||(this.options.cardSize={...this.options.cardSize,...e},this.applyCardSize())}dispose(){var e,t;this.disposed||(this.disposed=!0,(e=this.unsubManager)==null||e.call(this),this.unsubManager=null,(t=this.unsubTheme)==null||t.call(this),this.unsubTheme=null,this.onDocPointerDown&&(document.removeEventListener("pointerdown",this.onDocPointerDown),this.onDocPointerDown=null),this.root.remove())}applyTheme(){const e=this.options.theme!=null,t=this.options.theme??Oe(this.options.host);ot(t,this.root,{isolated:e})}applyCardSize(){const e=this.options.cardSize;this.card.style.width=Px(e==null?void 0:e.width,xL),this.card.style.height=Px(e==null?void 0:e.height,kL)}syncSourceChrome(){const e=this.resolveSourceOptions();new Set(e.map(o=>o.value)).has(this.activeView)||(this.activeView=Js,this.closeMenu());const i=e.find(o=>o.value===this.activeView)??e[0];this.footerLabel.textContent=(i==null?void 0:i.label)??"";const n=e.length>1;this.footerBtn.disabled=!n,this.footerBtn.classList.toggle("is-single",!n),this.footerChevron.hidden=!n,n||this.closeMenu(),this.menuEl.replaceChildren();for(const o of e){const r=document.createElement("button");r.type="button",r.className="ml-ui-file-open-menu-item",r.setAttribute("role","option"),r.setAttribute("aria-selected",o.value===this.activeView?"true":"false"),o.value===this.activeView&&r.classList.add("is-active"),r.textContent=o.label,r.addEventListener("click",a=>{a.stopPropagation(),this.selectSource(o.value)}),this.menuEl.appendChild(r)}}selectSource(e){this.activeView=e,this.closeMenu(),this.syncSourceChrome(),this.renderActiveView(),this.maybeAutoSignIn(e)}maybeAutoSignIn(e){if(e===Js||e===Su)return;const t=this.resolveSources().find(n=>n.id===e);if(t){t.requiresAuth&&t.getAuthState()==="signed-out"&&t.signIn().catch(()=>{}).finally(()=>this.refreshSourceButtons());return}const i=this.resolveExtraMenuItems().find(n=>n.sourceId===e&&n.action==="sign-in");i&&this.emit({kind:"data-source",item:i})}toggleMenu(){this.footerBtn.disabled||(this.menuOpen?this.closeMenu():this.openMenu())}openMenu(){this.menuOpen=!0,this.menuEl.hidden=!1,this.footerBtn.setAttribute("aria-expanded","true"),this.footerBtn.classList.add("is-open"),this.footerChevron.textContent="▴"}closeMenu(){this.menuOpen=!1,this.menuEl.hidden=!0,this.footerBtn.setAttribute("aria-expanded","false"),this.footerBtn.classList.remove("is-open"),this.footerChevron.textContent="▾"}resolveSourceOptions(){const e=[{value:Js,label:m.t("main.dataSource.local")}];this.options.showUrl!==!1&&e.push({value:Su,label:m.t("main.dataSource.url")});const t=new Set;for(const i of this.resolveMenuItems())t.has(i.sourceId)||(t.add(i.sourceId),e.push({value:i.sourceId,label:this.resolveSourceLabel(i.sourceId)}));return e}resolveSourceLabel(e){var n;const t=this.resolveSources().find(o=>o.id===e);if(t)return m.t(t.labelKey);const i=this.resolveExtraMenuItems().find(o=>o.sourceId===e);return(n=i==null?void 0:i.labelParams)!=null&&n.name?i.labelParams.name:e}renderActiveView(){if(this.contentEl.replaceChildren(),this.activeView===Js){this.contentEl.appendChild(this.dropzone);return}if(this.activeView===Su){this.contentEl.appendChild(this.urlRow),requestAnimationFrame(()=>this.urlInput.focus());return}this.renderSourceActions(this.activeView),this.contentEl.appendChild(this.sourceActionsEl)}canPickSource(e){const t=this.resolveSources().find(i=>i.id===e);return t?t.requiresAuth?t.getAuthState()==="signed-in":!0:this.resolveExtraMenuItems().some(i=>i.sourceId===e&&i.action==="pick")}buildPickMenuItem(e){const t=this.resolveSourceLabel(e),i=m.t("main.dataSource.openFrom");return{id:`${e}:pick`,sourceId:e,action:"pick",labelKey:"main.dataSource.openFrom",labelParams:{name:t},label:i.includes("{name}")?i.split("{name}").join(t):m.t("main.dataSource.selectFile")}}resolveAccountProfile(e){var r,a,l,c;const t=(a=(r=this.options).getAccountProfile)==null?void 0:a.call(r,e);if(t!=null&&t.displayName)return t;const i=this.resolveSources().find(d=>d.id===e);if(!i||i.getAuthState()!=="signed-in")return;const n=(l=i.getAccountProfile)==null?void 0:l.call(i);if(n!=null&&n.displayName)return n;const o=(c=i.getAccountLabel)==null?void 0:c.call(i);if(o)return{displayName:o}}initialsFromName(e){const t=e.trim().split(/\s+/).filter(Boolean);return t.length===0?"?":t.length===1?t[0].slice(0,2).toUpperCase():`${t[0][0]??""}${t[1][0]??""}`.toUpperCase()}renderSourceActions(e){this.sourceActionsEl.replaceChildren();const t=this.resolveAccountProfile(e);if(t){const o=document.createElement("div");o.className="ml-ui-file-open-account";const r=document.createElement("div");if(r.className="ml-ui-file-open-avatar",t.avatarUrl){const c=document.createElement("img");c.className="ml-ui-file-open-avatar-img",c.src=t.avatarUrl,c.alt="",c.referrerPolicy="no-referrer",r.appendChild(c)}else{const c=document.createElement("span");c.className="ml-ui-file-open-avatar-initials",c.textContent=this.initialsFromName(t.displayName),r.appendChild(c)}const a=document.createElement("div");a.className="ml-ui-file-open-account-text";const l=document.createElement("div");if(l.className="ml-ui-file-open-account-name",l.textContent=t.displayName,a.appendChild(l),t.email&&t.email!==t.displayName){const c=document.createElement("div");c.className="ml-ui-file-open-account-email",c.textContent=t.email,a.appendChild(c)}o.appendChild(r),o.appendChild(a),this.sourceActionsEl.appendChild(o)}const i=document.createElement("button");i.type="button",i.className="ml-ui-file-open-source-btn ml-ui-file-open-source-btn--primary",i.textContent=m.t("main.dataSource.selectFile");const n=this.canPickSource(e);i.disabled=!n,n||(i.title=m.t("main.dataSource.signInRequired")),i.addEventListener("click",()=>{this.canPickSource(e)&&this.emit({kind:"data-source",item:this.buildPickMenuItem(e)})}),this.sourceActionsEl.appendChild(i)}resolveMenuItems(){const e=this.resolveSources().filter(r=>r.id!==wa&&r.id!==iu),t=Sv(e),i=this.resolveExtraMenuItems(),n=new Set(t.map(r=>r.sourceId)),o=i.filter(r=>!n.has(r.sourceId));return[...t,...o]}resolveSources(){var e;return this.options.getSources?this.options.getSources():((e=k.tryGetInstance())==null?void 0:e.dataSourceManager.list())??[]}resolveExtraMenuItems(){const e=this.options.extraMenuItems;return e?typeof e=="function"?e():e:[]}bindManagerEvents(){var i;if(this.unsubManager)return;const e=(i=k.tryGetInstance())==null?void 0:i.dataSourceManager;if(!e)return;const t=()=>this.refreshSourceButtons();e.on("changed",t),e.on("auth-changed",t),this.unsubManager=()=>{e.off("changed",t),e.off("auth-changed",t)}}submitUrl(){const e=this.urlInput.value.trim();if(!e){this.urlInput.focus();return}this.emit({kind:"url",url:e})}onDrag(e,t){e.preventDefault(),e.stopPropagation(),this.dropzone.classList.toggle("is-dragover",t)}onDrop(e){var i,n;this.onDrag(e,!1);const t=(n=(i=e.dataTransfer)==null?void 0:i.files)==null?void 0:n[0];t&&this.isSupportedFileName(t.name)&&this.emitLocal(t)}isSupportedFileName(e){const t=e.toLowerCase();return _x.some(i=>t.endsWith(i))}emitLocal(e){this.emit({kind:"local",file:e})}emit(e){var t,i,n,o,r,a,l,c,d,h;switch((i=(t=this.options).onResult)==null||i.call(t,e),e.kind){case"local":(o=(n=this.options).onLocalFile)==null||o.call(n,e.file);break;case"url":(a=(r=this.options).onUrl)==null||a.call(r,e.url);break;case"data-source":(c=(l=this.options).onDataSourceAction)==null||c.call(l,e.item);break;case"new-drawing":(h=(d=this.options).onNewDrawing)==null||h.call(d);break}}createDivider(){const e=document.createElement("p");e.className="ml-ui-file-open-divider",e.setAttribute("aria-hidden","true");const t=document.createElement("span");return t.textContent=m.t("main.dataSource.or"),e.appendChild(t),e}static ensureStyles(){if(typeof document>"u"||document.getElementById(zn.styleId))return;const e=document.createElement("style");e.id=zn.styleId,e.textContent=`
2660
2660
  .ml-ui-file-open {
2661
2661
  display: flex;
2662
2662
  flex-direction: column;